1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "crypto/encryptor.h"
10 #include "base/logging.h"
11 #include "base/strings/string_util.h"
12 #include "base/sys_byteorder.h"
13 #include "crypto/openssl_util.h"
14 #include "crypto/symmetric_key.h"
15 #include "third_party/boringssl/src/include/openssl/aes.h"
16 #include "third_party/boringssl/src/include/openssl/evp.h"
22 const EVP_CIPHER* GetCipherForKey(const SymmetricKey* key) {
23 switch (key->key().length()) {
24 case 16: return EVP_aes_128_cbc();
25 case 32: return EVP_aes_256_cbc();
31 // On destruction this class will cleanup the ctx, and also clear the OpenSSL
32 // ERR stack as a convenience.
33 class ScopedCipherCTX {
36 EVP_CIPHER_CTX_init(&ctx_);
39 EVP_CIPHER_CTX_cleanup(&ctx_);
40 ClearOpenSSLERRStack(FROM_HERE);
42 EVP_CIPHER_CTX* get() { return &ctx_; }
50 /////////////////////////////////////////////////////////////////////////////
51 // Encyptor::Counter Implementation.
52 Encryptor::Counter::Counter(base::StringPiece counter) {
53 CHECK(sizeof(counter_) == counter.length());
55 memcpy(&counter_, counter.data(), sizeof(counter_));
58 Encryptor::Counter::~Counter() = default;
60 bool Encryptor::Counter::Increment() {
61 uint64_t low_num = base::NetToHost64(counter_.components64[1]);
62 uint64_t new_low_num = low_num + 1;
63 counter_.components64[1] = base::HostToNet64(new_low_num);
65 // If overflow occured then increment the most significant component.
66 if (new_low_num < low_num) {
67 counter_.components64[0] =
68 base::HostToNet64(base::NetToHost64(counter_.components64[0]) + 1);
71 // TODO(hclam): Return false if counter value overflows.
75 void Encryptor::Counter::Write(void* buf) {
76 uint8_t* buf_ptr = reinterpret_cast<uint8_t*>(buf);
77 memcpy(buf_ptr, &counter_, sizeof(counter_));
80 size_t Encryptor::Counter::GetLengthInBytes() const {
81 return sizeof(counter_);
84 /////////////////////////////////////////////////////////////////////////////
85 // Encryptor Implementation.
87 Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
89 Encryptor::~Encryptor() = default;
91 bool Encryptor::Init(const SymmetricKey* key, Mode mode, base::StringPiece iv) {
93 DCHECK(mode == CBC || mode == CTR);
96 if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
99 if (GetCipherForKey(key) == nullptr)
104 iv.CopyToString(&iv_);
108 bool Encryptor::Encrypt(base::StringPiece plaintext, std::string* ciphertext) {
109 CHECK(!plaintext.empty() || (mode_ == CBC));
110 return (mode_ == CTR) ?
111 CryptCTR(true, plaintext, ciphertext) :
112 Crypt(true, plaintext, ciphertext);
115 bool Encryptor::Decrypt(base::StringPiece ciphertext, std::string* plaintext) {
116 CHECK(!ciphertext.empty());
117 return (mode_ == CTR) ?
118 CryptCTR(false, ciphertext, plaintext) :
119 Crypt(false, ciphertext, plaintext);
122 bool Encryptor::SetCounter(base::StringPiece counter) {
125 if (counter.length() != 16u)
128 counter_.reset(new Counter(counter));
132 bool Encryptor::Crypt(bool do_encrypt,
133 base::StringPiece input,
134 std::string* output) {
135 DCHECK(key_); // Must call Init() before En/De-crypt.
136 // Work on the result in a local variable, and then only transfer it to
137 // |output| on success to ensure no partial data is returned.
141 const EVP_CIPHER* cipher = GetCipherForKey(key_);
142 DCHECK(cipher); // Already handled in Init();
144 const std::string& key = key_->key();
145 DCHECK_EQ(EVP_CIPHER_iv_length(cipher), iv_.length());
146 DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length());
149 if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr,
150 reinterpret_cast<const uint8_t*>(key.data()),
151 reinterpret_cast<const uint8_t*>(iv_.data()),
155 // When encrypting, add another block size of space to allow for any padding.
156 const size_t output_size = input.size() + (do_encrypt ? iv_.size() : 0);
157 CHECK_GT(output_size, 0u);
158 CHECK_GT(output_size + 1, input.size());
160 reinterpret_cast<uint8_t*>(base::WriteInto(&result, output_size + 1));
162 if (!EVP_CipherUpdate(ctx.get(), out_ptr, &out_len,
163 reinterpret_cast<const uint8_t*>(input.data()),
167 // Write out the final block plus padding (if any) to the end of the data
170 if (!EVP_CipherFinal_ex(ctx.get(), out_ptr + out_len, &tail_len))
174 DCHECK_LE(out_len, static_cast<int>(output_size));
175 result.resize(out_len);
177 output->swap(result);
181 bool Encryptor::CryptCTR(bool do_encrypt,
182 base::StringPiece input,
183 std::string* output) {
184 if (!counter_.get()) {
185 LOG(ERROR) << "Counter value not set in CTR mode.";
190 if (AES_set_encrypt_key(reinterpret_cast<const uint8_t*>(key_->key().data()),
191 key_->key().size() * 8, &aes_key) != 0) {
195 const size_t out_size = input.size();
196 CHECK_GT(out_size, 0u);
197 CHECK_GT(out_size + 1, input.size());
201 reinterpret_cast<uint8_t*>(base::WriteInto(&result, out_size + 1));
203 uint8_t ivec[AES_BLOCK_SIZE] = { 0 };
204 uint8_t ecount_buf[AES_BLOCK_SIZE] = { 0 };
205 unsigned int block_offset = 0;
207 counter_->Write(ivec);
209 AES_ctr128_encrypt(reinterpret_cast<const uint8_t*>(input.data()), out_ptr,
210 input.size(), &aes_key, ivec, ecount_buf, &block_offset);
212 // AES_ctr128_encrypt() updates |ivec|. Update the |counter_| here.
213 SetCounter(base::StringPiece(reinterpret_cast<const char*>(ivec),
216 output->swap(result);
220 } // namespace crypto