1 // Copyright (c) 2012 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 "crypto/ec_private_key.h"
7 #include <openssl/ec.h>
8 #include <openssl/evp.h>
9 #include <openssl/pkcs12.h>
10 #include <openssl/x509.h>
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "crypto/openssl_util.h"
15 #include "crypto/scoped_openssl_types.h"
21 // Function pointer definition, for injecting the required key export function
22 // into ExportKeyWithBio, below. |bio| is a temporary memory BIO object, and
23 // |key| is a handle to the input key object. Return 1 on success, 0 otherwise.
24 // NOTE: Used with OpenSSL functions, which do not comply with the Chromium
25 // style guide, hence the unusual parameter placement / types.
26 typedef int (*ExportBioFunction
)(BIO
* bio
, const void* key
);
28 typedef ScopedOpenSSL
<PKCS8_PRIV_KEY_INFO
, PKCS8_PRIV_KEY_INFO_free
>::Type
29 ScopedPKCS8_PRIV_KEY_INFO
;
30 typedef ScopedOpenSSL
<X509_SIG
, X509_SIG_free
>::Type ScopedX509_SIG
;
32 // Helper to export |key| into |output| via the specified ExportBioFunction.
33 bool ExportKeyWithBio(const void* key
,
34 ExportBioFunction export_fn
,
35 std::vector
<uint8
>* output
) {
39 ScopedBIO
bio(BIO_new(BIO_s_mem()));
43 if (!export_fn(bio
.get(), key
))
47 long len
= BIO_get_mem_data(bio
.get(), &data
);
51 output
->assign(data
, data
+ len
);
55 // Function pointer definition, for injecting the required key export function
56 // into ExportKey below. |key| is a pointer to the input key object,
57 // and |data| is either NULL, or the address of an 'unsigned char*' pointer
58 // that points to the start of the output buffer. The function must return
59 // the number of bytes required to export the data, or -1 in case of error.
60 typedef int (*ExportDataFunction
)(const void* key
, unsigned char** data
);
62 // Helper to export |key| into |output| via the specified export function.
63 bool ExportKey(const void* key
,
64 ExportDataFunction export_fn
,
65 std::vector
<uint8
>* output
) {
69 int data_len
= export_fn(key
, NULL
);
73 output
->resize(static_cast<size_t>(data_len
));
74 unsigned char* data
= &(*output
)[0];
75 if (export_fn(key
, &data
) < 0)
83 ECPrivateKey::~ECPrivateKey() {
89 bool ECPrivateKey::IsSupported() { return true; }
92 ECPrivateKey
* ECPrivateKey::Create() {
93 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
95 ScopedEC_KEY
ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1
));
96 if (!ec_key
.get() || !EC_KEY_generate_key(ec_key
.get()))
99 scoped_ptr
<ECPrivateKey
> result(new ECPrivateKey());
100 result
->key_
= EVP_PKEY_new();
101 if (!result
->key_
|| !EVP_PKEY_set1_EC_KEY(result
->key_
, ec_key
.get()))
104 CHECK_EQ(EVP_PKEY_EC
, EVP_PKEY_type(result
->key_
->type
));
105 return result
.release();
109 ECPrivateKey
* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
110 const std::string
& password
,
111 const std::vector
<uint8
>& encrypted_private_key_info
,
112 const std::vector
<uint8
>& subject_public_key_info
) {
113 // NOTE: The |subject_public_key_info| can be ignored here, it is only
114 // useful for the NSS implementation (which uses the public key's SHA1
115 // as a lookup key when storing the private one in its store).
116 if (encrypted_private_key_info
.empty())
119 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
120 // Write the encrypted private key into a memory BIO.
121 char* private_key_data
= reinterpret_cast<char*>(
122 const_cast<uint8
*>(&encrypted_private_key_info
[0]));
123 int private_key_data_len
=
124 static_cast<int>(encrypted_private_key_info
.size());
125 ScopedBIO
bio(BIO_new_mem_buf(private_key_data
, private_key_data_len
));
129 // Convert it, then decrypt it into a PKCS#8 object.
130 ScopedX509_SIG
p8_encrypted(d2i_PKCS8_bio(bio
.get(), NULL
));
131 if (!p8_encrypted
.get())
134 ScopedPKCS8_PRIV_KEY_INFO
p8_decrypted(PKCS8_decrypt(
135 p8_encrypted
.get(), password
.c_str(), static_cast<int>(password
.size())));
136 if (!p8_decrypted
.get() && password
.empty()) {
137 // Hack for reading keys generated by ec_private_key_nss. Passing NULL
138 // causes OpenSSL to use an empty password instead of "\0\0".
139 p8_decrypted
.reset(PKCS8_decrypt(p8_encrypted
.get(), NULL
, 0));
141 if (!p8_decrypted
.get())
144 // Create a new EVP_PKEY for it.
145 scoped_ptr
<ECPrivateKey
> result(new ECPrivateKey
);
146 result
->key_
= EVP_PKCS82PKEY(p8_decrypted
.get());
147 if (!result
->key_
|| EVP_PKEY_type(result
->key_
->type
) != EVP_PKEY_EC
)
150 return result
.release();
153 bool ECPrivateKey::ExportEncryptedPrivateKey(
154 const std::string
& password
,
156 std::vector
<uint8
>* output
) {
157 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
158 // Convert into a PKCS#8 object.
159 ScopedPKCS8_PRIV_KEY_INFO
pkcs8(EVP_PKEY2PKCS8(key_
));
163 // Encrypt the object.
164 // NOTE: NSS uses SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC
165 // so use NID_pbe_WithSHA1And3_Key_TripleDES_CBC which should be the OpenSSL
167 ScopedX509_SIG
encrypted(PKCS8_encrypt(NID_pbe_WithSHA1And3_Key_TripleDES_CBC
,
170 static_cast<int>(password
.size()),
175 if (!encrypted
.get())
178 // Write it into |*output|
179 return ExportKeyWithBio(encrypted
.get(),
180 reinterpret_cast<ExportBioFunction
>(i2d_PKCS8_bio
),
184 bool ECPrivateKey::ExportPublicKey(std::vector
<uint8
>* output
) {
185 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
186 return ExportKeyWithBio(
187 key_
, reinterpret_cast<ExportBioFunction
>(i2d_PUBKEY_bio
), output
);
190 bool ECPrivateKey::ExportRawPublicKey(std::string
* output
) {
191 // i2d_PublicKey will produce an ANSI X9.62 public key which, for a P-256
192 // key, is 0x04 (meaning uncompressed) followed by the x and y field
193 // elements as 32-byte, big-endian numbers.
194 static const int kExpectedKeyLength
= 65;
196 int len
= i2d_PublicKey(key_
, NULL
);
197 if (len
!= kExpectedKeyLength
)
200 uint8 buf
[kExpectedKeyLength
];
202 len
= i2d_PublicKey(key_
, &derp
);
203 if (len
!= kExpectedKeyLength
)
206 output
->assign(reinterpret_cast<char*>(buf
+ 1), kExpectedKeyLength
- 1);
210 bool ECPrivateKey::ExportValue(std::vector
<uint8
>* output
) {
211 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
212 ScopedEC_KEY
ec_key(EVP_PKEY_get1_EC_KEY(key_
));
213 return ExportKey(ec_key
.get(),
214 reinterpret_cast<ExportDataFunction
>(i2d_ECPrivateKey
),
218 bool ECPrivateKey::ExportECParams(std::vector
<uint8
>* output
) {
219 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
220 ScopedEC_KEY
ec_key(EVP_PKEY_get1_EC_KEY(key_
));
221 return ExportKey(ec_key
.get(),
222 reinterpret_cast<ExportDataFunction
>(i2d_ECParameters
),
226 ECPrivateKey::ECPrivateKey() : key_(NULL
) {}
228 } // namespace crypto