1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "crypto/symmetric_key.h"
6
7 #include <memory>
8 #include <string>
9
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13
TEST(SymmetricKeyTest,GenerateRandomKey)14 TEST(SymmetricKeyTest, GenerateRandomKey) {
15 std::unique_ptr<crypto::SymmetricKey> key(
16 crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
17 ASSERT_TRUE(key);
18 EXPECT_EQ(32U, key->key().size());
19
20 // Do it again and check that the keys are different.
21 // (Note: this has a one-in-10^77 chance of failure!)
22 std::unique_ptr<crypto::SymmetricKey> key2(
23 crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
24 ASSERT_TRUE(key2);
25 EXPECT_EQ(32U, key2->key().size());
26 EXPECT_NE(key->key(), key2->key());
27 }
28
TEST(SymmetricKeyTest,ImportGeneratedKey)29 TEST(SymmetricKeyTest, ImportGeneratedKey) {
30 std::unique_ptr<crypto::SymmetricKey> key1(
31 crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
32 ASSERT_TRUE(key1);
33
34 std::unique_ptr<crypto::SymmetricKey> key2(
35 crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, key1->key()));
36 ASSERT_TRUE(key2);
37
38 EXPECT_EQ(key1->key(), key2->key());
39 }
40
TEST(SymmetricKeyTest,ImportDerivedKey)41 TEST(SymmetricKeyTest, ImportDerivedKey) {
42 std::unique_ptr<crypto::SymmetricKey> key1(
43 crypto::SymmetricKey::DeriveKeyFromPasswordUsingPbkdf2(
44 crypto::SymmetricKey::HMAC_SHA1, "password", "somesalt", 1024, 128));
45 ASSERT_TRUE(key1);
46
47 std::unique_ptr<crypto::SymmetricKey> key2(crypto::SymmetricKey::Import(
48 crypto::SymmetricKey::HMAC_SHA1, key1->key()));
49 ASSERT_TRUE(key2);
50
51 EXPECT_EQ(key1->key(), key2->key());
52 }
53