1 // Copyright 2014 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/owner_key_util_impl.h"
10 #include "base/files/file_util.h"
11 #include "base/logging.h"
12 #include "base/system/sys_info.h"
13 #include "build/build_config.h"
14 #include "build/chromeos_buildflags.h"
15 #include "crypto/nss_key_util.h"
19 static const uint16_t kKeySizeInBits = 2048;
21 OwnerKeyUtilImpl::OwnerKeyUtilImpl(const base::FilePath& public_key_file)
22 : public_key_file_(public_key_file) {}
24 OwnerKeyUtilImpl::~OwnerKeyUtilImpl() = default;
26 scoped_refptr<PublicKey> OwnerKeyUtilImpl::ImportPublicKey() {
27 // Get the file size (must fit in a 32 bit int for NSS).
29 if (!base::GetFileSize(public_key_file_, &file_size)) {
30 #if BUILDFLAG(IS_CHROMEOS_ASH)
31 LOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS())
32 << "Could not get size of " << public_key_file_.value();
33 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
36 if (file_size > static_cast<int64_t>(std::numeric_limits<int>::max())) {
37 LOG(ERROR) << public_key_file_.value() << "is " << file_size
38 << "bytes!!! Too big!";
41 int32_t safe_file_size = static_cast<int32_t>(file_size);
43 std::vector<uint8_t> key_data;
44 key_data.resize(safe_file_size);
46 if (safe_file_size == 0) {
47 LOG(WARNING) << "Public key file is empty. This seems wrong.";
51 // Get the key data off of disk
53 base::ReadFile(public_key_file_, reinterpret_cast<char*>(key_data.data()),
55 if (data_read != safe_file_size) {
59 return base::MakeRefCounted<ownership::PublicKey>(
60 /*is_persisted=*/true, std::move(key_data));
63 crypto::ScopedSECKEYPrivateKey OwnerKeyUtilImpl::GenerateKeyPair(
67 PK11RSAGenParams param;
68 param.keySizeInBits = kKeySizeInBits;
70 SECKEYPublicKey* public_key_ptr = nullptr;
72 crypto::ScopedSECKEYPrivateKey key(PK11_GenerateKeyPair(
73 slot, CKM_RSA_PKCS_KEY_PAIR_GEN, ¶m, &public_key_ptr,
74 PR_TRUE /* permanent */, PR_TRUE /* sensitive */, nullptr));
75 crypto::ScopedSECKEYPublicKey public_key(public_key_ptr);
79 crypto::ScopedSECKEYPrivateKey OwnerKeyUtilImpl::FindPrivateKeyInSlot(
80 const std::vector<uint8_t>& key,
85 crypto::ScopedSECKEYPrivateKey private_key(
86 crypto::FindNSSKeyFromPublicKeyInfoInSlot(key, slot));
87 if (!private_key || SECKEY_GetPrivateKeyType(private_key.get()) != rsaKey)
92 bool OwnerKeyUtilImpl::IsPublicKeyPresent() {
93 return base::PathExists(public_key_file_);
96 } // namespace ownership