1 // Copyright 2012 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.
5 #include "components/ownership/mock_owner_key_util.h"
9 #include "base/check.h"
10 #include "base/files/file_path.h"
11 #include "crypto/nss_key_util.h"
12 #include "crypto/nss_util.h"
13 #include "crypto/rsa_private_key.h"
17 static const uint16_t kKeySizeInBits = 2048;
19 MockOwnerKeyUtil::MockOwnerKeyUtil() = default;
21 MockOwnerKeyUtil::~MockOwnerKeyUtil() = default;
23 scoped_refptr<PublicKey> MockOwnerKeyUtil::ImportPublicKey() {
24 return public_key_.empty() ? nullptr
25 : base::MakeRefCounted<ownership::PublicKey>(
26 /*is_persisted=*/true, /*data=*/public_key_);
29 crypto::ScopedSECKEYPrivateKey MockOwnerKeyUtil::GenerateKeyPair(
31 if (generate_key_fail_times_ > 0) {
32 --generate_key_fail_times_;
36 PK11RSAGenParams param;
37 param.keySizeInBits = kKeySizeInBits;
39 SECKEYPublicKey* public_key_ptr = nullptr;
41 crypto::ScopedSECKEYPrivateKey key(PK11_GenerateKeyPair(
42 slot, CKM_RSA_PKCS_KEY_PAIR_GEN, ¶m, &public_key_ptr,
43 PR_TRUE /* permanent */, PR_TRUE /* sensitive */, nullptr));
44 crypto::ScopedSECKEYPublicKey public_key(public_key_ptr);
48 crypto::ScopedSECKEYPrivateKey MockOwnerKeyUtil::FindPrivateKeyInSlot(
49 const std::vector<uint8_t>& key,
53 return crypto::ScopedSECKEYPrivateKey(
54 SECKEY_CopyPrivateKey(private_key_.get()));
57 bool MockOwnerKeyUtil::IsPublicKeyPresent() {
58 return !public_key_.empty();
61 void MockOwnerKeyUtil::Clear() {
66 void MockOwnerKeyUtil::SetPublicKey(const std::vector<uint8_t>& key) {
70 void MockOwnerKeyUtil::SetPublicKeyFromPrivateKey(
71 const crypto::RSAPrivateKey& key) {
72 CHECK(key.ExportPublicKey(&public_key_));
75 void MockOwnerKeyUtil::ImportPrivateKeyAndSetPublicKey(
76 std::unique_ptr<crypto::RSAPrivateKey> key) {
77 crypto::EnsureNSSInit();
79 CHECK(key->ExportPublicKey(&public_key_));
81 std::vector<uint8_t> key_exported;
82 CHECK(key->ExportPrivateKey(&key_exported));
84 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
86 private_key_ = crypto::ImportNSSKeyFromPrivateKeyInfo(
87 slot.get(), key_exported, false /* not permanent */);
91 void MockOwnerKeyUtil::SimulateGenerateKeyFailure(int fail_times) {
92 generate_key_fail_times_ = fail_times;
95 } // namespace ownership