Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / webcrypto / algorithms / aes_gcm.cc
blob57fa77f71cc82eeb3867b4e4ba0de2f551aab175
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>
6 #include <vector>
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "components/webcrypto/algorithms/aes.h"
11 #include "components/webcrypto/algorithms/util_openssl.h"
12 #include "components/webcrypto/crypto_data.h"
13 #include "components/webcrypto/key.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"
20 namespace webcrypto {
22 namespace {
24 const EVP_AEAD* GetAesGcmAlgorithmFromKeySize(size_t key_size_bytes) {
25 switch (key_size_bytes) {
26 case 16:
27 return EVP_aead_aes_128_gcm();
28 case 32:
29 return EVP_aead_aes_256_gcm();
30 default:
31 return NULL;
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 = GetSymmetricKeyData(key);
41 const blink::WebCryptoAesGcmParams* params = algorithm.aesGcmParams();
43 // The WebCrypto spec defines the default value for the tag length, as well as
44 // the allowed values for tag length.
45 unsigned int tag_length_bits = 128;
46 if (params->hasTagLengthBits()) {
47 tag_length_bits = params->optionalTagLengthBits();
48 if (tag_length_bits != 32 && tag_length_bits != 64 &&
49 tag_length_bits != 96 && tag_length_bits != 104 &&
50 tag_length_bits != 112 && tag_length_bits != 120 &&
51 tag_length_bits != 128) {
52 return Status::ErrorInvalidAesGcmTagLength();
56 return AeadEncryptDecrypt(
57 mode, raw_key, data, tag_length_bits / 8, CryptoData(params->iv()),
58 CryptoData(params->optionalAdditionalData()),
59 GetAesGcmAlgorithmFromKeySize(raw_key.size()), buffer);
62 class AesGcmImplementation : public AesAlgorithm {
63 public:
64 AesGcmImplementation() : AesAlgorithm("GCM") {}
66 Status Encrypt(const blink::WebCryptoAlgorithm& algorithm,
67 const blink::WebCryptoKey& key,
68 const CryptoData& data,
69 std::vector<uint8_t>* buffer) const override {
70 return AesGcmEncryptDecrypt(ENCRYPT, algorithm, key, data, buffer);
73 Status Decrypt(const blink::WebCryptoAlgorithm& algorithm,
74 const blink::WebCryptoKey& key,
75 const CryptoData& data,
76 std::vector<uint8_t>* buffer) const override {
77 return AesGcmEncryptDecrypt(DECRYPT, algorithm, key, data, buffer);
81 } // namespace
83 scoped_ptr<AlgorithmImplementation> CreateAesGcmImplementation() {
84 return make_scoped_ptr(new AesGcmImplementation);
87 } // namespace webcrypto