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 "content/child/webcrypto/platform_crypto.h"
8 #include <openssl/aes.h>
9 #include <openssl/evp.h>
10 #include <openssl/hmac.h>
11 #include <openssl/rand.h>
12 #include <openssl/sha.h>
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "content/child/webcrypto/crypto_data.h"
17 #include "content/child/webcrypto/status.h"
18 #include "content/child/webcrypto/webcrypto_util.h"
19 #include "crypto/openssl_util.h"
20 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
21 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
22 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
30 class SymKey
: public Key
{
32 explicit SymKey(const CryptoData
& key_data
)
33 : key_(key_data
.bytes(), key_data
.bytes() + key_data
.byte_length()) {}
35 virtual SymKey
* AsSymKey() OVERRIDE
{ return this; }
36 virtual PublicKey
* AsPublicKey() OVERRIDE
{ return NULL
; }
37 virtual PrivateKey
* AsPrivateKey() OVERRIDE
{ return NULL
; }
38 virtual bool ThreadSafeSerializeForClone(
39 blink::WebVector
<uint8
>* key_data
) OVERRIDE
{
40 key_data
->assign(Uint8VectorStart(key_
), key_
.size());
44 const std::vector
<unsigned char>& key() const { return key_
; }
47 const std::vector
<unsigned char> key_
;
49 DISALLOW_COPY_AND_ASSIGN(SymKey
);
54 const EVP_CIPHER
* GetAESCipherByKeyLength(unsigned int key_length_bytes
) {
55 // OpenSSL supports AES CBC ciphers for only 3 key lengths: 128, 192, 256 bits
56 switch (key_length_bytes
) {
58 return EVP_aes_128_cbc();
60 return EVP_aes_192_cbc();
62 return EVP_aes_256_cbc();
68 const EVP_MD
* GetDigest(blink::WebCryptoAlgorithmId id
) {
70 case blink::WebCryptoAlgorithmIdSha1
:
72 case blink::WebCryptoAlgorithmIdSha256
:
74 case blink::WebCryptoAlgorithmIdSha384
:
76 case blink::WebCryptoAlgorithmIdSha512
:
83 // OpenSSL constants for EVP_CipherInit_ex(), do not change
84 enum CipherOperation
{ kDoDecrypt
= 0, kDoEncrypt
= 1 };
86 Status
AesCbcEncryptDecrypt(EncryptOrDecrypt mode
,
89 const CryptoData
& data
,
90 std::vector
<uint8
>* buffer
) {
91 CipherOperation cipher_operation
=
92 (mode
== ENCRYPT
) ? kDoEncrypt
: kDoDecrypt
;
94 if (data
.byte_length() >= INT_MAX
- AES_BLOCK_SIZE
) {
95 // TODO(padolph): Handle this by chunking the input fed into OpenSSL. Right
96 // now it doesn't make much difference since the one-shot API would end up
97 // blowing out the memory and crashing anyway.
98 return Status::ErrorDataTooLarge();
101 // Note: PKCS padding is enabled by default
102 crypto::ScopedOpenSSL
<EVP_CIPHER_CTX
, EVP_CIPHER_CTX_free
> context(
103 EVP_CIPHER_CTX_new());
106 return Status::OperationError();
108 const EVP_CIPHER
* const cipher
= GetAESCipherByKeyLength(key
->key().size());
111 if (!EVP_CipherInit_ex(context
.get(),
117 return Status::OperationError();
120 // According to the openssl docs, the amount of data written may be as large
121 // as (data_size + cipher_block_size - 1), constrained to a multiple of
122 // cipher_block_size.
123 unsigned int output_max_len
= data
.byte_length() + AES_BLOCK_SIZE
- 1;
124 const unsigned remainder
= output_max_len
% AES_BLOCK_SIZE
;
126 output_max_len
+= AES_BLOCK_SIZE
- remainder
;
127 DCHECK_GT(output_max_len
, data
.byte_length());
129 buffer
->resize(output_max_len
);
131 unsigned char* const buffer_data
= Uint8VectorStart(buffer
);
134 if (!EVP_CipherUpdate(context
.get(),
139 return Status::OperationError();
140 int final_output_chunk_len
= 0;
141 if (!EVP_CipherFinal_ex(
142 context
.get(), buffer_data
+ output_len
, &final_output_chunk_len
)) {
143 return Status::OperationError();
146 const unsigned int final_output_len
=
147 static_cast<unsigned int>(output_len
) +
148 static_cast<unsigned int>(final_output_chunk_len
);
149 DCHECK_LE(final_output_len
, output_max_len
);
151 buffer
->resize(final_output_len
);
153 return Status::Success();
158 class DigestorOpenSSL
: public blink::WebCryptoDigestor
{
160 explicit DigestorOpenSSL(blink::WebCryptoAlgorithmId algorithm_id
)
161 : initialized_(false),
162 digest_context_(EVP_MD_CTX_create()),
163 algorithm_id_(algorithm_id
) {}
165 virtual bool consume(const unsigned char* data
, unsigned int size
) {
166 return ConsumeWithStatus(data
, size
).IsSuccess();
169 Status
ConsumeWithStatus(const unsigned char* data
, unsigned int size
) {
170 crypto::OpenSSLErrStackTracer(FROM_HERE
);
171 Status error
= Init();
172 if (!error
.IsSuccess())
175 if (!EVP_DigestUpdate(digest_context_
.get(), data
, size
))
176 return Status::OperationError();
178 return Status::Success();
181 virtual bool finish(unsigned char*& result_data
,
182 unsigned int& result_data_size
) {
183 Status error
= FinishInternal(result_
, &result_data_size
);
184 if (!error
.IsSuccess())
186 result_data
= result_
;
190 Status
FinishWithVectorAndStatus(std::vector
<uint8
>* result
) {
191 const int hash_expected_size
= EVP_MD_CTX_size(digest_context_
.get());
192 result
->resize(hash_expected_size
);
193 unsigned char* const hash_buffer
= Uint8VectorStart(result
);
194 unsigned int hash_buffer_size
; // ignored
195 return FinishInternal(hash_buffer
, &hash_buffer_size
);
201 return Status::Success();
203 const EVP_MD
* digest_algorithm
= GetDigest(algorithm_id_
);
204 if (!digest_algorithm
)
205 return Status::ErrorUnexpected();
207 if (!digest_context_
.get())
208 return Status::OperationError();
210 if (!EVP_DigestInit_ex(digest_context_
.get(), digest_algorithm
, NULL
))
211 return Status::OperationError();
214 return Status::Success();
217 Status
FinishInternal(unsigned char* result
, unsigned int* result_size
) {
218 crypto::OpenSSLErrStackTracer(FROM_HERE
);
219 Status error
= Init();
220 if (!error
.IsSuccess())
223 const int hash_expected_size
= EVP_MD_CTX_size(digest_context_
.get());
224 if (hash_expected_size
<= 0)
225 return Status::ErrorUnexpected();
226 DCHECK_LE(hash_expected_size
, EVP_MAX_MD_SIZE
);
228 if (!EVP_DigestFinal_ex(digest_context_
.get(), result
, result_size
) ||
229 static_cast<int>(*result_size
) != hash_expected_size
)
230 return Status::OperationError();
232 return Status::Success();
236 crypto::ScopedOpenSSL
<EVP_MD_CTX
, EVP_MD_CTX_destroy
> digest_context_
;
237 blink::WebCryptoAlgorithmId algorithm_id_
;
238 unsigned char result_
[EVP_MAX_MD_SIZE
];
241 Status
ExportKeyRaw(SymKey
* key
, std::vector
<uint8
>* buffer
) {
242 *buffer
= key
->key();
243 return Status::Success();
246 void Init() { crypto::EnsureOpenSSLInit(); }
248 Status
EncryptDecryptAesCbc(EncryptOrDecrypt mode
,
250 const CryptoData
& data
,
251 const CryptoData
& iv
,
252 std::vector
<uint8
>* buffer
) {
253 // TODO(eroman): inline the function here.
254 return AesCbcEncryptDecrypt(mode
, key
, iv
, data
, buffer
);
257 Status
DigestSha(blink::WebCryptoAlgorithmId algorithm
,
258 const CryptoData
& data
,
259 std::vector
<uint8
>* buffer
) {
260 DigestorOpenSSL
digestor(algorithm
);
261 Status error
= digestor
.ConsumeWithStatus(data
.bytes(), data
.byte_length());
262 if (!error
.IsSuccess())
264 return digestor
.FinishWithVectorAndStatus(buffer
);
267 scoped_ptr
<blink::WebCryptoDigestor
> CreateDigestor(
268 blink::WebCryptoAlgorithmId algorithm_id
) {
269 return scoped_ptr
<blink::WebCryptoDigestor
>(
270 new DigestorOpenSSL(algorithm_id
));
273 Status
GenerateSecretKey(const blink::WebCryptoAlgorithm
& algorithm
,
275 blink::WebCryptoKeyUsageMask usage_mask
,
276 unsigned keylen_bytes
,
277 blink::WebCryptoKey
* key
) {
278 // TODO(eroman): Is this right?
279 if (keylen_bytes
== 0)
280 return Status::ErrorGenerateKeyLength();
282 crypto::OpenSSLErrStackTracer(FROM_HERE
);
284 std::vector
<unsigned char> random_bytes(keylen_bytes
, 0);
285 if (!(RAND_bytes(&random_bytes
[0], keylen_bytes
)))
286 return Status::OperationError();
288 blink::WebCryptoKeyAlgorithm key_algorithm
;
289 if (!CreateSecretKeyAlgorithm(algorithm
, keylen_bytes
, &key_algorithm
))
290 return Status::ErrorUnexpected();
292 *key
= blink::WebCryptoKey::create(new SymKey(CryptoData(random_bytes
)),
293 blink::WebCryptoKeyTypeSecret
,
298 return Status::Success();
301 Status
GenerateRsaKeyPair(const blink::WebCryptoAlgorithm
& algorithm
,
303 blink::WebCryptoKeyUsageMask public_key_usage_mask
,
304 blink::WebCryptoKeyUsageMask private_key_usage_mask
,
305 unsigned int modulus_length_bits
,
306 const CryptoData
& public_exponent
,
307 blink::WebCryptoKey
* public_key
,
308 blink::WebCryptoKey
* private_key
) {
309 // TODO(padolph): Placeholder for OpenSSL implementation.
310 // Issue http://crbug.com/267888.
311 return Status::ErrorUnsupported();
314 Status
ImportKeyRaw(const blink::WebCryptoAlgorithm
& algorithm
,
315 const CryptoData
& key_data
,
317 blink::WebCryptoKeyUsageMask usage_mask
,
318 blink::WebCryptoKey
* key
) {
320 blink::WebCryptoKeyAlgorithm key_algorithm
;
321 if (!CreateSecretKeyAlgorithm(
322 algorithm
, key_data
.byte_length(), &key_algorithm
))
323 return Status::ErrorUnexpected();
325 *key
= blink::WebCryptoKey::create(new SymKey(key_data
),
326 blink::WebCryptoKeyTypeSecret
,
331 return Status::Success();
334 Status
SignHmac(SymKey
* key
,
335 const blink::WebCryptoAlgorithm
& hash
,
336 const CryptoData
& data
,
337 std::vector
<uint8
>* buffer
) {
338 const EVP_MD
* digest_algorithm
= GetDigest(hash
.id());
339 if (!digest_algorithm
)
340 return Status::ErrorUnsupported();
341 unsigned int hmac_expected_length
= EVP_MD_size(digest_algorithm
);
343 const std::vector
<unsigned char>& raw_key
= key
->key();
345 // OpenSSL wierdness here.
346 // First, HMAC() needs a void* for the key data, so make one up front as a
347 // cosmetic to avoid a cast. Second, OpenSSL does not like a NULL key,
348 // which will result if the raw_key vector is empty; an entirely valid
349 // case. Handle this specific case by pointing to an empty array.
350 const unsigned char null_key
[] = {};
351 const void* const raw_key_voidp
= raw_key
.size() ? &raw_key
[0] : null_key
;
353 buffer
->resize(hmac_expected_length
);
354 crypto::ScopedOpenSSLSafeSizeBuffer
<EVP_MAX_MD_SIZE
> hmac_result(
355 Uint8VectorStart(buffer
), hmac_expected_length
);
357 crypto::OpenSSLErrStackTracer(FROM_HERE
);
359 unsigned int hmac_actual_length
;
360 unsigned char* const success
= HMAC(digest_algorithm
,
365 hmac_result
.safe_buffer(),
366 &hmac_actual_length
);
367 if (!success
|| hmac_actual_length
!= hmac_expected_length
)
368 return Status::OperationError();
370 return Status::Success();
373 Status
ImportRsaPublicKey(const blink::WebCryptoAlgorithm
& algorithm
,
375 blink::WebCryptoKeyUsageMask usage_mask
,
376 const CryptoData
& modulus_data
,
377 const CryptoData
& exponent_data
,
378 blink::WebCryptoKey
* key
) {
379 // TODO(padolph): Placeholder for OpenSSL implementation.
381 return Status::ErrorUnsupported();
384 Status
ImportRsaPrivateKey(const blink::WebCryptoAlgorithm
& algorithm
,
386 blink::WebCryptoKeyUsageMask usage_mask
,
387 const CryptoData
& modulus
,
388 const CryptoData
& public_exponent
,
389 const CryptoData
& private_exponent
,
390 const CryptoData
& prime1
,
391 const CryptoData
& prime2
,
392 const CryptoData
& exponent1
,
393 const CryptoData
& exponent2
,
394 const CryptoData
& coefficient
,
395 blink::WebCryptoKey
* key
) {
396 // TODO(eroman): http://crbug.com/267888
397 return Status::ErrorUnsupported();
400 Status
EncryptDecryptAesGcm(EncryptOrDecrypt mode
,
402 const CryptoData
& data
,
403 const CryptoData
& iv
,
404 const CryptoData
& additional_data
,
405 unsigned int tag_length_bits
,
406 std::vector
<uint8
>* buffer
) {
407 // TODO(eroman): http://crbug.com/267888
408 return Status::ErrorUnsupported();
411 Status
EncryptRsaOaep(PublicKey
* key
,
412 const blink::WebCryptoAlgorithm
& hash
,
413 const CryptoData
& label
,
414 const CryptoData
& data
,
415 std::vector
<uint8
>* buffer
) {
416 // TODO(eroman): http://crbug.com/267888
417 return Status::ErrorUnsupported();
420 Status
DecryptRsaOaep(PrivateKey
* key
,
421 const blink::WebCryptoAlgorithm
& hash
,
422 const CryptoData
& label
,
423 const CryptoData
& data
,
424 std::vector
<uint8
>* buffer
) {
425 // TODO(eroman): http://crbug.com/267888
426 return Status::ErrorUnsupported();
429 Status
SignRsaSsaPkcs1v1_5(PrivateKey
* key
,
430 const blink::WebCryptoAlgorithm
& hash
,
431 const CryptoData
& data
,
432 std::vector
<uint8
>* buffer
) {
433 // TODO(eroman): http://crbug.com/267888
434 return Status::ErrorUnsupported();
437 // Key is guaranteed to be an RSA SSA key.
438 Status
VerifyRsaSsaPkcs1v1_5(PublicKey
* key
,
439 const blink::WebCryptoAlgorithm
& hash
,
440 const CryptoData
& signature
,
441 const CryptoData
& data
,
442 bool* signature_match
) {
443 // TODO(eroman): http://crbug.com/267888
444 return Status::ErrorUnsupported();
447 Status
ImportKeySpki(const blink::WebCryptoAlgorithm
& algorithm
,
448 const CryptoData
& key_data
,
450 blink::WebCryptoKeyUsageMask usage_mask
,
451 blink::WebCryptoKey
* key
) {
452 // TODO(eroman): http://crbug.com/267888
453 return Status::ErrorUnsupported();
456 Status
ImportKeyPkcs8(const blink::WebCryptoAlgorithm
& algorithm
,
457 const CryptoData
& key_data
,
459 blink::WebCryptoKeyUsageMask usage_mask
,
460 blink::WebCryptoKey
* key
) {
461 // TODO(eroman): http://crbug.com/267888
462 return Status::ErrorUnsupported();
465 Status
ExportKeySpki(PublicKey
* key
, std::vector
<uint8
>* buffer
) {
466 // TODO(eroman): http://crbug.com/267888
467 return Status::ErrorUnsupported();
470 Status
ExportKeyPkcs8(PrivateKey
* key
,
471 const blink::WebCryptoKeyAlgorithm
& key_algorithm
,
472 std::vector
<uint8
>* buffer
) {
473 // TODO(eroman): http://crbug.com/267888
474 return Status::ErrorUnsupported();
477 Status
ExportRsaPublicKey(PublicKey
* key
,
478 std::vector
<uint8
>* modulus
,
479 std::vector
<uint8
>* public_exponent
) {
480 // TODO(eroman): http://crbug.com/267888
481 return Status::ErrorUnsupported();
484 Status
ExportRsaPrivateKey(PrivateKey
* key
,
485 std::vector
<uint8
>* modulus
,
486 std::vector
<uint8
>* public_exponent
,
487 std::vector
<uint8
>* private_exponent
,
488 std::vector
<uint8
>* prime1
,
489 std::vector
<uint8
>* prime2
,
490 std::vector
<uint8
>* exponent1
,
491 std::vector
<uint8
>* exponent2
,
492 std::vector
<uint8
>* coefficient
) {
493 // TODO(eroman): http://crbug.com/267888
494 return Status::ErrorUnsupported();
497 Status
WrapSymKeyAesKw(SymKey
* key
,
498 SymKey
* wrapping_key
,
499 std::vector
<uint8
>* buffer
) {
500 // TODO(eroman): http://crbug.com/267888
501 return Status::ErrorUnsupported();
504 Status
UnwrapSymKeyAesKw(const CryptoData
& wrapped_key_data
,
505 SymKey
* wrapping_key
,
506 const blink::WebCryptoAlgorithm
& algorithm
,
508 blink::WebCryptoKeyUsageMask usage_mask
,
509 blink::WebCryptoKey
* key
) {
510 // TODO(eroman): http://crbug.com/267888
511 return Status::ErrorUnsupported();
514 Status
DecryptAesKw(SymKey
* key
,
515 const CryptoData
& data
,
516 std::vector
<uint8
>* buffer
) {
517 // TODO(eroman): http://crbug.com/267888
518 return Status::ErrorUnsupported();
521 bool ThreadSafeDeserializeKeyForClone(
522 const blink::WebCryptoKeyAlgorithm
& algorithm
,
523 blink::WebCryptoKeyType type
,
525 blink::WebCryptoKeyUsageMask usages
,
526 const CryptoData
& key_data
,
527 blink::WebCryptoKey
* key
) {
528 // TODO(eroman): http://crbug.com/267888
532 } // namespace platform
534 } // namespace webcrypto
536 } // namespace content