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.
6 #include <openssl/evp.h>
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "components/webcrypto/crypto_data.h"
11 #include "components/webcrypto/openssl/aes_algorithm_openssl.h"
12 #include "components/webcrypto/openssl/key_openssl.h"
13 #include "components/webcrypto/openssl/util_openssl.h"
14 #include "components/webcrypto/status.h"
15 #include "components/webcrypto/webcrypto_util.h"
16 #include "crypto/openssl_util.h"
17 #include "crypto/scoped_openssl_types.h"
18 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
24 const EVP_AEAD
* GetAesGcmAlgorithmFromKeySize(size_t key_size_bytes
) {
25 switch (key_size_bytes
) {
27 return EVP_aead_aes_128_gcm();
29 return EVP_aead_aes_256_gcm();
35 Status
AesGcmEncryptDecrypt(EncryptOrDecrypt mode
,
36 const blink::WebCryptoAlgorithm
& algorithm
,
37 const blink::WebCryptoKey
& key
,
38 const CryptoData
& data
,
39 std::vector
<uint8_t>* buffer
) {
40 const std::vector
<uint8_t>& raw_key
=
41 SymKeyOpenSsl::Cast(key
)->raw_key_data();
42 const blink::WebCryptoAesGcmParams
* params
= algorithm
.aesGcmParams();
44 unsigned int tag_length_bits
;
45 Status status
= GetAesGcmTagLengthInBits(params
, &tag_length_bits
);
49 return AeadEncryptDecrypt(
50 mode
, raw_key
, data
, tag_length_bits
/ 8, CryptoData(params
->iv()),
51 CryptoData(params
->optionalAdditionalData()),
52 GetAesGcmAlgorithmFromKeySize(raw_key
.size()), buffer
);
55 class AesGcmImplementation
: public AesAlgorithm
{
57 AesGcmImplementation() : AesAlgorithm("GCM") {}
59 Status
Encrypt(const blink::WebCryptoAlgorithm
& algorithm
,
60 const blink::WebCryptoKey
& key
,
61 const CryptoData
& data
,
62 std::vector
<uint8_t>* buffer
) const override
{
63 return AesGcmEncryptDecrypt(ENCRYPT
, algorithm
, key
, data
, buffer
);
66 Status
Decrypt(const blink::WebCryptoAlgorithm
& algorithm
,
67 const blink::WebCryptoKey
& key
,
68 const CryptoData
& data
,
69 std::vector
<uint8_t>* buffer
) const override
{
70 return AesGcmEncryptDecrypt(DECRYPT
, algorithm
, key
, data
, buffer
);
76 AlgorithmImplementation
* CreatePlatformAesGcmImplementation() {
77 return new AesGcmImplementation
;
80 } // namespace webcrypto