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 #ifndef CRYPTO_RSA_PRIVATE_KEY_H_
6 #define CRYPTO_RSA_PRIVATE_KEY_H_
8 #include "build/build_config.h"
10 #if defined(USE_OPENSSL)
11 // Forward declaration for openssl/*.h
12 typedef struct evp_pkey_st EVP_PKEY
;
13 #elif defined(USE_NSS)
14 // Forward declaration.
15 struct SECKEYPrivateKeyStr
;
16 struct SECKEYPublicKeyStr
;
18 #include <Security/Security.h>
19 #elif defined(OS_MACOSX)
20 #include <Security/cssm.h>
26 #include "base/basictypes.h"
27 #include "crypto/crypto_export.h"
30 #include "crypto/scoped_capi_types.h"
33 #include "base/gtest_prod_util.h"
38 // Used internally by RSAPrivateKey for serializing and deserializing
39 // PKCS #8 PrivateKeyInfo and PublicKeyInfo.
40 class PrivateKeyInfoCodec
{
43 // ASN.1 encoding of the AlgorithmIdentifier from PKCS #8.
44 static const uint8 kRsaAlgorithmIdentifier
[];
46 // ASN.1 tags for some types we use.
47 static const uint8 kBitStringTag
= 0x03;
48 static const uint8 kIntegerTag
= 0x02;
49 static const uint8 kNullTag
= 0x05;
50 static const uint8 kOctetStringTag
= 0x04;
51 static const uint8 kSequenceTag
= 0x30;
53 // |big_endian| here specifies the byte-significance of the integer components
54 // that will be parsed & serialized (modulus(), etc...) during Import(),
55 // Export() and ExportPublicKeyInfo() -- not the ASN.1 DER encoding of the
56 // PrivateKeyInfo/PublicKeyInfo (which is always big-endian).
57 explicit PrivateKeyInfoCodec(bool big_endian
);
59 ~PrivateKeyInfoCodec();
61 // Exports the contents of the integer components to the ASN.1 DER encoding
62 // of the PrivateKeyInfo structure to |output|.
63 bool Export(std::vector
<uint8
>* output
);
65 // Exports the contents of the integer components to the ASN.1 DER encoding
66 // of the PublicKeyInfo structure to |output|.
67 bool ExportPublicKeyInfo(std::vector
<uint8
>* output
);
69 // Exports the contents of the integer components to the ASN.1 DER encoding
70 // of the RSAPublicKey structure to |output|.
71 bool ExportPublicKey(std::vector
<uint8
>* output
);
73 // Parses the ASN.1 DER encoding of the PrivateKeyInfo structure in |input|
74 // and populates the integer components with |big_endian_| byte-significance.
75 // IMPORTANT NOTE: This is currently *not* security-approved for importing
76 // keys from unstrusted sources.
77 bool Import(const std::vector
<uint8
>& input
);
79 // Accessors to the contents of the integer components of the PrivateKeyInfo
81 std::vector
<uint8
>* modulus() { return &modulus_
; };
82 std::vector
<uint8
>* public_exponent() { return &public_exponent_
; };
83 std::vector
<uint8
>* private_exponent() { return &private_exponent_
; };
84 std::vector
<uint8
>* prime1() { return &prime1_
; };
85 std::vector
<uint8
>* prime2() { return &prime2_
; };
86 std::vector
<uint8
>* exponent1() { return &exponent1_
; };
87 std::vector
<uint8
>* exponent2() { return &exponent2_
; };
88 std::vector
<uint8
>* coefficient() { return &coefficient_
; };
91 // Utility wrappers for PrependIntegerImpl that use the class's |big_endian_|
93 void PrependInteger(const std::vector
<uint8
>& in
, std::list
<uint8
>* out
);
94 void PrependInteger(uint8
* val
, int num_bytes
, std::list
<uint8
>* data
);
96 // Prepends the integer stored in |val| - |val + num_bytes| with |big_endian|
97 // byte-significance into |data| as an ASN.1 integer.
98 void PrependIntegerImpl(uint8
* val
,
100 std::list
<uint8
>* data
,
103 // Utility wrappers for ReadIntegerImpl that use the class's |big_endian_|
105 bool ReadInteger(uint8
** pos
, uint8
* end
, std::vector
<uint8
>* out
);
106 bool ReadIntegerWithExpectedSize(uint8
** pos
,
108 size_t expected_size
,
109 std::vector
<uint8
>* out
);
111 // Reads an ASN.1 integer from |pos|, and stores the result into |out| with
112 // |big_endian| byte-significance.
113 bool ReadIntegerImpl(uint8
** pos
,
115 std::vector
<uint8
>* out
,
118 // Prepends the integer stored in |val|, starting a index |start|, for
119 // |num_bytes| bytes onto |data|.
120 void PrependBytes(uint8
* val
,
123 std::list
<uint8
>* data
);
125 // Helper to prepend an ASN.1 length field.
126 void PrependLength(size_t size
, std::list
<uint8
>* data
);
128 // Helper to prepend an ASN.1 type header.
129 void PrependTypeHeaderAndLength(uint8 type
,
131 std::list
<uint8
>* output
);
133 // Helper to prepend an ASN.1 bit string
134 void PrependBitString(uint8
* val
, int num_bytes
, std::list
<uint8
>* output
);
136 // Read an ASN.1 length field. This also checks that the length does not
137 // extend beyond |end|.
138 bool ReadLength(uint8
** pos
, uint8
* end
, uint32
* result
);
140 // Read an ASN.1 type header and its length.
141 bool ReadTypeHeaderAndLength(uint8
** pos
,
146 // Read an ASN.1 sequence declaration. This consumes the type header and
147 // length field, but not the contents of the sequence.
148 bool ReadSequence(uint8
** pos
, uint8
* end
);
150 // Read the RSA AlgorithmIdentifier.
151 bool ReadAlgorithmIdentifier(uint8
** pos
, uint8
* end
);
153 // Read one of the two version fields in PrivateKeyInfo.
154 bool ReadVersion(uint8
** pos
, uint8
* end
);
156 // The byte-significance of the stored components (modulus, etc..).
159 // Component integers of the PrivateKeyInfo
160 std::vector
<uint8
> modulus_
;
161 std::vector
<uint8
> public_exponent_
;
162 std::vector
<uint8
> private_exponent_
;
163 std::vector
<uint8
> prime1_
;
164 std::vector
<uint8
> prime2_
;
165 std::vector
<uint8
> exponent1_
;
166 std::vector
<uint8
> exponent2_
;
167 std::vector
<uint8
> coefficient_
;
169 DISALLOW_COPY_AND_ASSIGN(PrivateKeyInfoCodec
);
172 // Encapsulates an RSA private key. Can be used to generate new keys, export
173 // keys to other formats, or to extract a public key.
174 // TODO(hclam): This class should be ref-counted so it can be reused easily.
175 class CRYPTO_EXPORT RSAPrivateKey
{
179 // Create a new random instance. Can return NULL if initialization fails.
180 static RSAPrivateKey
* Create(uint16 num_bits
);
182 // Create a new random instance. Can return NULL if initialization fails.
183 // The created key is permanent and is not exportable in plaintext form.
185 // NOTE: Currently only available if USE_NSS is defined.
186 static RSAPrivateKey
* CreateSensitive(uint16 num_bits
);
188 // Create a new instance by importing an existing private key. The format is
189 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
190 // initialization fails.
191 static RSAPrivateKey
* CreateFromPrivateKeyInfo(
192 const std::vector
<uint8
>& input
);
194 // Create a new instance by importing an existing private key. The format is
195 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
196 // initialization fails.
197 // The created key is permanent and is not exportable in plaintext form.
199 // NOTE: Currently only available if USE_NSS is defined.
200 static RSAPrivateKey
* CreateSensitiveFromPrivateKeyInfo(
201 const std::vector
<uint8
>& input
);
203 // Import an existing public key, and then search for the private
204 // half in the key database. The format of the public key blob is is
205 // an X509 SubjectPublicKeyInfo block. This can return NULL if
206 // initialization fails or the private key cannot be found. The
207 // caller takes ownership of the returned object, but nothing new is
208 // created in the key database.
210 // NOTE: Currently only available if USE_NSS is defined.
211 static RSAPrivateKey
* FindFromPublicKeyInfo(
212 const std::vector
<uint8
>& input
);
214 #if defined(USE_OPENSSL)
215 EVP_PKEY
* key() { return key_
; }
216 #elif defined(USE_NSS)
217 SECKEYPrivateKeyStr
* key() { return key_
; }
218 SECKEYPublicKeyStr
* public_key() { return public_key_
; }
219 #elif defined(OS_WIN)
220 HCRYPTPROV
provider() { return provider_
; }
221 HCRYPTKEY
key() { return key_
; }
222 #elif defined(OS_IOS)
223 SecKeyRef
key() { return key_
; }
224 SecKeyRef
public_key() { return public_key_
; }
225 #elif defined(OS_MACOSX)
226 CSSM_KEY_PTR
key() { return &key_
; }
227 CSSM_KEY_PTR
public_key() { return &public_key_
; }
230 // Creates a copy of the object.
231 RSAPrivateKey
* Copy() const;
233 // Exports the private key to a PKCS #1 PrivateKey block.
234 bool ExportPrivateKey(std::vector
<uint8
>* output
) const;
236 // Exports the public key to an X509 SubjectPublicKeyInfo block.
237 bool ExportPublicKey(std::vector
<uint8
>* output
) const;
241 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest
, FindFromPublicKey
);
242 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest
, FailedFindFromPublicKey
);
245 // Constructor is private. Use one of the Create*() or Find*()
246 // methods above instead.
249 // Shared helper for Create() and CreateSensitive().
250 // TODO(cmasone): consider replacing |permanent| and |sensitive| with a
251 // flags arg created by ORing together some enumerated values.
252 static RSAPrivateKey
* CreateWithParams(uint16 num_bits
,
256 // Shared helper for CreateFromPrivateKeyInfo() and
257 // CreateSensitiveFromPrivateKeyInfo().
258 static RSAPrivateKey
* CreateFromPrivateKeyInfoWithParams(
259 const std::vector
<uint8
>& input
, bool permanent
, bool sensitive
);
261 #if defined(USE_OPENSSL)
263 #elif defined(USE_NSS)
264 SECKEYPrivateKeyStr
* key_
;
265 SECKEYPublicKeyStr
* public_key_
;
266 #elif defined(OS_WIN)
269 ScopedHCRYPTPROV provider_
;
270 ScopedHCRYPTKEY key_
;
271 #elif defined(OS_IOS)
273 SecKeyRef public_key_
;
274 #elif defined(OS_MACOSX)
276 CSSM_KEY public_key_
;
279 DISALLOW_COPY_AND_ASSIGN(RSAPrivateKey
);
282 } // namespace crypto
284 #endif // CRYPTO_RSA_PRIVATE_KEY_H_