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/evp.h>
8 #include "base/logging.h"
9 #include "base/numerics/safe_math.h"
10 #include "base/stl_util.h"
11 #include "components/webcrypto/algorithms/aes.h"
12 #include "components/webcrypto/algorithms/util_openssl.h"
13 #include "components/webcrypto/crypto_data.h"
14 #include "components/webcrypto/key.h"
15 #include "components/webcrypto/status.h"
16 #include "crypto/openssl_util.h"
17 #include "crypto/scoped_openssl_types.h"
23 const EVP_AEAD
* GetAesKwAlgorithmFromKeySize(size_t key_size_bytes
) {
24 switch (key_size_bytes
) {
26 return EVP_aead_aes_128_key_wrap();
28 return EVP_aead_aes_256_key_wrap();
34 Status
AesKwEncryptDecrypt(EncryptOrDecrypt mode
,
35 const blink::WebCryptoAlgorithm
& algorithm
,
36 const blink::WebCryptoKey
& key
,
37 const CryptoData
& data
,
38 std::vector
<uint8_t>* buffer
) {
39 // These length checks are done in order to give a more specific error. These
40 // are not required for correctness.
41 if ((mode
== ENCRYPT
&& data
.byte_length() < 16) ||
42 (mode
== DECRYPT
&& data
.byte_length() < 24)) {
43 return Status::ErrorDataTooSmall();
45 if (data
.byte_length() % 8)
46 return Status::ErrorInvalidAesKwDataLength();
48 const std::vector
<uint8_t>& raw_key
= GetSymmetricKeyData(key
);
50 return AeadEncryptDecrypt(mode
, raw_key
, data
,
51 8, // tag_length_bytes
53 CryptoData(), // additional_data
54 GetAesKwAlgorithmFromKeySize(raw_key
.size()),
58 class AesKwImplementation
: public AesAlgorithm
{
62 blink::WebCryptoKeyUsageWrapKey
| blink::WebCryptoKeyUsageUnwrapKey
,
65 Status
Encrypt(const blink::WebCryptoAlgorithm
& algorithm
,
66 const blink::WebCryptoKey
& key
,
67 const CryptoData
& data
,
68 std::vector
<uint8_t>* buffer
) const override
{
69 return AesKwEncryptDecrypt(ENCRYPT
, algorithm
, key
, data
, buffer
);
72 Status
Decrypt(const blink::WebCryptoAlgorithm
& algorithm
,
73 const blink::WebCryptoKey
& key
,
74 const CryptoData
& data
,
75 std::vector
<uint8_t>* buffer
) const override
{
76 return AesKwEncryptDecrypt(DECRYPT
, algorithm
, key
, data
, buffer
);
82 scoped_ptr
<AlgorithmImplementation
> CreateAesKwImplementation() {
83 return make_scoped_ptr(new AesKwImplementation
);
86 } // namespace webcrypto