Fix several issues in BaseCryptLib:
[mirror_edk2.git] / CryptoPkg / Library / BaseCryptLib / Pk / CryptRsaExt.c
1 /** @file
2 RSA Asymmetric Cipher Wrapper Implementation over OpenSSL.
3
4 This file implements following APIs which provide more capabilities for RSA:
5 1) RsaGetKey
6 2) RsaGenerateKey
7 3) RsaCheckKey
8 4) RsaPkcs1Sign
9
10 Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
11 This program and the accompanying materials
12 are licensed and made available under the terms and conditions of the BSD License
13 which accompanies this distribution. The full text of the license may be found at
14 http://opensource.org/licenses/bsd-license.php
15
16 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
17 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18
19 **/
20
21 #include "InternalCryptLib.h"
22
23 #include <openssl/rsa.h>
24 #include <openssl/err.h>
25
26 //
27 // ASN.1 value for Hash Algorithm ID with the Distringuished Encoding Rules (DER)
28 // Refer to Section 9.2 of PKCS#1 v2.1
29 //
30 CONST UINT8 Asn1IdMd5[] = {
31 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86,
32 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
33 };
34
35 CONST UINT8 Asn1IdSha1[] = {
36 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
37 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14
38 };
39
40 CONST UINT8 Asn1IdSha256[] = {
41 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
42 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
43 0x00, 0x04, 0x20
44 };
45
46 /**
47 Gets the tag-designated RSA key component from the established RSA context.
48
49 This function retrieves the tag-designated RSA key component from the
50 established RSA context as a non-negative integer (octet string format
51 represented in RSA PKCS#1).
52 If specified key component has not been set or has been cleared, then returned
53 BnSize is set to 0.
54 If the BigNumber buffer is too small to hold the contents of the key, FALSE
55 is returned and BnSize is set to the required buffer size to obtain the key.
56
57 If RsaContext is NULL, then return FALSE.
58 If BnSize is NULL, then return FALSE.
59 If BnSize is large enough but BigNumber is NULL, then return FALSE.
60
61 @param[in, out] RsaContext Pointer to RSA context being set.
62 @param[in] KeyTag Tag of RSA key component being set.
63 @param[out] BigNumber Pointer to octet integer buffer.
64 @param[in, out] BnSize On input, the size of big number buffer in bytes.
65 On output, the size of data returned in big number buffer in bytes.
66
67 @retval TRUE RSA key component was retrieved successfully.
68 @retval FALSE Invalid RSA key component tag.
69 @retval FALSE BnSize is too small.
70
71 **/
72 BOOLEAN
73 EFIAPI
74 RsaGetKey (
75 IN OUT VOID *RsaContext,
76 IN RSA_KEY_TAG KeyTag,
77 OUT UINT8 *BigNumber,
78 IN OUT UINTN *BnSize
79 )
80 {
81 RSA *RsaKey;
82 BIGNUM *BnKey;
83 UINTN Size;
84
85 //
86 // Check input parameters.
87 //
88 if (RsaContext == NULL || BnSize == NULL) {
89 return FALSE;
90 }
91
92 RsaKey = (RSA *) RsaContext;
93 Size = *BnSize;
94 *BnSize = 0;
95
96 switch (KeyTag) {
97
98 //
99 // RSA Public Modulus (N)
100 //
101 case RsaKeyN:
102 if (RsaKey->n == NULL) {
103 return TRUE;
104 }
105 BnKey = RsaKey->n;
106 break;
107
108 //
109 // RSA Public Exponent (e)
110 //
111 case RsaKeyE:
112 if (RsaKey->e == NULL) {
113 return TRUE;
114 }
115 BnKey = RsaKey->e;
116 break;
117
118 //
119 // RSA Private Exponent (d)
120 //
121 case RsaKeyD:
122 if (RsaKey->d == NULL) {
123 return TRUE;
124 }
125 BnKey = RsaKey->d;
126 break;
127
128 //
129 // RSA Secret Prime Factor of Modulus (p)
130 //
131 case RsaKeyP:
132 if (RsaKey->p == NULL) {
133 return TRUE;
134 }
135 BnKey = RsaKey->p;
136 break;
137
138 //
139 // RSA Secret Prime Factor of Modules (q)
140 //
141 case RsaKeyQ:
142 if (RsaKey->q == NULL) {
143 return TRUE;
144 }
145 BnKey = RsaKey->q;
146 break;
147
148 //
149 // p's CRT Exponent (== d mod (p - 1))
150 //
151 case RsaKeyDp:
152 if (RsaKey->dmp1 == NULL) {
153 return TRUE;
154 }
155 BnKey = RsaKey->dmp1;
156 break;
157
158 //
159 // q's CRT Exponent (== d mod (q - 1))
160 //
161 case RsaKeyDq:
162 if (RsaKey->dmq1 == NULL) {
163 return TRUE;
164 }
165 BnKey = RsaKey->dmq1;
166 break;
167
168 //
169 // The CRT Coefficient (== 1/q mod p)
170 //
171 case RsaKeyQInv:
172 if (RsaKey->iqmp == NULL) {
173 return TRUE;
174 }
175 BnKey = RsaKey->iqmp;
176 break;
177
178 default:
179 return FALSE;
180 }
181
182 *BnSize = Size;
183 Size = BN_num_bytes (BnKey);
184
185 if (*BnSize < Size) {
186 *BnSize = Size;
187 return FALSE;
188 }
189
190 if (BigNumber == NULL) {
191 return FALSE;
192 }
193 *BnSize = BN_bn2bin (BnKey, BigNumber) ;
194
195 return TRUE;
196 }
197
198 /**
199 Generates RSA key components.
200
201 This function generates RSA key components. It takes RSA public exponent E and
202 length in bits of RSA modulus N as input, and generates all key components.
203 If PublicExponent is NULL, the default RSA public exponent (0x10001) will be used.
204
205 Before this function can be invoked, pseudorandom number generator must be correctly
206 initialized by RandomSeed().
207
208 If RsaContext is NULL, then return FALSE.
209
210 @param[in, out] RsaContext Pointer to RSA context being set.
211 @param[in] ModulusLength Length of RSA modulus N in bits.
212 @param[in] PublicExponent Pointer to RSA public exponent.
213 @param[in] PublicExponentSize Size of RSA public exponent buffer in bytes.
214
215 @retval TRUE RSA key component was generated successfully.
216 @retval FALSE Invalid RSA key component tag.
217
218 **/
219 BOOLEAN
220 EFIAPI
221 RsaGenerateKey (
222 IN OUT VOID *RsaContext,
223 IN UINTN ModulusLength,
224 IN CONST UINT8 *PublicExponent,
225 IN UINTN PublicExponentSize
226 )
227 {
228 BIGNUM *KeyE;
229 BOOLEAN RetVal;
230
231 //
232 // Check input parameters.
233 //
234 if (RsaContext == NULL || ModulusLength > INT_MAX || PublicExponentSize > INT_MAX) {
235 return FALSE;
236 }
237
238 KeyE = BN_new ();
239 if (KeyE == NULL) {
240 return FALSE;
241 }
242
243 RetVal = FALSE;
244
245 if (PublicExponent == NULL) {
246 if (BN_set_word (KeyE, 0x10001) == 0) {
247 goto _Exit;
248 }
249 } else {
250 if (BN_bin2bn (PublicExponent, (UINT32) PublicExponentSize, KeyE) == NULL) {
251 goto _Exit;
252 }
253 }
254
255 if (RSA_generate_key_ex ((RSA *) RsaContext, (UINT32) ModulusLength, KeyE, NULL) == 1) {
256 RetVal = TRUE;
257 }
258
259 _Exit:
260 BN_free (KeyE);
261 return RetVal;
262 }
263
264 /**
265 Validates key components of RSA context.
266
267 This function validates key compoents of RSA context in following aspects:
268 - Whether p is a prime
269 - Whether q is a prime
270 - Whether n = p * q
271 - Whether d*e = 1 mod lcm(p-1,q-1)
272
273 If RsaContext is NULL, then return FALSE.
274
275 @param[in] RsaContext Pointer to RSA context to check.
276
277 @retval TRUE RSA key components are valid.
278 @retval FALSE RSA key components are not valid.
279
280 **/
281 BOOLEAN
282 EFIAPI
283 RsaCheckKey (
284 IN VOID *RsaContext
285 )
286 {
287 UINTN Reason;
288
289 //
290 // Check input parameters.
291 //
292 if (RsaContext == NULL) {
293 return FALSE;
294 }
295
296 if (RSA_check_key ((RSA *) RsaContext) != 1) {
297 Reason = ERR_GET_REASON (ERR_peek_last_error ());
298 if (Reason == RSA_R_P_NOT_PRIME ||
299 Reason == RSA_R_Q_NOT_PRIME ||
300 Reason == RSA_R_N_DOES_NOT_EQUAL_P_Q ||
301 Reason == RSA_R_D_E_NOT_CONGRUENT_TO_1) {
302 return FALSE;
303 }
304 }
305
306 return TRUE;
307 }
308
309 /**
310 Performs the PKCS1-v1_5 encoding methods defined in RSA PKCS #1.
311
312 @param[in] Message Message buffer to be encoded.
313 @param[in] MessageSize Size of message buffer in bytes.
314 @param[out] DigestInfo Pointer to buffer of digest info for output.
315 @param[in,out] DigestInfoSize On input, the size of DigestInfo buffer in bytes.
316 On output, the size of data returned in DigestInfo
317 buffer in bytes.
318
319 @retval TRUE PKCS1-v1_5 encoding finished successfully.
320 @retval FALSE Any input parameter is invalid.
321 @retval FALSE DigestInfo buffer is not large enough.
322
323 **/
324 BOOLEAN
325 DigestInfoEncoding (
326 IN CONST UINT8 *Message,
327 IN UINTN MessageSize,
328 OUT UINT8 *DigestInfo,
329 IN OUT UINTN *DigestInfoSize
330 )
331 {
332 CONST UINT8 *HashDer;
333 UINTN DerSize;
334
335 //
336 // Check input parameters.
337 //
338 if (Message == NULL || DigestInfo == NULL || DigestInfoSize == NULL) {
339 return FALSE;
340 }
341
342 //
343 // The original message length is used to determine the hash algorithm since
344 // message is digest value hashed by the specified algorithm.
345 //
346 switch (MessageSize) {
347 case MD5_DIGEST_SIZE:
348 HashDer = Asn1IdMd5;
349 DerSize = sizeof (Asn1IdMd5);
350 break;
351
352 case SHA1_DIGEST_SIZE:
353 HashDer = Asn1IdSha1;
354 DerSize = sizeof (Asn1IdSha1);
355 break;
356
357 case SHA256_DIGEST_SIZE:
358 HashDer = Asn1IdSha256;
359 DerSize = sizeof (Asn1IdSha256);
360 break;
361
362 default:
363 return FALSE;
364 }
365
366 if (*DigestInfoSize < DerSize + MessageSize) {
367 *DigestInfoSize = DerSize + MessageSize;
368 return FALSE;
369 }
370
371 CopyMem (DigestInfo, HashDer, DerSize);
372 CopyMem (DigestInfo + DerSize, Message, MessageSize);
373
374 *DigestInfoSize = DerSize + MessageSize;
375 return TRUE;
376 }
377
378 /**
379 Carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme.
380
381 This function carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme defined in
382 RSA PKCS#1.
383 If the Signature buffer is too small to hold the contents of signature, FALSE
384 is returned and SigSize is set to the required buffer size to obtain the signature.
385
386 If RsaContext is NULL, then return FALSE.
387 If MessageHash is NULL, then return FALSE.
388 If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE.
389 If SigSize is large enough but Signature is NULL, then return FALSE.
390
391 @param[in] RsaContext Pointer to RSA context for signature generation.
392 @param[in] MessageHash Pointer to octet message hash to be signed.
393 @param[in] HashSize Size of the message hash in bytes.
394 @param[out] Signature Pointer to buffer to receive RSA PKCS1-v1_5 signature.
395 @param[in, out] SigSize On input, the size of Signature buffer in bytes.
396 On output, the size of data returned in Signature buffer in bytes.
397
398 @retval TRUE Signature successfully generated in PKCS1-v1_5.
399 @retval FALSE Signature generation failed.
400 @retval FALSE SigSize is too small.
401
402 **/
403 BOOLEAN
404 EFIAPI
405 RsaPkcs1Sign (
406 IN VOID *RsaContext,
407 IN CONST UINT8 *MessageHash,
408 IN UINTN HashSize,
409 OUT UINT8 *Signature,
410 IN OUT UINTN *SigSize
411 )
412 {
413 RSA *Rsa;
414 UINTN Size;
415 INTN ReturnVal;
416
417 //
418 // Check input parameters.
419 //
420 if (RsaContext == NULL || MessageHash == NULL ||
421 (HashSize != MD5_DIGEST_SIZE && HashSize != SHA1_DIGEST_SIZE && HashSize != SHA256_DIGEST_SIZE)) {
422 return FALSE;
423 }
424
425 Rsa = (RSA *) RsaContext;
426 Size = BN_num_bytes (Rsa->n);
427
428 if (*SigSize < Size) {
429 *SigSize = Size;
430 return FALSE;
431 }
432
433 if (Signature == NULL) {
434 return FALSE;
435 }
436
437 if (!DigestInfoEncoding (MessageHash, HashSize, Signature, SigSize)) {
438 return FALSE;
439 }
440
441 ReturnVal = RSA_private_encrypt (
442 (UINT32) *SigSize,
443 Signature,
444 Signature,
445 Rsa,
446 RSA_PKCS1_PADDING
447 );
448
449 if (ReturnVal < (INTN) *SigSize) {
450 return FALSE;
451 }
452
453 *SigSize = (UINTN) ReturnVal;
454 return TRUE;
455 }
456