1 // Copyright 2014 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 <openssl/aes.h>
6 #include <openssl/evp.h>
8 #include "base/logging.h"
9 #include "base/macros.h"
10 #include "base/numerics/safe_math.h"
11 #include "base/stl_util.h"
12 #include "components/webcrypto/algorithms/aes.h"
13 #include "components/webcrypto/algorithms/util_openssl.h"
14 #include "components/webcrypto/crypto_data.h"
15 #include "components/webcrypto/key.h"
16 #include "components/webcrypto/status.h"
17 #include "components/webcrypto/webcrypto_util.h"
18 #include "crypto/openssl_util.h"
19 #include "crypto/scoped_openssl_types.h"
20 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
26 const EVP_CIPHER
* GetAESCipherByKeyLength(size_t key_length_bytes
) {
27 // BoringSSL does not support 192-bit AES keys.
28 switch (key_length_bytes
) {
30 return EVP_aes_128_ctr();
32 return EVP_aes_256_ctr();
38 // Encrypts/decrypts given a 128-bit counter.
40 // |output| must be a pointer to a buffer which has a length of at least
41 // |input.byte_length()|.
42 Status
AesCtrEncrypt128BitCounter(const EVP_CIPHER
* cipher
,
43 const CryptoData
& raw_key
,
44 const CryptoData
& input
,
45 const CryptoData
& counter
,
48 DCHECK_EQ(16u, counter
.byte_length());
50 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
51 crypto::ScopedOpenSSL
<EVP_CIPHER_CTX
, EVP_CIPHER_CTX_free
> context(
52 EVP_CIPHER_CTX_new());
55 return Status::OperationError();
57 if (!EVP_CipherInit_ex(context
.get(), cipher
, NULL
, raw_key
.bytes(),
58 counter
.bytes(), ENCRYPT
)) {
59 return Status::OperationError();
63 if (!EVP_CipherUpdate(context
.get(), output
, &output_len
, input
.bytes(),
64 input
.byte_length())) {
65 return Status::OperationError();
67 int final_output_chunk_len
= 0;
68 if (!EVP_CipherFinal_ex(context
.get(), output
+ output_len
,
69 &final_output_chunk_len
)) {
70 return Status::OperationError();
73 output_len
+= final_output_chunk_len
;
74 if (static_cast<unsigned int>(output_len
) != input
.byte_length())
75 return Status::ErrorUnexpected();
77 return Status::Success();
80 // Returns ceil(a/b), where a and b are integers.
83 return a
== 0 ? 0 : 1 + (a
- 1) / b
;
86 // Extracts the counter as a BIGNUM. The counter is the rightmost
87 // "counter_length_bits" of the block, interpreted as a big-endian number.
88 crypto::ScopedBIGNUM
GetCounter(const CryptoData
& counter_block
,
89 unsigned int counter_length_bits
) {
90 unsigned int counter_length_remainder_bits
= (counter_length_bits
% 8);
92 // If the counter is a multiple of 8 bits then can call BN_bin2bn() directly.
93 if (counter_length_remainder_bits
== 0) {
94 unsigned int byte_length
= counter_length_bits
/ 8;
95 return crypto::ScopedBIGNUM(BN_bin2bn(
96 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
100 // Otherwise make a copy of the counter and zero out the topmost bits so
101 // BN_bin2bn() can be called with a byte stream.
102 unsigned int byte_length
= CeilDiv(counter_length_bits
, 8u);
103 std::vector
<uint8_t> counter(
104 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
105 counter_block
.bytes() + counter_block
.byte_length());
106 counter
[0] &= ~(0xFF << counter_length_remainder_bits
);
108 return crypto::ScopedBIGNUM(
109 BN_bin2bn(vector_as_array(&counter
), counter
.size(), NULL
));
112 // Returns a counter block with the counter bits all set all zero.
113 std::vector
<uint8_t> BlockWithZeroedCounter(const CryptoData
& counter_block
,
114 unsigned int counter_length_bits
) {
115 unsigned int counter_length_bytes
= counter_length_bits
/ 8;
116 unsigned int counter_length_bits_remainder
= counter_length_bits
% 8;
118 std::vector
<uint8_t> new_counter_block(
119 counter_block
.bytes(),
120 counter_block
.bytes() + counter_block
.byte_length());
122 size_t index
= new_counter_block
.size() - counter_length_bytes
;
123 memset(&new_counter_block
.front() + index
, 0, counter_length_bytes
);
125 if (counter_length_bits_remainder
) {
126 new_counter_block
[index
- 1] &= 0xFF << counter_length_bits_remainder
;
129 return new_counter_block
;
132 // This function does encryption/decryption for AES-CTR (encryption and
133 // decryption are the same).
135 // BoringSSL's interface for AES-CTR differs from that of WebCrypto. In
136 // WebCrypto the caller specifies a 16-byte counter block and designates how
137 // many of the right-most X bits to use as a big-endian counter. Whereas in
138 // BoringSSL the entire counter block is interpreted as a 128-bit counter.
140 // In AES-CTR, the counter block MUST be unique across all messages that are
141 // encrypted/decrypted. WebCrypto expects that the counter can start at any
142 // value, and is therefore permitted to wrap around to zero on overflow.
144 // Some care is taken to fail if the counter wraps back to an earlier value.
145 // However this protection is only enforced during a *single* call to
147 Status
AesCtrEncryptDecrypt(const blink::WebCryptoAlgorithm
& algorithm
,
148 const blink::WebCryptoKey
& key
,
149 const CryptoData
& data
,
150 std::vector
<uint8_t>* buffer
) {
151 const blink::WebCryptoAesCtrParams
* params
= algorithm
.aesCtrParams();
152 const std::vector
<uint8_t>& raw_key
= GetSymmetricKeyData(key
);
154 if (params
->counter().size() != 16)
155 return Status::ErrorIncorrectSizeAesCtrCounter();
157 unsigned int counter_length_bits
= params
->lengthBits();
158 if (counter_length_bits
< 1 || counter_length_bits
> 128)
159 return Status::ErrorInvalidAesCtrCounterLength();
161 // The output of AES-CTR is the same size as the input. However BoringSSL
162 // expects buffer sizes as an "int".
163 base::CheckedNumeric
<int> output_max_len
= data
.byte_length();
164 if (!output_max_len
.IsValid())
165 return Status::ErrorDataTooLarge();
167 const EVP_CIPHER
* const cipher
= GetAESCipherByKeyLength(raw_key
.size());
169 return Status::ErrorUnexpected();
171 const CryptoData
counter_block(params
->counter());
172 buffer
->resize(output_max_len
.ValueOrDie());
174 // The total number of possible counter values is pow(2, counter_length_bits)
175 crypto::ScopedBIGNUM
num_counter_values(BN_new());
176 if (!BN_lshift(num_counter_values
.get(), BN_value_one(), counter_length_bits
))
177 return Status::ErrorUnexpected();
179 crypto::ScopedBIGNUM current_counter
=
180 GetCounter(counter_block
, counter_length_bits
);
182 // The number of AES blocks needed for encryption/decryption. The counter is
183 // incremented this many times.
184 crypto::ScopedBIGNUM
num_output_blocks(BN_new());
186 num_output_blocks
.get(),
187 CeilDiv(buffer
->size(), static_cast<size_t>(AES_BLOCK_SIZE
)))) {
188 return Status::ErrorUnexpected();
191 // If the counter is going to be incremented more times than there are counter
192 // values, fail. (Repeating values of the counter block is bad).
193 if (BN_cmp(num_output_blocks
.get(), num_counter_values
.get()) > 0)
194 return Status::ErrorAesCtrInputTooLongCounterRepeated();
196 // This is the number of blocks that can be successfully encrypted without
197 // overflowing the counter. Encrypting the subsequent block will need to
198 // reset the counter to zero.
199 crypto::ScopedBIGNUM
num_blocks_until_reset(BN_new());
201 if (!BN_sub(num_blocks_until_reset
.get(), num_counter_values
.get(),
202 current_counter
.get())) {
203 return Status::ErrorUnexpected();
206 // If the counter can be incremented for the entire input without
207 // wrapping-around, do it as a single call into BoringSSL.
208 if (BN_cmp(num_blocks_until_reset
.get(), num_output_blocks
.get()) >= 0) {
209 return AesCtrEncrypt128BitCounter(cipher
, CryptoData(raw_key
), data
,
210 counter_block
, vector_as_array(buffer
));
213 // Otherwise the encryption needs to be done in 2 parts. The first part using
214 // the current counter_block, and the next part resetting the counter portion
215 // of the block to zero.
217 // This is guaranteed to fit in an "unsigned int" because input size in bytes
218 // fits in an "unsigned int".
219 BN_ULONG num_blocks_part1
= BN_get_word(num_blocks_until_reset
.get());
220 BN_ULONG input_size_part1
= num_blocks_part1
* AES_BLOCK_SIZE
;
221 DCHECK_LT(input_size_part1
, data
.byte_length());
223 // Encrypt the first part (before wrap-around).
224 Status status
= AesCtrEncrypt128BitCounter(
225 cipher
, CryptoData(raw_key
), CryptoData(data
.bytes(), input_size_part1
),
226 counter_block
, vector_as_array(buffer
));
227 if (status
.IsError())
230 // Encrypt the second part (after wrap-around).
231 std::vector
<uint8_t> counter_block_part2
=
232 BlockWithZeroedCounter(counter_block
, counter_length_bits
);
234 return AesCtrEncrypt128BitCounter(
235 cipher
, CryptoData(raw_key
),
236 CryptoData(data
.bytes() + input_size_part1
,
237 data
.byte_length() - input_size_part1
),
238 CryptoData(counter_block_part2
),
239 vector_as_array(buffer
) + input_size_part1
);
242 class AesCtrImplementation
: public AesAlgorithm
{
244 AesCtrImplementation() : AesAlgorithm("CTR") {}
246 Status
Encrypt(const blink::WebCryptoAlgorithm
& algorithm
,
247 const blink::WebCryptoKey
& key
,
248 const CryptoData
& data
,
249 std::vector
<uint8_t>* buffer
) const override
{
250 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
253 Status
Decrypt(const blink::WebCryptoAlgorithm
& algorithm
,
254 const blink::WebCryptoKey
& key
,
255 const CryptoData
& data
,
256 std::vector
<uint8_t>* buffer
) const override
{
257 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
263 scoped_ptr
<AlgorithmImplementation
> CreateAesCtrImplementation() {
264 return make_scoped_ptr(new AesCtrImplementation
);
267 } // namespace webcrypto