Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / webcrypto / algorithms / aes_kw.cc
blob89ef6d3b122f26b16e84f8a82db96b526d812ac2
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/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"
19 namespace webcrypto {
21 namespace {
23 const EVP_AEAD* GetAesKwAlgorithmFromKeySize(size_t key_size_bytes) {
24 switch (key_size_bytes) {
25 case 16:
26 return EVP_aead_aes_128_key_wrap();
27 case 32:
28 return EVP_aead_aes_256_key_wrap();
29 default:
30 return NULL;
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
52 CryptoData(), // iv
53 CryptoData(), // additional_data
54 GetAesKwAlgorithmFromKeySize(raw_key.size()),
55 buffer);
58 class AesKwImplementation : public AesAlgorithm {
59 public:
60 AesKwImplementation()
61 : AesAlgorithm(
62 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
63 "KW") {}
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);
80 } // namespace
82 scoped_ptr<AlgorithmImplementation> CreateAesKwImplementation() {
83 return make_scoped_ptr(new AesKwImplementation);
86 } // namespace webcrypto