encryptor.cc 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. #include "crypto/encryptor.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include "base/logging.h"
  8. #include "base/strings/string_util.h"
  9. #include "base/sys_byteorder.h"
  10. #include "crypto/openssl_util.h"
  11. #include "crypto/symmetric_key.h"
  12. #include "third_party/boringssl/src/include/openssl/aes.h"
  13. #include "third_party/boringssl/src/include/openssl/evp.h"
  14. namespace crypto {
  15. namespace {
  16. const EVP_CIPHER* GetCipherForKey(const SymmetricKey* key) {
  17. switch (key->key().length()) {
  18. case 16: return EVP_aes_128_cbc();
  19. case 32: return EVP_aes_256_cbc();
  20. default:
  21. return nullptr;
  22. }
  23. }
  24. } // namespace
  25. /////////////////////////////////////////////////////////////////////////////
  26. // Encryptor Implementation.
  27. Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
  28. Encryptor::~Encryptor() = default;
  29. bool Encryptor::Init(const SymmetricKey* key, Mode mode, base::StringPiece iv) {
  30. return Init(key, mode, base::as_bytes(base::make_span(iv)));
  31. }
  32. bool Encryptor::Init(const SymmetricKey* key,
  33. Mode mode,
  34. base::span<const uint8_t> iv) {
  35. DCHECK(key);
  36. DCHECK(mode == CBC || mode == CTR);
  37. EnsureOpenSSLInit();
  38. if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
  39. return false;
  40. // CTR mode passes the starting counter separately, via SetCounter().
  41. if (mode == CTR && !iv.empty())
  42. return false;
  43. if (GetCipherForKey(key) == nullptr)
  44. return false;
  45. key_ = key;
  46. mode_ = mode;
  47. iv_.assign(iv.begin(), iv.end());
  48. return true;
  49. }
  50. bool Encryptor::Encrypt(base::StringPiece plaintext, std::string* ciphertext) {
  51. return CryptString(/*do_encrypt=*/true, plaintext, ciphertext);
  52. }
  53. bool Encryptor::Encrypt(base::span<const uint8_t> plaintext,
  54. std::vector<uint8_t>* ciphertext) {
  55. return CryptBytes(/*do_encrypt=*/true, plaintext, ciphertext);
  56. }
  57. bool Encryptor::Decrypt(base::StringPiece ciphertext, std::string* plaintext) {
  58. return CryptString(/*do_encrypt=*/false, ciphertext, plaintext);
  59. }
  60. bool Encryptor::Decrypt(base::span<const uint8_t> ciphertext,
  61. std::vector<uint8_t>* plaintext) {
  62. return CryptBytes(/*do_encrypt=*/false, ciphertext, plaintext);
  63. }
  64. bool Encryptor::SetCounter(base::StringPiece counter) {
  65. return SetCounter(base::as_bytes(base::make_span(counter)));
  66. }
  67. bool Encryptor::SetCounter(base::span<const uint8_t> counter) {
  68. if (mode_ != CTR)
  69. return false;
  70. if (counter.size() != 16u)
  71. return false;
  72. iv_.assign(counter.begin(), counter.end());
  73. return true;
  74. }
  75. bool Encryptor::CryptString(bool do_encrypt,
  76. base::StringPiece input,
  77. std::string* output) {
  78. std::string result(MaxOutput(do_encrypt, input.size()), '\0');
  79. absl::optional<size_t> len =
  80. (mode_ == CTR)
  81. ? CryptCTR(do_encrypt, base::as_bytes(base::make_span(input)),
  82. base::as_writable_bytes(base::make_span(result)))
  83. : Crypt(do_encrypt, base::as_bytes(base::make_span(input)),
  84. base::as_writable_bytes(base::make_span(result)));
  85. if (!len)
  86. return false;
  87. result.resize(*len);
  88. *output = std::move(result);
  89. return true;
  90. }
  91. bool Encryptor::CryptBytes(bool do_encrypt,
  92. base::span<const uint8_t> input,
  93. std::vector<uint8_t>* output) {
  94. std::vector<uint8_t> result(MaxOutput(do_encrypt, input.size()));
  95. absl::optional<size_t> len = (mode_ == CTR)
  96. ? CryptCTR(do_encrypt, input, result)
  97. : Crypt(do_encrypt, input, result);
  98. if (!len)
  99. return false;
  100. result.resize(*len);
  101. *output = std::move(result);
  102. return true;
  103. }
  104. size_t Encryptor::MaxOutput(bool do_encrypt, size_t length) {
  105. size_t result = length + ((do_encrypt && mode_ == CBC) ? 16 : 0);
  106. CHECK_GE(result, length); // Overflow
  107. return result;
  108. }
  109. absl::optional<size_t> Encryptor::Crypt(bool do_encrypt,
  110. base::span<const uint8_t> input,
  111. base::span<uint8_t> output) {
  112. DCHECK(key_); // Must call Init() before En/De-crypt.
  113. const EVP_CIPHER* cipher = GetCipherForKey(key_);
  114. DCHECK(cipher); // Already handled in Init();
  115. const std::string& key = key_->key();
  116. DCHECK_EQ(EVP_CIPHER_iv_length(cipher), iv_.size());
  117. DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.size());
  118. OpenSSLErrStackTracer err_tracer(FROM_HERE);
  119. bssl::ScopedEVP_CIPHER_CTX ctx;
  120. if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr,
  121. reinterpret_cast<const uint8_t*>(key.data()),
  122. iv_.data(), do_encrypt)) {
  123. return absl::nullopt;
  124. }
  125. // Encrypting needs a block size of space to allow for any padding.
  126. CHECK_GE(output.size(), input.size() + (do_encrypt ? iv_.size() : 0));
  127. int out_len;
  128. if (!EVP_CipherUpdate(ctx.get(), output.data(), &out_len, input.data(),
  129. input.size()))
  130. return absl::nullopt;
  131. // Write out the final block plus padding (if any) to the end of the data
  132. // just written.
  133. int tail_len;
  134. if (!EVP_CipherFinal_ex(ctx.get(), output.data() + out_len, &tail_len))
  135. return absl::nullopt;
  136. out_len += tail_len;
  137. DCHECK_LE(out_len, static_cast<int>(output.size()));
  138. return out_len;
  139. }
  140. absl::optional<size_t> Encryptor::CryptCTR(bool do_encrypt,
  141. base::span<const uint8_t> input,
  142. base::span<uint8_t> output) {
  143. if (iv_.size() != AES_BLOCK_SIZE) {
  144. LOG(ERROR) << "Counter value not set in CTR mode.";
  145. return absl::nullopt;
  146. }
  147. AES_KEY aes_key;
  148. if (AES_set_encrypt_key(reinterpret_cast<const uint8_t*>(key_->key().data()),
  149. key_->key().size() * 8, &aes_key) != 0) {
  150. return absl::nullopt;
  151. }
  152. uint8_t ecount_buf[AES_BLOCK_SIZE] = { 0 };
  153. unsigned int block_offset = 0;
  154. // |output| must have room for |input|.
  155. CHECK_GE(output.size(), input.size());
  156. // Note AES_ctr128_encrypt() will update |iv_|. However, this method discards
  157. // |ecount_buf| and |block_offset|, so this is not quite a streaming API.
  158. AES_ctr128_encrypt(input.data(), output.data(), input.size(), &aes_key,
  159. iv_.data(), ecount_buf, &block_offset);
  160. return input.size();
  161. }
  162. } // namespace crypto