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"
20 // Function pointer definition, for injecting the required key export function
21 // into ExportKeyWithBio, below. |bio| is a temporary memory BIO object, and
22 // |key| is a handle to the input key object. Return 1 on success, 0 otherwise.
23 // NOTE: Used with OpenSSL functions, which do not comply with the Chromium
24 // style guide, hence the unusual parameter placement / types.
25 typedef int (*ExportBioFunction
)(BIO
* bio
, const void* key
);
27 // Helper to export |key| into |output| via the specified ExportBioFunction.
28 bool ExportKeyWithBio(const void* key
,
29 ExportBioFunction export_fn
,
30 std::vector
<uint8
>* output
) {
34 ScopedOpenSSL
<BIO
, BIO_free_all
> bio(BIO_new(BIO_s_mem()));
38 if (!export_fn(bio
.get(), key
))
42 long len
= BIO_get_mem_data(bio
.get(), &data
);
46 output
->assign(data
, data
+ len
);
50 // Function pointer definition, for injecting the required key export function
51 // into ExportKey below. |key| is a pointer to the input key object,
52 // and |data| is either NULL, or the address of an 'unsigned char*' pointer
53 // that points to the start of the output buffer. The function must return
54 // the number of bytes required to export the data, or -1 in case of error.
55 typedef int (*ExportDataFunction
)(const void* key
, unsigned char** data
);
57 // Helper to export |key| into |output| via the specified export function.
58 bool ExportKey(const void* key
,
59 ExportDataFunction export_fn
,
60 std::vector
<uint8
>* output
) {
64 int data_len
= export_fn(key
, NULL
);
68 output
->resize(static_cast<size_t>(data_len
));
69 unsigned char* data
= &(*output
)[0];
70 if (export_fn(key
, &data
) < 0)
78 ECPrivateKey::~ECPrivateKey() {
84 bool ECPrivateKey::IsSupported() { return true; }
87 ECPrivateKey
* ECPrivateKey::Create() {
88 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
90 ScopedOpenSSL
<EC_KEY
, EC_KEY_free
> ec_key(
91 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1
));
92 if (!ec_key
.get() || !EC_KEY_generate_key(ec_key
.get()))
95 scoped_ptr
<ECPrivateKey
> result(new ECPrivateKey());
96 result
->key_
= EVP_PKEY_new();
97 if (!result
->key_
|| !EVP_PKEY_set1_EC_KEY(result
->key_
, ec_key
.get()))
100 CHECK_EQ(EVP_PKEY_EC
, EVP_PKEY_type(result
->key_
->type
));
101 return result
.release();
105 ECPrivateKey
* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
106 const std::string
& password
,
107 const std::vector
<uint8
>& encrypted_private_key_info
,
108 const std::vector
<uint8
>& subject_public_key_info
) {
109 // NOTE: The |subject_public_key_info| can be ignored here, it is only
110 // useful for the NSS implementation (which uses the public key's SHA1
111 // as a lookup key when storing the private one in its store).
112 if (encrypted_private_key_info
.empty())
115 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
116 // Write the encrypted private key into a memory BIO.
117 char* private_key_data
= reinterpret_cast<char*>(
118 const_cast<uint8
*>(&encrypted_private_key_info
[0]));
119 int private_key_data_len
=
120 static_cast<int>(encrypted_private_key_info
.size());
121 ScopedOpenSSL
<BIO
, BIO_free_all
> bio(
122 BIO_new_mem_buf(private_key_data
, private_key_data_len
));
126 // Convert it, then decrypt it into a PKCS#8 object.
127 ScopedOpenSSL
<X509_SIG
, X509_SIG_free
> p8_encrypted(
128 d2i_PKCS8_bio(bio
.get(), NULL
));
129 if (!p8_encrypted
.get())
132 ScopedOpenSSL
<PKCS8_PRIV_KEY_INFO
, PKCS8_PRIV_KEY_INFO_free
> p8_decrypted(
133 PKCS8_decrypt(p8_encrypted
.get(),
135 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 ScopedOpenSSL
<PKCS8_PRIV_KEY_INFO
, PKCS8_PRIV_KEY_INFO_free
> pkcs8(
160 EVP_PKEY2PKCS8(key_
));
164 // Encrypt the object.
165 // NOTE: NSS uses SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC
166 // so use NID_pbe_WithSHA1And3_Key_TripleDES_CBC which should be the OpenSSL
168 ScopedOpenSSL
<X509_SIG
, X509_SIG_free
> encrypted(
169 PKCS8_encrypt(NID_pbe_WithSHA1And3_Key_TripleDES_CBC
,
172 static_cast<int>(password
.size()),
177 if (!encrypted
.get())
180 // Write it into |*output|
181 return ExportKeyWithBio(encrypted
.get(),
182 reinterpret_cast<ExportBioFunction
>(i2d_PKCS8_bio
),
186 bool ECPrivateKey::ExportPublicKey(std::vector
<uint8
>* output
) {
187 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
188 return ExportKeyWithBio(
189 key_
, reinterpret_cast<ExportBioFunction
>(i2d_PUBKEY_bio
), output
);
192 bool ECPrivateKey::ExportRawPublicKey(std::string
* output
) {
193 // i2d_PublicKey will produce an ANSI X9.62 public key which, for a P-256
194 // key, is 0x04 (meaning uncompressed) followed by the x and y field
195 // elements as 32-byte, big-endian numbers.
196 static const int kExpectedKeyLength
= 65;
198 int len
= i2d_PublicKey(key_
, NULL
);
199 if (len
!= kExpectedKeyLength
)
202 uint8 buf
[kExpectedKeyLength
];
204 len
= i2d_PublicKey(key_
, &derp
);
205 if (len
!= kExpectedKeyLength
)
208 output
->assign(reinterpret_cast<char*>(buf
+ 1), kExpectedKeyLength
- 1);
212 bool ECPrivateKey::ExportValue(std::vector
<uint8
>* output
) {
213 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
214 ScopedOpenSSL
<EC_KEY
, EC_KEY_free
> ec_key(EVP_PKEY_get1_EC_KEY(key_
));
215 return ExportKey(ec_key
.get(),
216 reinterpret_cast<ExportDataFunction
>(i2d_ECPrivateKey
),
220 bool ECPrivateKey::ExportECParams(std::vector
<uint8
>* output
) {
221 OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
222 ScopedOpenSSL
<EC_KEY
, EC_KEY_free
> ec_key(EVP_PKEY_get1_EC_KEY(key_
));
223 return ExportKey(ec_key
.get(),
224 reinterpret_cast<ExportDataFunction
>(i2d_ECParameters
),
228 ECPrivateKey::ECPrivateKey() : key_(NULL
) {}
230 } // namespace crypto