1 // Copyright (c) 2011 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 #ifndef CRYPTO_RSA_PRIVATE_KEY_H_
6 #define CRYPTO_RSA_PRIVATE_KEY_H_
9 #include "build/build_config.h"
11 #if defined(USE_OPENSSL)
12 // Forward declaration for openssl/*.h
13 typedef struct evp_pkey_st EVP_PKEY
;
14 #elif defined(USE_NSS)
15 // Forward declaration.
16 struct SECKEYPrivateKeyStr
;
17 struct SECKEYPublicKeyStr
;
18 #elif defined(OS_MACOSX)
19 #include <Security/cssm.h>
25 #include "base/basictypes.h"
26 #include "crypto/crypto_api.h"
29 #include "crypto/scoped_capi_types.h"
32 #include "base/gtest_prod_util.h"
37 // Used internally by RSAPrivateKey for serializing and deserializing
38 // PKCS #8 PrivateKeyInfo and PublicKeyInfo.
39 class PrivateKeyInfoCodec
{
42 // ASN.1 encoding of the AlgorithmIdentifier from PKCS #8.
43 static const uint8 kRsaAlgorithmIdentifier
[];
45 // ASN.1 tags for some types we use.
46 static const uint8 kBitStringTag
= 0x03;
47 static const uint8 kIntegerTag
= 0x02;
48 static const uint8 kNullTag
= 0x05;
49 static const uint8 kOctetStringTag
= 0x04;
50 static const uint8 kSequenceTag
= 0x30;
52 // |big_endian| here specifies the byte-significance of the integer components
53 // that will be parsed & serialized (modulus(), etc...) during Import(),
54 // Export() and ExportPublicKeyInfo() -- not the ASN.1 DER encoding of the
55 // PrivateKeyInfo/PublicKeyInfo (which is always big-endian).
56 explicit PrivateKeyInfoCodec(bool big_endian
);
58 ~PrivateKeyInfoCodec();
60 // Exports the contents of the integer components to the ASN.1 DER encoding
61 // of the PrivateKeyInfo structure to |output|.
62 bool Export(std::vector
<uint8
>* output
);
64 // Exports the contents of the integer components to the ASN.1 DER encoding
65 // of the PublicKeyInfo structure to |output|.
66 bool ExportPublicKeyInfo(std::vector
<uint8
>* output
);
68 // Exports the contents of the integer components to the ASN.1 DER encoding
69 // of the RSAPublicKey structure to |output|.
70 bool ExportPublicKey(std::vector
<uint8
>* output
);
72 // Parses the ASN.1 DER encoding of the PrivateKeyInfo structure in |input|
73 // and populates the integer components with |big_endian_| byte-significance.
74 // IMPORTANT NOTE: This is currently *not* security-approved for importing
75 // keys from unstrusted sources.
76 bool Import(const std::vector
<uint8
>& input
);
78 // Accessors to the contents of the integer components of the PrivateKeyInfo
80 std::vector
<uint8
>* modulus() { return &modulus_
; };
81 std::vector
<uint8
>* public_exponent() { return &public_exponent_
; };
82 std::vector
<uint8
>* private_exponent() { return &private_exponent_
; };
83 std::vector
<uint8
>* prime1() { return &prime1_
; };
84 std::vector
<uint8
>* prime2() { return &prime2_
; };
85 std::vector
<uint8
>* exponent1() { return &exponent1_
; };
86 std::vector
<uint8
>* exponent2() { return &exponent2_
; };
87 std::vector
<uint8
>* coefficient() { return &coefficient_
; };
90 // Utility wrappers for PrependIntegerImpl that use the class's |big_endian_|
92 void PrependInteger(const std::vector
<uint8
>& in
, std::list
<uint8
>* out
);
93 void PrependInteger(uint8
* val
, int num_bytes
, std::list
<uint8
>* data
);
95 // Prepends the integer stored in |val| - |val + num_bytes| with |big_endian|
96 // byte-significance into |data| as an ASN.1 integer.
97 void PrependIntegerImpl(uint8
* val
,
99 std::list
<uint8
>* data
,
102 // Utility wrappers for ReadIntegerImpl that use the class's |big_endian_|
104 bool ReadInteger(uint8
** pos
, uint8
* end
, std::vector
<uint8
>* out
);
105 bool ReadIntegerWithExpectedSize(uint8
** pos
,
107 size_t expected_size
,
108 std::vector
<uint8
>* out
);
110 // Reads an ASN.1 integer from |pos|, and stores the result into |out| with
111 // |big_endian| byte-significance.
112 bool ReadIntegerImpl(uint8
** pos
,
114 std::vector
<uint8
>* out
,
117 // Prepends the integer stored in |val|, starting a index |start|, for
118 // |num_bytes| bytes onto |data|.
119 void PrependBytes(uint8
* val
,
122 std::list
<uint8
>* data
);
124 // Helper to prepend an ASN.1 length field.
125 void PrependLength(size_t size
, std::list
<uint8
>* data
);
127 // Helper to prepend an ASN.1 type header.
128 void PrependTypeHeaderAndLength(uint8 type
,
130 std::list
<uint8
>* output
);
132 // Helper to prepend an ASN.1 bit string
133 void PrependBitString(uint8
* val
, int num_bytes
, std::list
<uint8
>* output
);
135 // Read an ASN.1 length field. This also checks that the length does not
136 // extend beyond |end|.
137 bool ReadLength(uint8
** pos
, uint8
* end
, uint32
* result
);
139 // Read an ASN.1 type header and its length.
140 bool ReadTypeHeaderAndLength(uint8
** pos
,
145 // Read an ASN.1 sequence declaration. This consumes the type header and
146 // length field, but not the contents of the sequence.
147 bool ReadSequence(uint8
** pos
, uint8
* end
);
149 // Read the RSA AlgorithmIdentifier.
150 bool ReadAlgorithmIdentifier(uint8
** pos
, uint8
* end
);
152 // Read one of the two version fields in PrivateKeyInfo.
153 bool ReadVersion(uint8
** pos
, uint8
* end
);
155 // The byte-significance of the stored components (modulus, etc..).
158 // Component integers of the PrivateKeyInfo
159 std::vector
<uint8
> modulus_
;
160 std::vector
<uint8
> public_exponent_
;
161 std::vector
<uint8
> private_exponent_
;
162 std::vector
<uint8
> prime1_
;
163 std::vector
<uint8
> prime2_
;
164 std::vector
<uint8
> exponent1_
;
165 std::vector
<uint8
> exponent2_
;
166 std::vector
<uint8
> coefficient_
;
168 DISALLOW_COPY_AND_ASSIGN(PrivateKeyInfoCodec
);
171 // Encapsulates an RSA private key. Can be used to generate new keys, export
172 // keys to other formats, or to extract a public key.
173 // TODO(hclam): This class should be ref-counted so it can be reused easily.
174 class CRYPTO_API RSAPrivateKey
{
178 // Create a new random instance. Can return NULL if initialization fails.
179 static RSAPrivateKey
* Create(uint16 num_bits
);
181 // Create a new random instance. Can return NULL if initialization fails.
182 // The created key is permanent and is not exportable in plaintext form.
184 // NOTE: Currently only available if USE_NSS is defined.
185 static RSAPrivateKey
* CreateSensitive(uint16 num_bits
);
187 // Create a new instance by importing an existing private key. The format is
188 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
189 // initialization fails.
190 static RSAPrivateKey
* CreateFromPrivateKeyInfo(
191 const std::vector
<uint8
>& input
);
193 // Create a new instance by importing an existing private key. The format is
194 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
195 // initialization fails.
196 // The created key is permanent and is not exportable in plaintext form.
198 // NOTE: Currently only available if USE_NSS is defined.
199 static RSAPrivateKey
* CreateSensitiveFromPrivateKeyInfo(
200 const std::vector
<uint8
>& input
);
202 // Import an existing public key, and then search for the private
203 // half in the key database. The format of the public key blob is is
204 // an X509 SubjectPublicKeyInfo block. This can return NULL if
205 // initialization fails or the private key cannot be found. The
206 // caller takes ownership of the returned object, but nothing new is
207 // created in the key database.
209 // NOTE: Currently only available if USE_NSS is defined.
210 static RSAPrivateKey
* FindFromPublicKeyInfo(
211 const std::vector
<uint8
>& input
);
213 #if defined(USE_OPENSSL)
214 EVP_PKEY
* key() { return key_
; }
215 #elif defined(USE_NSS)
216 SECKEYPrivateKeyStr
* key() { return key_
; }
217 SECKEYPublicKeyStr
* public_key() { return public_key_
; }
218 #elif defined(OS_WIN)
219 HCRYPTPROV
provider() { return provider_
; }
220 HCRYPTKEY
key() { return key_
; }
221 #elif defined(OS_MACOSX)
222 CSSM_KEY_PTR
key() { return &key_
; }
223 CSSM_KEY_PTR
public_key() { return &public_key_
; }
226 // Exports the private key to a PKCS #1 PrivateKey block.
227 bool ExportPrivateKey(std::vector
<uint8
>* output
);
229 // Exports the public key to an X509 SubjectPublicKeyInfo block.
230 bool ExportPublicKey(std::vector
<uint8
>* output
);
234 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest
, FindFromPublicKey
);
235 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest
, FailedFindFromPublicKey
);
238 // Constructor is private. Use one of the Create*() or Find*()
239 // methods above instead.
242 // Shared helper for Create() and CreateSensitive().
243 // TODO(cmasone): consider replacing |permanent| and |sensitive| with a
244 // flags arg created by ORing together some enumerated values.
245 static RSAPrivateKey
* CreateWithParams(uint16 num_bits
,
249 // Shared helper for CreateFromPrivateKeyInfo() and
250 // CreateSensitiveFromPrivateKeyInfo().
251 static RSAPrivateKey
* CreateFromPrivateKeyInfoWithParams(
252 const std::vector
<uint8
>& input
, bool permanent
, bool sensitive
);
254 #if defined(USE_OPENSSL)
256 #elif defined(USE_NSS)
257 SECKEYPrivateKeyStr
* key_
;
258 SECKEYPublicKeyStr
* public_key_
;
259 #elif defined(OS_WIN)
262 ScopedHCRYPTPROV provider_
;
263 ScopedHCRYPTKEY key_
;
264 #elif defined(OS_MACOSX)
266 CSSM_KEY public_key_
;
269 DISALLOW_COPY_AND_ASSIGN(RSAPrivateKey
);
272 } // namespace crypto
274 #endif // CRYPTO_RSA_PRIVATE_KEY_H_