]> git.proxmox.com Git - mirror_edk2.git/blob - CryptoPkg/Library/BaseCryptLib/Pk/CryptRsa.c
1. Remove conducting ASSERT in BaseCryptLib.
[mirror_edk2.git] / CryptoPkg / Library / BaseCryptLib / Pk / CryptRsa.c
1 /** @file
2 RSA Asymmetric Cipher Wrapper Implementation over OpenSSL.
3
4 Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "InternalCryptLib.h"
16
17 #include <openssl/rsa.h>
18 #include <openssl/err.h>
19
20 //
21 // ASN.1 value for Hash Algorithm ID with the Distringuished Encoding Rules (DER)
22 // Refer to Section 9.2 of PKCS#1 v2.1
23 //
24 CONST UINT8 Asn1IdMd5[] = {
25 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86,
26 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
27 };
28
29 CONST UINT8 Asn1IdSha1[] = {
30 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
31 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14
32 };
33
34 CONST UINT8 Asn1IdSha256[] = {
35 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
36 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
37 0x00, 0x04, 0x20
38 };
39
40
41 /**
42 Allocates and initializes one RSA context for subsequent use.
43
44 @return Pointer to the RSA context that has been initialized.
45 If the allocations fails, RsaNew() returns NULL.
46
47 **/
48 VOID *
49 EFIAPI
50 RsaNew (
51 VOID
52 )
53 {
54 //
55 // Allocates & Initializes RSA Context by OpenSSL RSA_new()
56 //
57 return (VOID *)RSA_new ();
58 }
59
60 /**
61 Release the specified RSA context.
62
63 If RsaContext is NULL, then return FALSE.
64
65 @param[in] RsaContext Pointer to the RSA context to be released.
66
67 **/
68 VOID
69 EFIAPI
70 RsaFree (
71 IN VOID *RsaContext
72 )
73 {
74 //
75 // Free OpenSSL RSA Context
76 //
77 RSA_free ((RSA *)RsaContext);
78 }
79
80 /**
81 Sets the tag-designated key component into the established RSA context.
82
83 This function sets the tag-designated RSA key component into the established
84 RSA context from the user-specified non-negative integer (octet string format
85 represented in RSA PKCS#1).
86 If BigNumber is NULL, then the specified key componenet in RSA context is cleared.
87
88 If RsaContext is NULL, then return FALSE.
89
90 @param[in, out] RsaContext Pointer to RSA context being set.
91 @param[in] KeyTag Tag of RSA key component being set.
92 @param[in] BigNumber Pointer to octet integer buffer.
93 If NULL, then the specified key componenet in RSA
94 context is cleared.
95 @param[in] BnSize Size of big number buffer in bytes.
96 If BigNumber is NULL, then it is ignored.
97
98 @retval TRUE RSA key component was set successfully.
99 @retval FALSE Invalid RSA key component tag.
100
101 **/
102 BOOLEAN
103 EFIAPI
104 RsaSetKey (
105 IN OUT VOID *RsaContext,
106 IN RSA_KEY_TAG KeyTag,
107 IN CONST UINT8 *BigNumber,
108 IN UINTN BnSize
109 )
110 {
111 RSA *RsaKey;
112
113 //
114 // Check input parameters.
115 //
116 if (RsaContext == NULL) {
117 return FALSE;
118 }
119
120 RsaKey = (RSA *)RsaContext;
121 //
122 // Set RSA Key Components by converting octet string to OpenSSL BN representation.
123 // NOTE: For RSA public key (used in signature verification), only public components
124 // (N, e) are needed.
125 //
126 switch (KeyTag) {
127
128 //
129 // RSA Public Modulus (N)
130 //
131 case RsaKeyN:
132 if (RsaKey->n != NULL) {
133 BN_free (RsaKey->n);
134 }
135 RsaKey->n = NULL;
136 if (BigNumber == NULL) {
137 break;
138 }
139 RsaKey->n = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->n);
140 break;
141
142 //
143 // RSA Public Exponent (e)
144 //
145 case RsaKeyE:
146 if (RsaKey->e != NULL) {
147 BN_free (RsaKey->e);
148 }
149 RsaKey->e = NULL;
150 if (BigNumber == NULL) {
151 break;
152 }
153 RsaKey->e = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->e);
154 break;
155
156 //
157 // RSA Private Exponent (d)
158 //
159 case RsaKeyD:
160 if (RsaKey->d != NULL) {
161 BN_free (RsaKey->d);
162 }
163 RsaKey->d = NULL;
164 if (BigNumber == NULL) {
165 break;
166 }
167 RsaKey->d = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->d);
168 break;
169
170 //
171 // RSA Secret Prime Factor of Modulus (p)
172 //
173 case RsaKeyP:
174 if (RsaKey->p != NULL) {
175 BN_free (RsaKey->p);
176 }
177 RsaKey->p = NULL;
178 if (BigNumber == NULL) {
179 break;
180 }
181 RsaKey->p = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->p);
182 break;
183
184 //
185 // RSA Secret Prime Factor of Modules (q)
186 //
187 case RsaKeyQ:
188 if (RsaKey->q != NULL) {
189 BN_free (RsaKey->q);
190 }
191 RsaKey->q = NULL;
192 if (BigNumber == NULL) {
193 break;
194 }
195 RsaKey->q = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->q);
196 break;
197
198 //
199 // p's CRT Exponent (== d mod (p - 1))
200 //
201 case RsaKeyDp:
202 if (RsaKey->dmp1 != NULL) {
203 BN_free (RsaKey->dmp1);
204 }
205 RsaKey->dmp1 = NULL;
206 if (BigNumber == NULL) {
207 break;
208 }
209 RsaKey->dmp1 = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->dmp1);
210 break;
211
212 //
213 // q's CRT Exponent (== d mod (q - 1))
214 //
215 case RsaKeyDq:
216 if (RsaKey->dmq1 != NULL) {
217 BN_free (RsaKey->dmq1);
218 }
219 RsaKey->dmq1 = NULL;
220 if (BigNumber == NULL) {
221 break;
222 }
223 RsaKey->dmq1 = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->dmq1);
224 break;
225
226 //
227 // The CRT Coefficient (== 1/q mod p)
228 //
229 case RsaKeyQInv:
230 if (RsaKey->iqmp != NULL) {
231 BN_free (RsaKey->iqmp);
232 }
233 RsaKey->iqmp = NULL;
234 if (BigNumber == NULL) {
235 break;
236 }
237 RsaKey->iqmp = BN_bin2bn (BigNumber, (UINT32) BnSize, RsaKey->iqmp);
238 break;
239
240 default:
241 return FALSE;
242 }
243
244 return TRUE;
245 }
246
247 /**
248 Gets the tag-designated RSA key component from the established RSA context.
249
250 This function retrieves the tag-designated RSA key component from the
251 established RSA context as a non-negative integer (octet string format
252 represented in RSA PKCS#1).
253 If specified key component has not been set or has been cleared, then returned
254 BnSize is set to 0.
255 If the BigNumber buffer is too small to hold the contents of the key, FALSE
256 is returned and BnSize is set to the required buffer size to obtain the key.
257
258 If RsaContext is NULL, then return FALSE.
259 If BnSize is NULL, then return FALSE.
260 If BnSize is large enough but BigNumber is NULL, then return FALSE.
261
262 @param[in, out] RsaContext Pointer to RSA context being set.
263 @param[in] KeyTag Tag of RSA key component being set.
264 @param[out] BigNumber Pointer to octet integer buffer.
265 @param[in, out] BnSize On input, the size of big number buffer in bytes.
266 On output, the size of data returned in big number buffer in bytes.
267
268 @retval TRUE RSA key component was retrieved successfully.
269 @retval FALSE Invalid RSA key component tag.
270 @retval FALSE BnSize is too small.
271
272 **/
273 BOOLEAN
274 EFIAPI
275 RsaGetKey (
276 IN OUT VOID *RsaContext,
277 IN RSA_KEY_TAG KeyTag,
278 OUT UINT8 *BigNumber,
279 IN OUT UINTN *BnSize
280 )
281 {
282 RSA *RsaKey;
283 BIGNUM *BnKey;
284 UINTN Size;
285
286 //
287 // Check input parameters.
288 //
289 if (RsaContext == NULL || BnSize == NULL) {
290 return FALSE;
291 }
292
293 RsaKey = (RSA *) RsaContext;
294 Size = *BnSize;
295 *BnSize = 0;
296
297 switch (KeyTag) {
298
299 //
300 // RSA Public Modulus (N)
301 //
302 case RsaKeyN:
303 if (RsaKey->n == NULL) {
304 return TRUE;
305 }
306 BnKey = RsaKey->n;
307 break;
308
309 //
310 // RSA Public Exponent (e)
311 //
312 case RsaKeyE:
313 if (RsaKey->e == NULL) {
314 return TRUE;
315 }
316 BnKey = RsaKey->e;
317 break;
318
319 //
320 // RSA Private Exponent (d)
321 //
322 case RsaKeyD:
323 if (RsaKey->d == NULL) {
324 return TRUE;
325 }
326 BnKey = RsaKey->d;
327 break;
328
329 //
330 // RSA Secret Prime Factor of Modulus (p)
331 //
332 case RsaKeyP:
333 if (RsaKey->p == NULL) {
334 return TRUE;
335 }
336 BnKey = RsaKey->p;
337 break;
338
339 //
340 // RSA Secret Prime Factor of Modules (q)
341 //
342 case RsaKeyQ:
343 if (RsaKey->q == NULL) {
344 return TRUE;
345 }
346 BnKey = RsaKey->q;
347 break;
348
349 //
350 // p's CRT Exponent (== d mod (p - 1))
351 //
352 case RsaKeyDp:
353 if (RsaKey->dmp1 == NULL) {
354 return TRUE;
355 }
356 BnKey = RsaKey->dmp1;
357 break;
358
359 //
360 // q's CRT Exponent (== d mod (q - 1))
361 //
362 case RsaKeyDq:
363 if (RsaKey->dmq1 == NULL) {
364 return TRUE;
365 }
366 BnKey = RsaKey->dmq1;
367 break;
368
369 //
370 // The CRT Coefficient (== 1/q mod p)
371 //
372 case RsaKeyQInv:
373 if (RsaKey->iqmp == NULL) {
374 return TRUE;
375 }
376 BnKey = RsaKey->iqmp;
377 break;
378
379 default:
380 return FALSE;
381 }
382
383 *BnSize = Size;
384 Size = BN_num_bytes (BnKey);
385
386 if (*BnSize < Size) {
387 *BnSize = Size;
388 return FALSE;
389 }
390
391 if (BigNumber == NULL) {
392 return FALSE;
393 }
394 *BnSize = BN_bn2bin (BnKey, BigNumber) ;
395
396 return TRUE;
397 }
398
399 /**
400 Generates RSA key components.
401
402 This function generates RSA key components. It takes RSA public exponent E and
403 length in bits of RSA modulus N as input, and generates all key components.
404 If PublicExponent is NULL, the default RSA public exponent (0x10001) will be used.
405
406 Before this function can be invoked, pseudorandom number generator must be correctly
407 initialized by RandomSeed().
408
409 If RsaContext is NULL, then return FALSE.
410
411 @param[in, out] RsaContext Pointer to RSA context being set.
412 @param[in] ModulusLength Length of RSA modulus N in bits.
413 @param[in] PublicExponent Pointer to RSA public exponent.
414 @param[in] PublicExponentSize Size of RSA public exponent buffer in bytes.
415
416 @retval TRUE RSA key component was generated successfully.
417 @retval FALSE Invalid RSA key component tag.
418
419 **/
420 BOOLEAN
421 EFIAPI
422 RsaGenerateKey (
423 IN OUT VOID *RsaContext,
424 IN UINTN ModulusLength,
425 IN CONST UINT8 *PublicExponent,
426 IN UINTN PublicExponentSize
427 )
428 {
429 BIGNUM *KeyE;
430 BOOLEAN RetVal;
431
432 //
433 // Check input parameters.
434 //
435 if (RsaContext == NULL) {
436 return FALSE;
437 }
438
439 KeyE = BN_new ();
440 if (PublicExponent == NULL) {
441 BN_set_word (KeyE, 0x10001);
442 } else {
443 BN_bin2bn (PublicExponent, (UINT32) PublicExponentSize, KeyE);
444 }
445
446 RetVal = FALSE;
447 if (RSA_generate_key_ex ((RSA *) RsaContext, (UINT32) ModulusLength, KeyE, NULL) == 1) {
448 RetVal = TRUE;
449 }
450
451 BN_free (KeyE);
452 return RetVal;
453 }
454
455 /**
456 Validates key components of RSA context.
457
458 This function validates key compoents of RSA context in following aspects:
459 - Whether p is a prime
460 - Whether q is a prime
461 - Whether n = p * q
462 - Whether d*e = 1 mod lcm(p-1,q-1)
463
464 If RsaContext is NULL, then return FALSE.
465
466 @param[in] RsaContext Pointer to RSA context to check.
467
468 @retval TRUE RSA key components are valid.
469 @retval FALSE RSA key components are not valid.
470
471 **/
472 BOOLEAN
473 EFIAPI
474 RsaCheckKey (
475 IN VOID *RsaContext
476 )
477 {
478 UINTN Reason;
479
480 //
481 // Check input parameters.
482 //
483 if (RsaContext == NULL) {
484 return FALSE;
485 }
486
487 if (RSA_check_key ((RSA *) RsaContext) != 1) {
488 Reason = ERR_GET_REASON (ERR_peek_last_error ());
489 if (Reason == RSA_R_P_NOT_PRIME ||
490 Reason == RSA_R_Q_NOT_PRIME ||
491 Reason == RSA_R_N_DOES_NOT_EQUAL_P_Q ||
492 Reason == RSA_R_D_E_NOT_CONGRUENT_TO_1) {
493 return FALSE;
494 }
495 }
496
497 return TRUE;
498 }
499
500 /**
501 Performs the PKCS1-v1_5 encoding methods defined in RSA PKCS #1.
502
503 @param Message Message buffer to be encoded.
504 @param MessageSize Size of message buffer in bytes.
505 @param DigestInfo Pointer to buffer of digest info for output.
506
507 @return Size of DigestInfo in bytes.
508
509 **/
510 UINTN
511 DigestInfoEncoding (
512 IN CONST UINT8 *Message,
513 IN UINTN MessageSize,
514 OUT UINT8 *DigestInfo
515 )
516 {
517 CONST UINT8 *HashDer;
518 UINTN DerSize;
519
520 //
521 // Check input parameters.
522 //
523 if (Message == NULL || DigestInfo == NULL) {
524 return FALSE;
525 }
526
527 //
528 // The original message length is used to determine the hash algorithm since
529 // message is digest value hashed by the specified algorithm.
530 //
531 switch (MessageSize) {
532 case MD5_DIGEST_SIZE:
533 HashDer = Asn1IdMd5;
534 DerSize = sizeof (Asn1IdMd5);
535 break;
536
537 case SHA1_DIGEST_SIZE:
538 HashDer = Asn1IdSha1;
539 DerSize = sizeof (Asn1IdSha1);
540 break;
541
542 case SHA256_DIGEST_SIZE:
543 HashDer = Asn1IdSha256;
544 DerSize = sizeof (Asn1IdSha256);
545 break;
546
547 default:
548 return FALSE;
549 }
550
551 CopyMem (DigestInfo, HashDer, DerSize);
552 CopyMem (DigestInfo + DerSize, Message, MessageSize);
553
554 return (DerSize + MessageSize);
555 }
556
557 /**
558 Carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme.
559
560 This function carries out the RSA-SSA signature generation with EMSA-PKCS1-v1_5 encoding scheme defined in
561 RSA PKCS#1.
562 If the Signature buffer is too small to hold the contents of signature, FALSE
563 is returned and SigSize is set to the required buffer size to obtain the signature.
564
565 If RsaContext is NULL, then return FALSE.
566 If MessageHash is NULL, then return FALSE.
567 If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE.
568 If SigSize is large enough but Signature is NULL, then return FALSE.
569
570 @param[in] RsaContext Pointer to RSA context for signature generation.
571 @param[in] MessageHash Pointer to octet message hash to be signed.
572 @param[in] HashSize Size of the message hash in bytes.
573 @param[out] Signature Pointer to buffer to receive RSA PKCS1-v1_5 signature.
574 @param[in, out] SigSize On input, the size of Signature buffer in bytes.
575 On output, the size of data returned in Signature buffer in bytes.
576
577 @retval TRUE Signature successfully generated in PKCS1-v1_5.
578 @retval FALSE Signature generation failed.
579 @retval FALSE SigSize is too small.
580
581 **/
582 BOOLEAN
583 EFIAPI
584 RsaPkcs1Sign (
585 IN VOID *RsaContext,
586 IN CONST UINT8 *MessageHash,
587 IN UINTN HashSize,
588 OUT UINT8 *Signature,
589 IN OUT UINTN *SigSize
590 )
591 {
592 RSA *Rsa;
593 UINTN Size;
594 INTN ReturnVal;
595
596 //
597 // Check input parameters.
598 //
599 if (RsaContext == NULL || MessageHash == NULL ||
600 (HashSize != MD5_DIGEST_SIZE && HashSize != SHA1_DIGEST_SIZE && HashSize != SHA256_DIGEST_SIZE)) {
601 return FALSE;
602 }
603
604 Rsa = (RSA *) RsaContext;
605 Size = BN_num_bytes (Rsa->n);
606
607 if (*SigSize < Size) {
608 *SigSize = Size;
609 return FALSE;
610 }
611
612 if (Signature == NULL) {
613 return FALSE;
614 }
615
616 Size = DigestInfoEncoding (MessageHash, HashSize, Signature);
617
618 ReturnVal = RSA_private_encrypt (
619 (UINT32) Size,
620 Signature,
621 Signature,
622 Rsa,
623 RSA_PKCS1_PADDING
624 );
625
626 if (ReturnVal < (INTN) Size) {
627 return FALSE;
628 }
629
630 *SigSize = (UINTN)ReturnVal;
631 return TRUE;
632 }
633
634 /**
635 Verifies the RSA-SSA signature with EMSA-PKCS1-v1_5 encoding scheme defined in
636 RSA PKCS#1.
637
638 If RsaContext is NULL, then return FALSE.
639 If MessageHash is NULL, then return FALSE.
640 If Signature is NULL, then return FALSE.
641 If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE.
642
643 @param[in] RsaContext Pointer to RSA context for signature verification.
644 @param[in] MessageHash Pointer to octet message hash to be checked.
645 @param[in] HashSize Size of the message hash in bytes.
646 @param[in] Signature Pointer to RSA PKCS1-v1_5 signature to be verified.
647 @param[in] SigSize Size of signature in bytes.
648
649 @retval TRUE Valid signature encoded in PKCS1-v1_5.
650 @retval FALSE Invalid signature or invalid RSA context.
651
652 **/
653 BOOLEAN
654 EFIAPI
655 RsaPkcs1Verify (
656 IN VOID *RsaContext,
657 IN CONST UINT8 *MessageHash,
658 IN UINTN HashSize,
659 IN UINT8 *Signature,
660 IN UINTN SigSize
661 )
662 {
663 INTN Length;
664
665 //
666 // Check input parameters.
667 //
668 if (RsaContext == NULL || MessageHash == NULL || Signature == NULL) {
669 return FALSE;
670 }
671
672
673 //
674 // Check for unsupported hash size:
675 // Only MD5, SHA-1 or SHA-256 digest size is supported
676 //
677 if (HashSize != MD5_DIGEST_SIZE && HashSize != SHA1_DIGEST_SIZE && HashSize != SHA256_DIGEST_SIZE) {
678 return FALSE;
679 }
680
681 //
682 // RSA PKCS#1 Signature Decoding using OpenSSL RSA Decryption with Public Key
683 //
684 Length = RSA_public_decrypt (
685 (UINT32) SigSize,
686 Signature,
687 Signature,
688 RsaContext,
689 RSA_PKCS1_PADDING
690 );
691
692 //
693 // Invalid RSA Key or PKCS#1 Padding Checking Failed (if Length < 0)
694 // NOTE: Length should be the addition of HashSize and some DER value.
695 // Ignore more strict length checking here.
696 //
697 if (Length < (INTN) HashSize) {
698 return FALSE;
699 }
700
701 //
702 // Validate the MessageHash and Decoded Signature
703 // NOTE: The decoded Signature should be the DER encoding of the DigestInfo value
704 // DigestInfo ::= SEQUENCE {
705 // digestAlgorithm AlgorithmIdentifier
706 // digest OCTET STRING
707 // }
708 // Then Memory Comparing should skip the DER value of the underlying SEQUENCE
709 // type and AlgorithmIdentifier.
710 //
711 if (CompareMem (MessageHash, Signature + Length - HashSize, HashSize) == 0) {
712 //
713 // Valid RSA PKCS#1 Signature
714 //
715 return TRUE;
716 } else {
717 //
718 // Failed to verification
719 //
720 return FALSE;
721 }
722 }