1 // Copyright 2014 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 "net/test/cert_test_util.h"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "crypto/nss_util.h"
13 #include "crypto/rsa_private_key.h"
14 #include "net/cert/cert_type.h"
18 scoped_ptr
<crypto::RSAPrivateKey
> ImportSensitiveKeyFromFile(
19 const base::FilePath
& dir
,
20 const std::string
& key_filename
,
22 #if defined(USE_OPENSSL)
23 // TODO(davidben): Port RSAPrivateKey::CreateSensitiveFromPrivateKeyInfo away
24 // from RSAPrivateKey so it doesn't make assumptions about the internal crypto
25 // library. Instead, return a ScopedSECKEYPrivateKey or have this function
26 // just return bool. https://crbug.com/478777
30 base::FilePath key_path
= dir
.AppendASCII(key_filename
);
31 std::string key_pkcs8
;
32 bool success
= base::ReadFileToString(key_path
, &key_pkcs8
);
34 LOG(ERROR
) << "Failed to read file " << key_path
.value();
35 return scoped_ptr
<crypto::RSAPrivateKey
>();
38 const uint8
* key_pkcs8_begin
=
39 reinterpret_cast<const uint8
*>(key_pkcs8
.data());
40 std::vector
<uint8
> key_vector(key_pkcs8_begin
,
41 key_pkcs8_begin
+ key_pkcs8
.length());
43 scoped_ptr
<crypto::RSAPrivateKey
> private_key(
44 crypto::RSAPrivateKey::CreateSensitiveFromPrivateKeyInfo(slot
,
46 LOG_IF(ERROR
, !private_key
) << "Could not create key from file "
48 return private_key
.Pass();
52 bool ImportClientCertToSlot(const scoped_refptr
<X509Certificate
>& cert
,
54 std::string nickname
= cert
->GetDefaultNickname(USER_CERT
);
56 crypto::AutoNSSWriteLock lock
;
57 SECStatus rv
= PK11_ImportCert(slot
,
58 cert
->os_cert_handle(),
62 if (rv
!= SECSuccess
) {
63 LOG(ERROR
) << "Could not import cert";
70 scoped_refptr
<X509Certificate
> ImportClientCertAndKeyFromFile(
71 const base::FilePath
& dir
,
72 const std::string
& cert_filename
,
73 const std::string
& key_filename
,
75 if (!ImportSensitiveKeyFromFile(dir
, key_filename
, slot
)) {
76 LOG(ERROR
) << "Could not import private key from file " << key_filename
;
80 scoped_refptr
<X509Certificate
> cert(ImportCertFromFile(dir
, cert_filename
));
83 LOG(ERROR
) << "Failed to parse cert from file " << cert_filename
;
87 if (!ImportClientCertToSlot(cert
, slot
))
90 // |cert| continues to point to the original X509Certificate before the
91 // import to |slot|. However this should not make a difference as NSS handles