blob: a58522c931113a04461b743af8af71f1e3610ae7 [file] [log] [blame]
[email protected]9eb7b11b2012-03-28 20:19:311// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]2377cdee2011-06-24 20:46:062// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "crypto/encryptor.h"
6
avidd373b8b2015-12-21 21:34:437#include <stddef.h>
8#include <stdint.h>
9
[email protected]2377cdee2011-06-24 20:46:0610#include "base/logging.h"
svaldez22de42fe2016-04-21 19:42:2211#include "base/strings/string_util.h"
[email protected]0e6f6192011-12-28 23:18:2112#include "base/sys_byteorder.h"
svaldez22de42fe2016-04-21 19:42:2213#include "crypto/openssl_util.h"
14#include "crypto/symmetric_key.h"
tfarina29a3a1742016-10-28 18:47:3315#include "third_party/boringssl/src/include/openssl/aes.h"
16#include "third_party/boringssl/src/include/openssl/evp.h"
[email protected]2377cdee2011-06-24 20:46:0617
18namespace crypto {
19
svaldez22de42fe2016-04-21 19:42:2220namespace {
21
Chris Mumfordea3b6c192017-06-09 18:33:1322const EVP_CIPHER* GetCipherForKey(const SymmetricKey* key) {
svaldez22de42fe2016-04-21 19:42:2223 switch (key->key().length()) {
24 case 16: return EVP_aes_128_cbc();
25 case 32: return EVP_aes_256_cbc();
rsleeviffe5a132016-06-28 01:51:5226 default:
27 return nullptr;
svaldez22de42fe2016-04-21 19:42:2228 }
29}
30
31// On destruction this class will cleanup the ctx, and also clear the OpenSSL
32// ERR stack as a convenience.
33class ScopedCipherCTX {
34 public:
davidben6004dc52017-02-03 04:15:2935 ScopedCipherCTX() {
svaldez22de42fe2016-04-21 19:42:2236 EVP_CIPHER_CTX_init(&ctx_);
37 }
38 ~ScopedCipherCTX() {
39 EVP_CIPHER_CTX_cleanup(&ctx_);
40 ClearOpenSSLERRStack(FROM_HERE);
41 }
42 EVP_CIPHER_CTX* get() { return &ctx_; }
43
44 private:
45 EVP_CIPHER_CTX ctx_;
46};
47
48} // namespace
49
[email protected]2377cdee2011-06-24 20:46:0650/////////////////////////////////////////////////////////////////////////////
51// Encyptor::Counter Implementation.
David Benjamincda45eb2017-11-06 18:16:5252Encryptor::Counter::Counter(base::StringPiece counter) {
[email protected]2377cdee2011-06-24 20:46:0653 CHECK(sizeof(counter_) == counter.length());
54
55 memcpy(&counter_, counter.data(), sizeof(counter_));
56}
57
Chris Watkinsa850a302017-11-30 03:53:4958Encryptor::Counter::~Counter() = default;
[email protected]2377cdee2011-06-24 20:46:0659
60bool Encryptor::Counter::Increment() {
avidd373b8b2015-12-21 21:34:4361 uint64_t low_num = base::NetToHost64(counter_.components64[1]);
62 uint64_t new_low_num = low_num + 1;
[email protected]9eb7b11b2012-03-28 20:19:3163 counter_.components64[1] = base::HostToNet64(new_low_num);
[email protected]2377cdee2011-06-24 20:46:0664
65 // If overflow occured then increment the most significant component.
66 if (new_low_num < low_num) {
67 counter_.components64[0] =
[email protected]9eb7b11b2012-03-28 20:19:3168 base::HostToNet64(base::NetToHost64(counter_.components64[0]) + 1);
[email protected]2377cdee2011-06-24 20:46:0669 }
70
71 // TODO(hclam): Return false if counter value overflows.
72 return true;
73}
74
75void Encryptor::Counter::Write(void* buf) {
avidd373b8b2015-12-21 21:34:4376 uint8_t* buf_ptr = reinterpret_cast<uint8_t*>(buf);
[email protected]2377cdee2011-06-24 20:46:0677 memcpy(buf_ptr, &counter_, sizeof(counter_));
78}
79
80size_t Encryptor::Counter::GetLengthInBytes() const {
81 return sizeof(counter_);
82}
83
84/////////////////////////////////////////////////////////////////////////////
svaldez22de42fe2016-04-21 19:42:2285// Encryptor Implementation.
86
rsleeviffe5a132016-06-28 01:51:5287Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
svaldez22de42fe2016-04-21 19:42:2288
Chris Watkinsa850a302017-11-30 03:53:4989Encryptor::~Encryptor() = default;
svaldez22de42fe2016-04-21 19:42:2290
David Benjamincda45eb2017-11-06 18:16:5291bool Encryptor::Init(const SymmetricKey* key, Mode mode, base::StringPiece iv) {
svaldez22de42fe2016-04-21 19:42:2292 DCHECK(key);
93 DCHECK(mode == CBC || mode == CTR);
94
95 EnsureOpenSSLInit();
96 if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
97 return false;
98
rsleeviffe5a132016-06-28 01:51:5299 if (GetCipherForKey(key) == nullptr)
svaldez22de42fe2016-04-21 19:42:22100 return false;
101
102 key_ = key;
103 mode_ = mode;
Jan Wilken Dörriec15b4bc2020-01-30 07:04:12104 iv_ = std::string(iv);
svaldez22de42fe2016-04-21 19:42:22105 return true;
106}
107
David Benjamincda45eb2017-11-06 18:16:52108bool Encryptor::Encrypt(base::StringPiece plaintext, std::string* ciphertext) {
svaldez22de42fe2016-04-21 19:42:22109 CHECK(!plaintext.empty() || (mode_ == CBC));
110 return (mode_ == CTR) ?
111 CryptCTR(true, plaintext, ciphertext) :
112 Crypt(true, plaintext, ciphertext);
113}
114
David Benjamincda45eb2017-11-06 18:16:52115bool Encryptor::Decrypt(base::StringPiece ciphertext, std::string* plaintext) {
svaldez22de42fe2016-04-21 19:42:22116 CHECK(!ciphertext.empty());
117 return (mode_ == CTR) ?
118 CryptCTR(false, ciphertext, plaintext) :
119 Crypt(false, ciphertext, plaintext);
120}
[email protected]2377cdee2011-06-24 20:46:06121
David Benjamincda45eb2017-11-06 18:16:52122bool Encryptor::SetCounter(base::StringPiece counter) {
[email protected]2377cdee2011-06-24 20:46:06123 if (mode_ != CTR)
124 return false;
125 if (counter.length() != 16u)
126 return false;
127
128 counter_.reset(new Counter(counter));
129 return true;
130}
131
svaldez22de42fe2016-04-21 19:42:22132bool Encryptor::Crypt(bool do_encrypt,
David Benjamincda45eb2017-11-06 18:16:52133 base::StringPiece input,
svaldez22de42fe2016-04-21 19:42:22134 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.
138 std::string result;
139 output->clear();
140
141 const EVP_CIPHER* cipher = GetCipherForKey(key_);
142 DCHECK(cipher); // Already handled in Init();
143
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());
147
148 ScopedCipherCTX ctx;
rsleeviffe5a132016-06-28 01:51:52149 if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr,
150 reinterpret_cast<const uint8_t*>(key.data()),
151 reinterpret_cast<const uint8_t*>(iv_.data()),
152 do_encrypt))
svaldez22de42fe2016-04-21 19:42:22153 return false;
154
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());
159 uint8_t* out_ptr =
160 reinterpret_cast<uint8_t*>(base::WriteInto(&result, output_size + 1));
161 int out_len;
162 if (!EVP_CipherUpdate(ctx.get(), out_ptr, &out_len,
163 reinterpret_cast<const uint8_t*>(input.data()),
164 input.length()))
165 return false;
166
167 // Write out the final block plus padding (if any) to the end of the data
168 // just written.
169 int tail_len;
170 if (!EVP_CipherFinal_ex(ctx.get(), out_ptr + out_len, &tail_len))
171 return false;
172
173 out_len += tail_len;
174 DCHECK_LE(out_len, static_cast<int>(output_size));
175 result.resize(out_len);
176
177 output->swap(result);
178 return true;
179}
180
181bool Encryptor::CryptCTR(bool do_encrypt,
David Benjamincda45eb2017-11-06 18:16:52182 base::StringPiece input,
svaldez22de42fe2016-04-21 19:42:22183 std::string* output) {
184 if (!counter_.get()) {
185 LOG(ERROR) << "Counter value not set in CTR mode.";
186 return false;
187 }
188
189 AES_KEY aes_key;
190 if (AES_set_encrypt_key(reinterpret_cast<const uint8_t*>(key_->key().data()),
191 key_->key().size() * 8, &aes_key) != 0) {
192 return false;
193 }
194
195 const size_t out_size = input.size();
196 CHECK_GT(out_size, 0u);
197 CHECK_GT(out_size + 1, input.size());
198
199 std::string result;
200 uint8_t* out_ptr =
201 reinterpret_cast<uint8_t*>(base::WriteInto(&result, out_size + 1));
202
203 uint8_t ivec[AES_BLOCK_SIZE] = { 0 };
204 uint8_t ecount_buf[AES_BLOCK_SIZE] = { 0 };
205 unsigned int block_offset = 0;
206
207 counter_->Write(ivec);
208
209 AES_ctr128_encrypt(reinterpret_cast<const uint8_t*>(input.data()), out_ptr,
210 input.size(), &aes_key, ivec, ecount_buf, &block_offset);
211
212 // AES_ctr128_encrypt() updates |ivec|. Update the |counter_| here.
213 SetCounter(base::StringPiece(reinterpret_cast<const char*>(ivec),
214 AES_BLOCK_SIZE));
215
216 output->swap(result);
217 return true;
218}
219
[email protected]2377cdee2011-06-24 20:46:06220} // namespace crypto