1 // Copyright (c) 2009 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.
4
5 #include "base/crypto/rsa_private_key.h"
6
7 #include <iostream>
8 #include <list>
9
10 #include "base/logging.h"
11 #include "base/scoped_ptr.h"
12 #include "base/string_util.h"
13
14 namespace {
15 // Helper for error handling during key import.
16 #define READ_ASSERT(truth) \
17 if (!(truth)) { \
18 NOTREACHED(); \
19 return false; \
20 }
21 } // namespace
22
23 namespace base {
24
25 // static
Create(uint16 num_bits)26 RSAPrivateKey* RSAPrivateKey::Create(uint16 num_bits) {
27 scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
28 if (!result->InitProvider())
29 return NULL;
30
31 DWORD flags = CRYPT_EXPORTABLE;
32
33 // The size is encoded as the upper 16 bits of the flags. :: sigh ::.
34 flags |= (num_bits << 16);
35 if (!CryptGenKey(result->provider_, CALG_RSA_SIGN, flags, &result->key_))
36 return NULL;
37
38 return result.release();
39 }
40
41 // static
CreateFromPrivateKeyInfo(const std::vector<uint8> & input)42 RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfo(
43 const std::vector<uint8>& input) {
44 scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
45 if (!result->InitProvider())
46 return NULL;
47
48 PrivateKeyInfoCodec pki(false); // Little-Endian
49 pki.Import(input);
50
51 int blob_size = sizeof(PUBLICKEYSTRUC) +
52 sizeof(RSAPUBKEY) +
53 pki.modulus()->size() +
54 pki.prime1()->size() +
55 pki.prime2()->size() +
56 pki.exponent1()->size() +
57 pki.exponent2()->size() +
58 pki.coefficient()->size() +
59 pki.private_exponent()->size();
60 scoped_array<BYTE> blob(new BYTE[blob_size]);
61
62 uint8* dest = blob.get();
63 PUBLICKEYSTRUC* public_key_struc = reinterpret_cast<PUBLICKEYSTRUC*>(dest);
64 public_key_struc->bType = PRIVATEKEYBLOB;
65 public_key_struc->bVersion = 0x02;
66 public_key_struc->reserved = 0;
67 public_key_struc->aiKeyAlg = CALG_RSA_SIGN;
68 dest += sizeof(PUBLICKEYSTRUC);
69
70 RSAPUBKEY* rsa_pub_key = reinterpret_cast<RSAPUBKEY*>(dest);
71 rsa_pub_key->magic = 0x32415352;
72 rsa_pub_key->bitlen = pki.modulus()->size() * 8;
73 int public_exponent_int = 0;
74 for (size_t i = pki.public_exponent()->size(); i > 0; --i) {
75 public_exponent_int <<= 8;
76 public_exponent_int |= (*pki.public_exponent())[i - 1];
77 }
78 rsa_pub_key->pubexp = public_exponent_int;
79 dest += sizeof(RSAPUBKEY);
80
81 memcpy(dest, &pki.modulus()->front(), pki.modulus()->size());
82 dest += pki.modulus()->size();
83 memcpy(dest, &pki.prime1()->front(), pki.prime1()->size());
84 dest += pki.prime1()->size();
85 memcpy(dest, &pki.prime2()->front(), pki.prime2()->size());
86 dest += pki.prime2()->size();
87 memcpy(dest, &pki.exponent1()->front(), pki.exponent1()->size());
88 dest += pki.exponent1()->size();
89 memcpy(dest, &pki.exponent2()->front(), pki.exponent2()->size());
90 dest += pki.exponent2()->size();
91 memcpy(dest, &pki.coefficient()->front(), pki.coefficient()->size());
92 dest += pki.coefficient()->size();
93 memcpy(dest, &pki.private_exponent()->front(), pki.private_exponent()->size());
94 dest += pki.private_exponent()->size();
95
96 READ_ASSERT(dest == blob.get() + blob_size);
97 if (!CryptImportKey(
98 result->provider_, reinterpret_cast<uint8*>(public_key_struc), blob_size,
99 NULL, CRYPT_EXPORTABLE, &result->key_)) {
100 return NULL;
101 }
102
103 return result.release();
104 }
105
RSAPrivateKey()106 RSAPrivateKey::RSAPrivateKey() : provider_(NULL), key_(NULL) {}
107
~RSAPrivateKey()108 RSAPrivateKey::~RSAPrivateKey() {
109 if (key_) {
110 if (!CryptDestroyKey(key_))
111 NOTREACHED();
112 }
113
114 if (provider_) {
115 if (!CryptReleaseContext(provider_, 0))
116 NOTREACHED();
117 }
118 }
119
InitProvider()120 bool RSAPrivateKey::InitProvider() {
121 return FALSE != CryptAcquireContext(&provider_, NULL, NULL,
122 PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
123 }
124
ExportPrivateKey(std::vector<uint8> * output)125 bool RSAPrivateKey::ExportPrivateKey(std::vector<uint8>* output) {
126 // Export the key
127 DWORD blob_length = 0;
128 if (!CryptExportKey(key_, NULL, PRIVATEKEYBLOB, 0, NULL, &blob_length)) {
129 NOTREACHED();
130 return false;
131 }
132
133 scoped_array<uint8> blob(new uint8[blob_length]);
134 if (!CryptExportKey(key_, NULL, PRIVATEKEYBLOB, 0, blob.get(),
135 &blob_length)) {
136 NOTREACHED();
137 return false;
138 }
139
140 uint8* pos = blob.get();
141 PUBLICKEYSTRUC *publickey_struct = reinterpret_cast<PUBLICKEYSTRUC*>(pos);
142 pos += sizeof(PUBLICKEYSTRUC);
143
144 RSAPUBKEY *rsa_pub_key = reinterpret_cast<RSAPUBKEY*>(pos);
145 pos += sizeof(RSAPUBKEY);
146
147 int mod_size = rsa_pub_key->bitlen / 8;
148 int primes_size = rsa_pub_key->bitlen / 16;
149
150 PrivateKeyInfoCodec pki(false); // Little-Endian
151
152 pki.modulus()->assign(pos, pos + mod_size);
153 pos += mod_size;
154
155 pki.prime1()->assign(pos, pos + primes_size);
156 pos += primes_size;
157 pki.prime2()->assign(pos, pos + primes_size);
158 pos += primes_size;
159
160 pki.exponent1()->assign(pos, pos + primes_size);
161 pos += primes_size;
162 pki.exponent2()->assign(pos, pos + primes_size);
163 pos += primes_size;
164
165 pki.coefficient()->assign(pos, pos + primes_size);
166 pos += primes_size;
167
168 pki.private_exponent()->assign(pos, pos + mod_size);
169 pos += mod_size;
170
171 pki.public_exponent()->assign(reinterpret_cast<uint8*>(&rsa_pub_key->pubexp),
172 reinterpret_cast<uint8*>(&rsa_pub_key->pubexp) + 4);
173
174 CHECK((pos - blob_length) == reinterpret_cast<BYTE*>(publickey_struct));
175
176 return pki.Export(output);
177 }
178
ExportPublicKey(std::vector<uint8> * output)179 bool RSAPrivateKey::ExportPublicKey(std::vector<uint8>* output) {
180 DWORD key_info_len;
181 if (!CryptExportPublicKeyInfo(
182 provider_, AT_SIGNATURE, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
183 NULL, &key_info_len)) {
184 NOTREACHED();
185 return false;
186 }
187
188 scoped_array<uint8> key_info(new uint8[key_info_len]);
189 if (!CryptExportPublicKeyInfo(
190 provider_, AT_SIGNATURE, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
191 reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(key_info.get()), &key_info_len)) {
192 NOTREACHED();
193 return false;
194 }
195
196 DWORD encoded_length;
197 if (!CryptEncodeObject(
198 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
199 reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(key_info.get()), NULL,
200 &encoded_length)) {
201 NOTREACHED();
202 return false;
203 }
204
205 scoped_array<BYTE> encoded(new BYTE[encoded_length]);
206 if (!CryptEncodeObject(
207 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
208 reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(key_info.get()), encoded.get(),
209 &encoded_length)) {
210 NOTREACHED();
211 return false;
212 }
213
214 for (size_t i = 0; i < encoded_length; ++i)
215 output->push_back(encoded[i]);
216
217 return true;
218 }
219
220 } // namespace base
221