1// Copyright (c) 2011 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 <openssl/aes.h>
8#include <openssl/evp.h>
9
10#include "base/logging.h"
11#include "base/strings/string_util.h"
12#include "crypto/openssl_util.h"
13#include "crypto/symmetric_key.h"
14
15namespace crypto {
16
17namespace {
18
19const EVP_CIPHER* GetCipherForKey(SymmetricKey* key) {
20  switch (key->key().length()) {
21    case 16: return EVP_aes_128_cbc();
22    case 32: return EVP_aes_256_cbc();
23    default: return NULL;
24  }
25}
26
27// On destruction this class will cleanup the ctx, and also clear the OpenSSL
28// ERR stack as a convenience.
29class ScopedCipherCTX {
30 public:
31  explicit ScopedCipherCTX() {
32    EVP_CIPHER_CTX_init(&ctx_);
33  }
34  ~ScopedCipherCTX() {
35    EVP_CIPHER_CTX_cleanup(&ctx_);
36    ClearOpenSSLERRStack(FROM_HERE);
37  }
38  EVP_CIPHER_CTX* get() { return &ctx_; }
39
40 private:
41  EVP_CIPHER_CTX ctx_;
42};
43
44}  // namespace
45
46Encryptor::Encryptor()
47    : key_(NULL),
48      mode_(CBC) {
49}
50
51Encryptor::~Encryptor() {
52}
53
54bool Encryptor::Init(SymmetricKey* key,
55                     Mode mode,
56                     const base::StringPiece& iv) {
57  DCHECK(key);
58  DCHECK(mode == CBC || mode == CTR);
59
60  EnsureOpenSSLInit();
61  if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
62    return false;
63
64  if (GetCipherForKey(key) == NULL)
65    return false;
66
67  key_ = key;
68  mode_ = mode;
69  iv.CopyToString(&iv_);
70  return true;
71}
72
73bool Encryptor::Encrypt(const base::StringPiece& plaintext,
74                        std::string* ciphertext) {
75  CHECK(!plaintext.empty() || (mode_ == CBC));
76  return (mode_ == CTR) ?
77      CryptCTR(true, plaintext, ciphertext) :
78      Crypt(true, plaintext, ciphertext);
79}
80
81bool Encryptor::Decrypt(const base::StringPiece& ciphertext,
82                        std::string* plaintext) {
83  CHECK(!ciphertext.empty());
84  return (mode_ == CTR) ?
85      CryptCTR(false, ciphertext, plaintext) :
86      Crypt(false, ciphertext, plaintext);
87}
88
89bool Encryptor::Crypt(bool do_encrypt,
90                      const base::StringPiece& input,
91                      std::string* output) {
92  DCHECK(key_);  // Must call Init() before En/De-crypt.
93  // Work on the result in a local variable, and then only transfer it to
94  // |output| on success to ensure no partial data is returned.
95  std::string result;
96  output->clear();
97
98  const EVP_CIPHER* cipher = GetCipherForKey(key_);
99  DCHECK(cipher);  // Already handled in Init();
100
101  const std::string& key = key_->key();
102  DCHECK_EQ(EVP_CIPHER_iv_length(cipher), iv_.length());
103  DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length());
104
105  ScopedCipherCTX ctx;
106  if (!EVP_CipherInit_ex(ctx.get(), cipher, NULL,
107                         reinterpret_cast<const uint8*>(key.data()),
108                         reinterpret_cast<const uint8*>(iv_.data()),
109                         do_encrypt))
110    return false;
111
112  // When encrypting, add another block size of space to allow for any padding.
113  const size_t output_size = input.size() + (do_encrypt ? iv_.size() : 0);
114  CHECK_GT(output_size, 0u);
115  CHECK_GT(output_size + 1, input.size());
116  uint8* out_ptr = reinterpret_cast<uint8*>(WriteInto(&result,
117                                                      output_size + 1));
118  int out_len;
119  if (!EVP_CipherUpdate(ctx.get(), out_ptr, &out_len,
120                        reinterpret_cast<const uint8*>(input.data()),
121                        input.length()))
122    return false;
123
124  // Write out the final block plus padding (if any) to the end of the data
125  // just written.
126  int tail_len;
127  if (!EVP_CipherFinal_ex(ctx.get(), out_ptr + out_len, &tail_len))
128    return false;
129
130  out_len += tail_len;
131  DCHECK_LE(out_len, static_cast<int>(output_size));
132  result.resize(out_len);
133
134  output->swap(result);
135  return true;
136}
137
138bool Encryptor::CryptCTR(bool do_encrypt,
139                         const base::StringPiece& input,
140                         std::string* output) {
141  if (!counter_.get()) {
142    LOG(ERROR) << "Counter value not set in CTR mode.";
143    return false;
144  }
145
146  AES_KEY aes_key;
147  if (AES_set_encrypt_key(reinterpret_cast<const uint8*>(key_->key().data()),
148                          key_->key().size() * 8, &aes_key) != 0) {
149    return false;
150  }
151
152  const size_t out_size = input.size();
153  CHECK_GT(out_size, 0u);
154  CHECK_GT(out_size + 1, input.size());
155
156  std::string result;
157  uint8* out_ptr = reinterpret_cast<uint8*>(WriteInto(&result, out_size + 1));
158
159  uint8_t ivec[AES_BLOCK_SIZE] = { 0 };
160  uint8_t ecount_buf[AES_BLOCK_SIZE] = { 0 };
161  unsigned int block_offset = 0;
162
163  counter_->Write(ivec);
164
165  AES_ctr128_encrypt(reinterpret_cast<const uint8*>(input.data()), out_ptr,
166                     input.size(), &aes_key, ivec, ecount_buf, &block_offset);
167
168  // AES_ctr128_encrypt() updates |ivec|. Update the |counter_| here.
169  SetCounter(base::StringPiece(reinterpret_cast<const char*>(ivec),
170                               AES_BLOCK_SIZE));
171
172  output->swap(result);
173  return true;
174}
175
176}  // namespace crypto
177