1 // Copyright 2015 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 "crypto/aead.h"
9 #include "testing/gtest/include/gtest/gtest.h"
13 const crypto::Aead::AeadAlgorithm kAllAlgorithms[]{
14 crypto::Aead::AES_128_CTR_HMAC_SHA256, crypto::Aead::AES_256_GCM,
15 crypto::Aead::AES_256_GCM_SIV,
18 class AeadTest : public testing::TestWithParam<crypto::Aead::AeadAlgorithm> {};
20 INSTANTIATE_TEST_SUITE_P(All, AeadTest, testing::ValuesIn(kAllAlgorithms));
22 TEST_P(AeadTest, SealOpen) {
23 crypto::Aead::AeadAlgorithm alg = GetParam();
24 crypto::Aead aead(alg);
25 std::string key(aead.KeyLength(), 0);
27 std::string nonce(aead.NonceLength(), 0);
28 std::string plaintext("this is the plaintext");
29 std::string ad("this is the additional data");
30 std::string ciphertext;
31 EXPECT_TRUE(aead.Seal(plaintext, nonce, ad, &ciphertext));
32 EXPECT_LT(0U, ciphertext.size());
34 std::string decrypted;
35 EXPECT_TRUE(aead.Open(ciphertext, nonce, ad, &decrypted));
37 EXPECT_EQ(plaintext, decrypted);
40 TEST_P(AeadTest, SealOpenSpan) {
41 crypto::Aead::AeadAlgorithm alg = GetParam();
42 crypto::Aead aead(alg);
43 std::vector<uint8_t> key(aead.KeyLength(), 0u);
45 std::vector<uint8_t> nonce(aead.NonceLength(), 0u);
46 static constexpr uint8_t kPlaintext[] = "plaintext";
47 static constexpr uint8_t kAdditionalData[] = "additional data input";
48 std::vector<uint8_t> ciphertext =
49 aead.Seal(kPlaintext, nonce, kAdditionalData);
50 EXPECT_LT(sizeof(kPlaintext), ciphertext.size());
52 base::Optional<std::vector<uint8_t>> decrypted =
53 aead.Open(ciphertext, nonce, kAdditionalData);
54 ASSERT_TRUE(decrypted);
55 ASSERT_EQ(decrypted->size(), sizeof(kPlaintext));
56 ASSERT_EQ(0, memcmp(decrypted->data(), kPlaintext, sizeof(kPlaintext)));
58 std::vector<uint8_t> wrong_key(aead.KeyLength(), 1u);
59 crypto::Aead aead_wrong_key(alg);
60 aead_wrong_key.Init(wrong_key);
61 decrypted = aead_wrong_key.Open(ciphertext, nonce, kAdditionalData);
62 EXPECT_FALSE(decrypted);
65 TEST_P(AeadTest, SealOpenWrongKey) {
66 crypto::Aead::AeadAlgorithm alg = GetParam();
67 crypto::Aead aead(alg);
68 std::string key(aead.KeyLength(), 0);
69 std::string wrong_key(aead.KeyLength(), 1);
71 crypto::Aead aead_wrong_key(alg);
72 aead_wrong_key.Init(&wrong_key);
74 std::string nonce(aead.NonceLength(), 0);
75 std::string plaintext("this is the plaintext");
76 std::string ad("this is the additional data");
77 std::string ciphertext;
78 EXPECT_TRUE(aead.Seal(plaintext, nonce, ad, &ciphertext));
79 EXPECT_LT(0U, ciphertext.size());
81 std::string decrypted;
82 EXPECT_FALSE(aead_wrong_key.Open(ciphertext, nonce, ad, &decrypted));
83 EXPECT_EQ(0U, decrypted.size());