1 // Copyright (c) 2011 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.
4
5 #include "chrome/browser/chromeos/login/owner_key_utils.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "base/file_path.h"
11 #include "base/file_util.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_temp_dir.h"
14 #include "crypto/nss_util.h"
15 #include "crypto/nss_util_internal.h"
16 #include "crypto/rsa_private_key.h"
17 #include "testing/gmock/include/gmock/gmock.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19
20 namespace chromeos {
21
22 class OwnerKeyUtilsTest : public ::testing::Test {
23 public:
OwnerKeyUtilsTest()24 OwnerKeyUtilsTest() : utils_(OwnerKeyUtils::Create()) {}
~OwnerKeyUtilsTest()25 virtual ~OwnerKeyUtilsTest() {}
26
SetUp()27 virtual void SetUp() {
28 crypto::OpenPersistentNSSDB();
29 }
30
31 // Key generation parameters.
32 static const uint16 kKeySizeInBits;
33
34 scoped_refptr<OwnerKeyUtils> utils_;
35 };
36
37 // We're generating and using 2048-bit RSA keys.
38 // static
39 const uint16 OwnerKeyUtilsTest::kKeySizeInBits = 2048;
40
TEST_F(OwnerKeyUtilsTest,ExportImportPublicKey)41 TEST_F(OwnerKeyUtilsTest, ExportImportPublicKey) {
42 scoped_ptr<crypto::RSAPrivateKey> pair(
43 crypto::RSAPrivateKey::CreateSensitive(kKeySizeInBits));
44 ASSERT_NE(pair.get(), reinterpret_cast<crypto::RSAPrivateKey*>(NULL));
45
46 // Export public key to file.
47 ScopedTempDir tmpdir;
48 FilePath tmpfile;
49 ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
50 ASSERT_TRUE(file_util::CreateTemporaryFileInDir(tmpdir.path(), &tmpfile));
51 ASSERT_TRUE(utils_->ExportPublicKeyToFile(pair.get(), tmpfile));
52
53 // Export public key, so that we can compare it to the one we get off disk.
54 std::vector<uint8> public_key;
55 ASSERT_TRUE(pair->ExportPublicKey(&public_key));
56 std::vector<uint8> from_disk;
57 ASSERT_TRUE(utils_->ImportPublicKey(tmpfile, &from_disk));
58
59 std::vector<uint8>::iterator pubkey_it;
60 std::vector<uint8>::iterator disk_it;
61 for (pubkey_it = public_key.begin(), disk_it = from_disk.begin();
62 pubkey_it < public_key.end();
63 pubkey_it++, disk_it++) {
64 EXPECT_EQ(*pubkey_it, *disk_it);
65 }
66 }
67
68 } // namespace chromeos
69