blob: ad82148428a564519262c98fb503f1969eee1fdb [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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.
4
5#ifndef CRYPTO_RSA_PRIVATE_KEY_H_
6#define CRYPTO_RSA_PRIVATE_KEY_H_
7
8#include "build/build_config.h"
9
Torne (Richard Coles)58218062012-11-14 11:43:16 +000010#include <list>
11#include <vector>
12
13#include "base/basictypes.h"
14#include "crypto/crypto_export.h"
15
Torne (Richard Coles)58218062012-11-14 11:43:16 +000016#if defined(USE_NSS)
17#include "base/gtest_prod_util.h"
18#endif
19
Ben Murdocheb525c52013-07-10 11:40:50 +010020#if defined(USE_OPENSSL)
21// Forward declaration for openssl/*.h
22typedef struct evp_pkey_st EVP_PKEY;
23#elif defined(USE_NSS) || defined(OS_WIN) || defined(OS_MACOSX)
24// Forward declaration.
25typedef struct SECKEYPrivateKeyStr SECKEYPrivateKey;
26typedef struct SECKEYPublicKeyStr SECKEYPublicKey;
27#endif
28
29
Torne (Richard Coles)58218062012-11-14 11:43:16 +000030namespace crypto {
31
32// Used internally by RSAPrivateKey for serializing and deserializing
33// PKCS #8 PrivateKeyInfo and PublicKeyInfo.
34class PrivateKeyInfoCodec {
35 public:
36
37 // ASN.1 encoding of the AlgorithmIdentifier from PKCS #8.
38 static const uint8 kRsaAlgorithmIdentifier[];
39
40 // ASN.1 tags for some types we use.
41 static const uint8 kBitStringTag = 0x03;
42 static const uint8 kIntegerTag = 0x02;
43 static const uint8 kNullTag = 0x05;
44 static const uint8 kOctetStringTag = 0x04;
45 static const uint8 kSequenceTag = 0x30;
46
47 // |big_endian| here specifies the byte-significance of the integer components
48 // that will be parsed & serialized (modulus(), etc...) during Import(),
49 // Export() and ExportPublicKeyInfo() -- not the ASN.1 DER encoding of the
50 // PrivateKeyInfo/PublicKeyInfo (which is always big-endian).
51 explicit PrivateKeyInfoCodec(bool big_endian);
52
53 ~PrivateKeyInfoCodec();
54
55 // Exports the contents of the integer components to the ASN.1 DER encoding
56 // of the PrivateKeyInfo structure to |output|.
57 bool Export(std::vector<uint8>* output);
58
59 // Exports the contents of the integer components to the ASN.1 DER encoding
60 // of the PublicKeyInfo structure to |output|.
61 bool ExportPublicKeyInfo(std::vector<uint8>* output);
62
63 // Exports the contents of the integer components to the ASN.1 DER encoding
64 // of the RSAPublicKey structure to |output|.
65 bool ExportPublicKey(std::vector<uint8>* output);
66
67 // Parses the ASN.1 DER encoding of the PrivateKeyInfo structure in |input|
68 // and populates the integer components with |big_endian_| byte-significance.
69 // IMPORTANT NOTE: This is currently *not* security-approved for importing
70 // keys from unstrusted sources.
71 bool Import(const std::vector<uint8>& input);
72
73 // Accessors to the contents of the integer components of the PrivateKeyInfo
74 // structure.
75 std::vector<uint8>* modulus() { return &modulus_; };
76 std::vector<uint8>* public_exponent() { return &public_exponent_; };
77 std::vector<uint8>* private_exponent() { return &private_exponent_; };
78 std::vector<uint8>* prime1() { return &prime1_; };
79 std::vector<uint8>* prime2() { return &prime2_; };
80 std::vector<uint8>* exponent1() { return &exponent1_; };
81 std::vector<uint8>* exponent2() { return &exponent2_; };
82 std::vector<uint8>* coefficient() { return &coefficient_; };
83
84 private:
85 // Utility wrappers for PrependIntegerImpl that use the class's |big_endian_|
86 // value.
87 void PrependInteger(const std::vector<uint8>& in, std::list<uint8>* out);
88 void PrependInteger(uint8* val, int num_bytes, std::list<uint8>* data);
89
90 // Prepends the integer stored in |val| - |val + num_bytes| with |big_endian|
91 // byte-significance into |data| as an ASN.1 integer.
92 void PrependIntegerImpl(uint8* val,
93 int num_bytes,
94 std::list<uint8>* data,
95 bool big_endian);
96
97 // Utility wrappers for ReadIntegerImpl that use the class's |big_endian_|
98 // value.
99 bool ReadInteger(uint8** pos, uint8* end, std::vector<uint8>* out);
100 bool ReadIntegerWithExpectedSize(uint8** pos,
101 uint8* end,
102 size_t expected_size,
103 std::vector<uint8>* out);
104
105 // Reads an ASN.1 integer from |pos|, and stores the result into |out| with
106 // |big_endian| byte-significance.
107 bool ReadIntegerImpl(uint8** pos,
108 uint8* end,
109 std::vector<uint8>* out,
110 bool big_endian);
111
112 // Prepends the integer stored in |val|, starting a index |start|, for
113 // |num_bytes| bytes onto |data|.
114 void PrependBytes(uint8* val,
115 int start,
116 int num_bytes,
117 std::list<uint8>* data);
118
119 // Helper to prepend an ASN.1 length field.
120 void PrependLength(size_t size, std::list<uint8>* data);
121
122 // Helper to prepend an ASN.1 type header.
123 void PrependTypeHeaderAndLength(uint8 type,
124 uint32 length,
125 std::list<uint8>* output);
126
127 // Helper to prepend an ASN.1 bit string
128 void PrependBitString(uint8* val, int num_bytes, std::list<uint8>* output);
129
130 // Read an ASN.1 length field. This also checks that the length does not
131 // extend beyond |end|.
132 bool ReadLength(uint8** pos, uint8* end, uint32* result);
133
134 // Read an ASN.1 type header and its length.
135 bool ReadTypeHeaderAndLength(uint8** pos,
136 uint8* end,
137 uint8 expected_tag,
138 uint32* length);
139
140 // Read an ASN.1 sequence declaration. This consumes the type header and
141 // length field, but not the contents of the sequence.
142 bool ReadSequence(uint8** pos, uint8* end);
143
144 // Read the RSA AlgorithmIdentifier.
145 bool ReadAlgorithmIdentifier(uint8** pos, uint8* end);
146
147 // Read one of the two version fields in PrivateKeyInfo.
148 bool ReadVersion(uint8** pos, uint8* end);
149
150 // The byte-significance of the stored components (modulus, etc..).
151 bool big_endian_;
152
153 // Component integers of the PrivateKeyInfo
154 std::vector<uint8> modulus_;
155 std::vector<uint8> public_exponent_;
156 std::vector<uint8> private_exponent_;
157 std::vector<uint8> prime1_;
158 std::vector<uint8> prime2_;
159 std::vector<uint8> exponent1_;
160 std::vector<uint8> exponent2_;
161 std::vector<uint8> coefficient_;
162
163 DISALLOW_COPY_AND_ASSIGN(PrivateKeyInfoCodec);
164};
165
166// Encapsulates an RSA private key. Can be used to generate new keys, export
167// keys to other formats, or to extract a public key.
168// TODO(hclam): This class should be ref-counted so it can be reused easily.
169class CRYPTO_EXPORT RSAPrivateKey {
170 public:
171 ~RSAPrivateKey();
172
173 // Create a new random instance. Can return NULL if initialization fails.
174 static RSAPrivateKey* Create(uint16 num_bits);
175
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000176 // Create a new instance by importing an existing private key. The format is
177 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
178 // initialization fails.
179 static RSAPrivateKey* CreateFromPrivateKeyInfo(
180 const std::vector<uint8>& input);
181
Ben Murdocheb525c52013-07-10 11:40:50 +0100182#if defined(USE_NSS)
183 // Create a new random instance. Can return NULL if initialization fails.
184 // The created key is permanent and is not exportable in plaintext form.
185 static RSAPrivateKey* CreateSensitive(uint16 num_bits);
186
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000187 // 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 // The created key is permanent and is not exportable in plaintext form.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000191 static RSAPrivateKey* CreateSensitiveFromPrivateKeyInfo(
192 const std::vector<uint8>& input);
193
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +0100194 // Create a new instance by referencing an existing private key
195 // structure. Does not import the key.
196 static RSAPrivateKey* CreateFromKey(SECKEYPrivateKey* key);
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +0100197
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000198 // Import an existing public key, and then search for the private
199 // half in the key database. The format of the public key blob is is
200 // an X509 SubjectPublicKeyInfo block. This can return NULL if
201 // initialization fails or the private key cannot be found. The
202 // caller takes ownership of the returned object, but nothing new is
203 // created in the key database.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000204 static RSAPrivateKey* FindFromPublicKeyInfo(
205 const std::vector<uint8>& input);
Ben Murdocheb525c52013-07-10 11:40:50 +0100206#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000207
208#if defined(USE_OPENSSL)
209 EVP_PKEY* key() { return key_; }
Ben Murdocheb525c52013-07-10 11:40:50 +0100210#elif defined(USE_NSS) || defined(OS_WIN) || defined(OS_MACOSX)
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +0100211 SECKEYPrivateKey* key() { return key_; }
212 SECKEYPublicKey* public_key() { return public_key_; }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000213#endif
214
215 // Creates a copy of the object.
216 RSAPrivateKey* Copy() const;
217
218 // Exports the private key to a PKCS #1 PrivateKey block.
219 bool ExportPrivateKey(std::vector<uint8>* output) const;
220
221 // Exports the public key to an X509 SubjectPublicKeyInfo block.
222 bool ExportPublicKey(std::vector<uint8>* output) const;
223
224 private:
225#if defined(USE_NSS)
226 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest, FindFromPublicKey);
227 FRIEND_TEST_ALL_PREFIXES(RSAPrivateKeyNSSTest, FailedFindFromPublicKey);
228#endif
229
230 // Constructor is private. Use one of the Create*() or Find*()
231 // methods above instead.
232 RSAPrivateKey();
233
234 // Shared helper for Create() and CreateSensitive().
235 // TODO(cmasone): consider replacing |permanent| and |sensitive| with a
236 // flags arg created by ORing together some enumerated values.
Ben Murdocheb525c52013-07-10 11:40:50 +0100237 // Note: |permanent| is only supported when USE_NSS is defined.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000238 static RSAPrivateKey* CreateWithParams(uint16 num_bits,
239 bool permanent,
240 bool sensitive);
241
242 // Shared helper for CreateFromPrivateKeyInfo() and
243 // CreateSensitiveFromPrivateKeyInfo().
Ben Murdocheb525c52013-07-10 11:40:50 +0100244 // Note: |permanent| is only supported when USE_NSS is defined.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000245 static RSAPrivateKey* CreateFromPrivateKeyInfoWithParams(
Ben Murdocheb525c52013-07-10 11:40:50 +0100246 const std::vector<uint8>& input,
247 bool permanent,
248 bool sensitive);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000249
250#if defined(USE_OPENSSL)
251 EVP_PKEY* key_;
Ben Murdocheb525c52013-07-10 11:40:50 +0100252#elif defined(USE_NSS) || defined(OS_WIN) || defined(OS_MACOSX)
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +0100253 SECKEYPrivateKey* key_;
254 SECKEYPublicKey* public_key_;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000255#endif
256
257 DISALLOW_COPY_AND_ASSIGN(RSAPrivateKey);
258};
259
260} // namespace crypto
261
262#endif // CRYPTO_RSA_PRIVATE_KEY_H_