Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / crypto / encryptor.cc
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.
4
5 #include "crypto/encryptor.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
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"
17
18 namespace crypto {
19
20 namespace {
21
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();
26     default:
27       return nullptr;
28   }
29 }
30
31 // On destruction this class will cleanup the ctx, and also clear the OpenSSL
32 // ERR stack as a convenience.
33 class ScopedCipherCTX {
34  public:
35   ScopedCipherCTX() {
36     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
50 /////////////////////////////////////////////////////////////////////////////
51 // Encyptor::Counter Implementation.
52 Encryptor::Counter::Counter(base::StringPiece counter) {
53   CHECK(sizeof(counter_) == counter.length());
54
55   memcpy(&counter_, counter.data(), sizeof(counter_));
56 }
57
58 Encryptor::Counter::~Counter() = default;
59
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);
64
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);
69   }
70
71   // TODO(hclam): Return false if counter value overflows.
72   return true;
73 }
74
75 void Encryptor::Counter::Write(void* buf) {
76   uint8_t* buf_ptr = reinterpret_cast<uint8_t*>(buf);
77   memcpy(buf_ptr, &counter_, sizeof(counter_));
78 }
79
80 size_t Encryptor::Counter::GetLengthInBytes() const {
81   return sizeof(counter_);
82 }
83
84 /////////////////////////////////////////////////////////////////////////////
85 // Encryptor Implementation.
86
87 Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
88
89 Encryptor::~Encryptor() = default;
90
91 bool Encryptor::Init(const SymmetricKey* key, Mode mode, base::StringPiece iv) {
92   DCHECK(key);
93   DCHECK(mode == CBC || mode == CTR);
94
95   EnsureOpenSSLInit();
96   if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
97     return false;
98
99   if (GetCipherForKey(key) == nullptr)
100     return false;
101
102   key_ = key;
103   mode_ = mode;
104   iv.CopyToString(&iv_);
105   return true;
106 }
107
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);
113 }
114
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);
120 }
121
122 bool Encryptor::SetCounter(base::StringPiece counter) {
123   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
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.
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;
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()),
152                          do_encrypt))
153     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
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.";
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
220 }  // namespace crypto