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