source: azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/rsa.c@ 464

Last change on this file since 464 was 464, checked in by coas-nagasima, 3 years ago

WolfSSLとAzure IoT SDKを更新

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 129.6 KB
Line 
1/* rsa.c
2 *
3 * Copyright (C) 2006-2020 wolfSSL Inc.
4 *
5 * This file is part of wolfSSL.
6 *
7 * wolfSSL is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * wolfSSL is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20 */
21
22/*
23
24DESCRIPTION
25This library provides the interface to the RSA.
26RSA keys can be used to encrypt, decrypt, sign and verify data.
27
28*/
29#ifdef HAVE_CONFIG_H
30 #include <config.h>
31#endif
32
33#include <wolfssl/wolfcrypt/settings.h>
34#include <wolfssl/wolfcrypt/error-crypt.h>
35
36#ifndef NO_RSA
37
38#if defined(HAVE_FIPS) && \
39 defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
40
41 /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
42 #define FIPS_NO_WRAPPERS
43
44 #ifdef USE_WINDOWS_API
45 #pragma code_seg(".fipsA$e")
46 #pragma const_seg(".fipsB$e")
47 #endif
48#endif
49
50#include <wolfssl/wolfcrypt/rsa.h>
51
52#ifdef WOLFSSL_AFALG_XILINX_RSA
53#include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
54#endif
55
56#ifdef WOLFSSL_HAVE_SP_RSA
57#include <wolfssl/wolfcrypt/sp.h>
58#endif
59
60/*
61Possible RSA enable options:
62 * NO_RSA: Overall control of RSA default: on (not defined)
63 * WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off
64 Note: slower by ~20%
65 * WOLFSSL_KEY_GEN: Allows Private Key Generation default: off
66 * RSA_LOW_MEM: NON CRT Private Operations, less memory default: off
67 * WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined)
68 * WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off
69 * WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off
70 * time calculation.
71*/
72
73/*
74RSA Key Size Configuration:
75 * FP_MAX_BITS: With USE_FAST_MATH only default: 4096
76 If USE_FAST_MATH then use this to override default.
77 Value is key size * 2. Example: RSA 3072 = 6144
78*/
79
80
81/* If building for old FIPS. */
82#if defined(HAVE_FIPS) && \
83 (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
84
85int wc_InitRsaKey(RsaKey* key, void* ptr)
86{
87 if (key == NULL) {
88 return BAD_FUNC_ARG;
89 }
90
91 return InitRsaKey_fips(key, ptr);
92}
93
94
95int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId)
96{
97 (void)devId;
98 if (key == NULL) {
99 return BAD_FUNC_ARG;
100 }
101 return InitRsaKey_fips(key, ptr);
102}
103
104
105int wc_FreeRsaKey(RsaKey* key)
106{
107 return FreeRsaKey_fips(key);
108}
109
110
111#ifndef WOLFSSL_RSA_VERIFY_ONLY
112int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
113 word32 outLen, RsaKey* key, WC_RNG* rng)
114{
115 if (in == NULL || out == NULL || key == NULL || rng == NULL) {
116 return BAD_FUNC_ARG;
117 }
118 return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng);
119}
120#endif
121
122
123#ifndef WOLFSSL_RSA_PUBLIC_ONLY
124int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out,
125 RsaKey* key)
126{
127 if (in == NULL || out == NULL || key == NULL) {
128 return BAD_FUNC_ARG;
129 }
130 return RsaPrivateDecryptInline_fips(in, inLen, out, key);
131}
132
133
134int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
135 word32 outLen, RsaKey* key)
136{
137 if (in == NULL || out == NULL || key == NULL) {
138 return BAD_FUNC_ARG;
139 }
140 return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key);
141}
142
143
144int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
145 word32 outLen, RsaKey* key, WC_RNG* rng)
146{
147 if (in == NULL || out == NULL || key == NULL || inLen == 0) {
148 return BAD_FUNC_ARG;
149 }
150 return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng);
151}
152#endif
153
154
155int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
156{
157 if (in == NULL || out == NULL || key == NULL) {
158 return BAD_FUNC_ARG;
159 }
160 return RsaSSL_VerifyInline_fips(in, inLen, out, key);
161}
162
163
164int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out,
165 word32 outLen, RsaKey* key)
166{
167 if (in == NULL || out == NULL || key == NULL || inLen == 0) {
168 return BAD_FUNC_ARG;
169 }
170 return RsaSSL_Verify_fips(in, inLen, out, outLen, key);
171}
172
173
174int wc_RsaEncryptSize(RsaKey* key)
175{
176 if (key == NULL) {
177 return BAD_FUNC_ARG;
178 }
179 return RsaEncryptSize_fips(key);
180}
181
182
183#ifndef WOLFSSL_RSA_VERIFY_ONLY
184int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b,
185 word32* bSz)
186{
187
188 /* not specified as fips so not needing _fips */
189 return RsaFlattenPublicKey(key, a, aSz, b, bSz);
190}
191#endif
192
193
194#ifdef WOLFSSL_KEY_GEN
195 int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
196 {
197 return MakeRsaKey(key, size, e, rng);
198 }
199#endif
200
201
202/* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c
203* wc_RsaPrivateKeyDecode
204* wc_RsaPublicKeyDecode
205*/
206
207#else /* else build without fips, or for new fips */
208
209#include <wolfssl/wolfcrypt/random.h>
210#include <wolfssl/wolfcrypt/logging.h>
211#ifdef WOLF_CRYPTO_CB
212 #include <wolfssl/wolfcrypt/cryptocb.h>
213#endif
214#ifdef NO_INLINE
215 #include <wolfssl/wolfcrypt/misc.h>
216#else
217 #define WOLFSSL_MISC_INCLUDED
218 #include <wolfcrypt/src/misc.c>
219#endif
220
221
222enum {
223 RSA_STATE_NONE = 0,
224
225 RSA_STATE_ENCRYPT_PAD,
226 RSA_STATE_ENCRYPT_EXPTMOD,
227 RSA_STATE_ENCRYPT_RES,
228
229 RSA_STATE_DECRYPT_EXPTMOD,
230 RSA_STATE_DECRYPT_UNPAD,
231 RSA_STATE_DECRYPT_RES,
232};
233
234
235static void wc_RsaCleanup(RsaKey* key)
236{
237#ifndef WOLFSSL_RSA_VERIFY_INLINE
238 if (key && key->data) {
239 /* make sure any allocated memory is free'd */
240 if (key->dataIsAlloc) {
241 #ifndef WOLFSSL_RSA_PUBLIC_ONLY
242 if (key->type == RSA_PRIVATE_DECRYPT ||
243 key->type == RSA_PRIVATE_ENCRYPT) {
244 ForceZero(key->data, key->dataLen);
245 }
246 #endif
247 XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
248 key->dataIsAlloc = 0;
249 }
250 key->data = NULL;
251 key->dataLen = 0;
252 }
253#else
254 (void)key;
255#endif
256}
257
258int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
259{
260 int ret = 0;
261
262 if (key == NULL) {
263 return BAD_FUNC_ARG;
264 }
265
266 XMEMSET(key, 0, sizeof(RsaKey));
267
268 key->type = RSA_TYPE_UNKNOWN;
269 key->state = RSA_STATE_NONE;
270 key->heap = heap;
271#ifndef WOLFSSL_RSA_VERIFY_INLINE
272 key->dataIsAlloc = 0;
273 key->data = NULL;
274#endif
275 key->dataLen = 0;
276#ifdef WC_RSA_BLINDING
277 key->rng = NULL;
278#endif
279
280#ifdef WOLF_CRYPTO_CB
281 key->devId = devId;
282#else
283 (void)devId;
284#endif
285
286#ifdef WOLFSSL_ASYNC_CRYPT
287 #ifdef WOLFSSL_CERT_GEN
288 XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
289 #endif
290
291 #ifdef WC_ASYNC_ENABLE_RSA
292 /* handle as async */
293 ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA,
294 key->heap, devId);
295 if (ret != 0)
296 return ret;
297 #endif /* WC_ASYNC_ENABLE_RSA */
298#endif /* WOLFSSL_ASYNC_CRYPT */
299
300#ifndef WOLFSSL_RSA_PUBLIC_ONLY
301 ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
302 if (ret != MP_OKAY)
303 return ret;
304
305#if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
306 ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
307#else
308 ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
309#endif
310 if (ret != MP_OKAY) {
311 mp_clear(&key->n);
312 mp_clear(&key->e);
313 return ret;
314 }
315#else
316 ret = mp_init(&key->n);
317 if (ret != MP_OKAY)
318 return ret;
319 ret = mp_init(&key->e);
320 if (ret != MP_OKAY) {
321 mp_clear(&key->n);
322 return ret;
323 }
324#endif
325
326#ifdef WOLFSSL_XILINX_CRYPT
327 key->pubExp = 0;
328 key->mod = NULL;
329#endif
330
331#ifdef WOLFSSL_AFALG_XILINX_RSA
332 key->alFd = WC_SOCK_NOTSET;
333 key->rdFd = WC_SOCK_NOTSET;
334#endif
335
336 return ret;
337}
338
339int wc_InitRsaKey(RsaKey* key, void* heap)
340{
341 return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
342}
343
344#ifdef WOLF_CRYPTO_CB
345int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
346 int devId)
347{
348 int ret = 0;
349
350 if (key == NULL)
351 ret = BAD_FUNC_ARG;
352 if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
353 ret = BUFFER_E;
354
355 if (ret == 0)
356 ret = wc_InitRsaKey_ex(key, heap, devId);
357 if (ret == 0 && id != NULL && len != 0) {
358 XMEMCPY(key->id, id, len);
359 key->idLen = len;
360 }
361
362 return ret;
363}
364
365int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId)
366{
367 int ret = 0;
368 int labelLen = 0;
369
370 if (key == NULL || label == NULL)
371 ret = BAD_FUNC_ARG;
372 if (ret == 0) {
373 labelLen = (int)XSTRLEN(label);
374 if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN)
375 ret = BUFFER_E;
376 }
377
378 if (ret == 0)
379 ret = wc_InitRsaKey_ex(key, heap, devId);
380 if (ret == 0) {
381 XMEMCPY(key->label, label, labelLen);
382 key->labelLen = labelLen;
383 }
384
385 return ret;
386}
387#endif
388
389
390#ifdef WOLFSSL_XILINX_CRYPT
391#define MAX_E_SIZE 4
392/* Used to setup hardware state
393 *
394 * key the RSA key to setup
395 *
396 * returns 0 on success
397 */
398int wc_InitRsaHw(RsaKey* key)
399{
400 unsigned char* m; /* RSA modulous */
401 word32 e = 0; /* RSA public exponent */
402 int mSz;
403 int eSz;
404
405 if (key == NULL) {
406 return BAD_FUNC_ARG;
407 }
408
409 mSz = mp_unsigned_bin_size(&(key->n));
410 m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
411 if (m == NULL) {
412 return MEMORY_E;
413 }
414
415 if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
416 WOLFSSL_MSG("Unable to get RSA key modulus");
417 XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
418 return MP_READ_E;
419 }
420
421 eSz = mp_unsigned_bin_size(&(key->e));
422 if (eSz > MAX_E_SIZE) {
423 WOLFSSL_MSG("Exponent of size 4 bytes expected");
424 XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
425 return BAD_FUNC_ARG;
426 }
427
428 if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
429 != MP_OKAY) {
430 XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
431 WOLFSSL_MSG("Unable to get RSA key exponent");
432 return MP_READ_E;
433 }
434
435 /* check for existing mod buffer to avoid memory leak */
436 if (key->mod != NULL) {
437 XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
438 }
439
440 key->pubExp = e;
441 key->mod = m;
442
443 if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
444 (byte*)&(key->pubExp)) != XST_SUCCESS) {
445 WOLFSSL_MSG("Unable to initialize RSA on hardware");
446 XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
447 return BAD_STATE_E;
448 }
449
450#ifdef WOLFSSL_XILINX_PATCH
451 /* currently a patch of xsecure_rsa.c for 2048 bit keys */
452 if (wc_RsaEncryptSize(key) == 256) {
453 if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
454 WOLFSSL_MSG("Unable to set RSA key size on hardware");
455 XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
456 return BAD_STATE_E;
457 }
458 }
459#endif
460 return 0;
461} /* WOLFSSL_XILINX_CRYPT*/
462
463#elif defined(WOLFSSL_CRYPTOCELL)
464
465int wc_InitRsaHw(RsaKey* key)
466{
467 CRYSError_t ret = 0;
468 byte e[3];
469 word32 eSz = sizeof(e);
470 byte n[256];
471 word32 nSz = sizeof(n);
472 byte d[256];
473 word32 dSz = sizeof(d);
474 byte p[128];
475 word32 pSz = sizeof(p);
476 byte q[128];
477 word32 qSz = sizeof(q);
478
479 if (key == NULL) {
480 return BAD_FUNC_ARG;
481 }
482
483 ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz);
484 if (ret != 0)
485 return MP_READ_E;
486
487 ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz);
488 if (ret != SA_SILIB_RET_OK){
489 WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed");
490 return ret;
491 }
492
493 ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz);
494
495 if (ret != SA_SILIB_RET_OK){
496 WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed");
497 return ret;
498 }
499 key->type = RSA_PRIVATE;
500 return 0;
501}
502static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e)
503{
504 CRYSError_t ret = 0;
505 CRYS_RSAKGData_t KeyGenData;
506 CRYS_RSAKGFipsContext_t FipsCtx;
507 byte ex[3];
508 word16 eSz = sizeof(ex);
509 byte n[256];
510 word16 nSz = sizeof(n);
511
512 ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
513 wc_rndGenVectFunc,
514 (byte*)&e,
515 3*sizeof(byte),
516 size,
517 &key->ctx.privKey,
518 &key->ctx.pubKey,
519 &KeyGenData,
520 &FipsCtx);
521
522 if (ret != SA_SILIB_RET_OK){
523 WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed");
524 return ret;
525 }
526
527 ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz);
528 if (ret != SA_SILIB_RET_OK){
529 WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed");
530 return ret;
531 }
532 ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key);
533
534 key->type = RSA_PRIVATE;
535
536 return ret;
537}
538#endif /* WOLFSSL_CRYPTOCELL */
539
540int wc_FreeRsaKey(RsaKey* key)
541{
542 int ret = 0;
543
544 if (key == NULL) {
545 return BAD_FUNC_ARG;
546 }
547
548 wc_RsaCleanup(key);
549
550#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
551 wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
552#endif
553
554#ifndef WOLFSSL_RSA_PUBLIC_ONLY
555 if (key->type == RSA_PRIVATE) {
556#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
557 mp_forcezero(&key->u);
558 mp_forcezero(&key->dQ);
559 mp_forcezero(&key->dP);
560#endif
561 mp_forcezero(&key->q);
562 mp_forcezero(&key->p);
563 mp_forcezero(&key->d);
564 }
565 /* private part */
566#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
567 mp_clear(&key->u);
568 mp_clear(&key->dQ);
569 mp_clear(&key->dP);
570#endif
571 mp_clear(&key->q);
572 mp_clear(&key->p);
573 mp_clear(&key->d);
574#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
575
576 /* public part */
577 mp_clear(&key->e);
578 mp_clear(&key->n);
579
580#ifdef WOLFSSL_XILINX_CRYPT
581 XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
582 key->mod = NULL;
583#endif
584
585#ifdef WOLFSSL_AFALG_XILINX_RSA
586 /* make sure that sockets are closed on cleanup */
587 if (key->alFd > 0) {
588 close(key->alFd);
589 key->alFd = WC_SOCK_NOTSET;
590 }
591 if (key->rdFd > 0) {
592 close(key->rdFd);
593 key->rdFd = WC_SOCK_NOTSET;
594 }
595#endif
596
597 return ret;
598}
599
600#ifndef WOLFSSL_RSA_PUBLIC_ONLY
601#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
602/* Check the pair-wise consistency of the RSA key.
603 * From NIST SP 800-56B, section 6.4.1.1.
604 * Verify that k = (k^e)^d, for some k: 1 < k < n-1. */
605int wc_CheckRsaKey(RsaKey* key)
606{
607#if defined(WOLFSSL_CRYPTOCELL)
608 return 0;
609#endif
610#ifdef WOLFSSL_SMALL_STACK
611 mp_int *k = NULL, *tmp = NULL;
612#else
613 mp_int k[1], tmp[1];
614#endif
615 int ret = 0;
616
617#ifdef WOLFSSL_SMALL_STACK
618 k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA);
619 if (k == NULL)
620 return MEMORY_E;
621 tmp = k + 1;
622#endif
623
624 if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY)
625 ret = MP_INIT_E;
626
627 if (ret == 0) {
628 if (key == NULL)
629 ret = BAD_FUNC_ARG;
630 }
631
632 if (ret == 0) {
633 if (mp_set_int(k, 0x2342) != MP_OKAY)
634 ret = MP_READ_E;
635 }
636#ifdef WOLFSSL_HAVE_SP_RSA
637 if (ret == 0) {
638 switch (mp_count_bits(&key->n)) {
639 #ifndef WOLFSSL_SP_NO_2048
640 case 2048:
641 ret = sp_ModExp_2048(k, &key->e, &key->n, tmp);
642 if (ret != 0)
643 ret = MP_EXPTMOD_E;
644 if (ret == 0) {
645 ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp);
646 if (ret != 0)
647 ret = MP_EXPTMOD_E;
648 }
649 break;
650 #endif /* WOLFSSL_SP_NO_2048 */
651 #ifndef WOLFSSL_SP_NO_3072
652 case 3072:
653 ret = sp_ModExp_3072(k, &key->e, &key->n, tmp);
654 if (ret != 0)
655 ret = MP_EXPTMOD_E;
656 if (ret == 0) {
657 ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp);
658 if (ret != 0)
659 ret = MP_EXPTMOD_E;
660 }
661 break;
662 #endif /* WOLFSSL_SP_NO_3072 */
663 #ifdef WOLFSSL_SP_4096
664 case 4096:
665 ret = sp_ModExp_4096(k, &key->e, &key->n, tmp);
666 if (ret != 0)
667 ret = MP_EXPTMOD_E;
668 if (ret == 0) {
669 ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp);
670 if (ret != 0)
671 ret = MP_EXPTMOD_E;
672 }
673 break;
674 #endif /* WOLFSSL_SP_4096 */
675 default:
676 /* If using only single precsision math then issue key size
677 * error, otherwise fall-back to multi-precision math
678 * calculation */
679 #if defined(WOLFSSL_SP_MATH)
680 ret = WC_KEY_SIZE_E;
681 #else
682 if (mp_exptmod_nct(k, &key->e, &key->n, tmp) != MP_OKAY)
683 ret = MP_EXPTMOD_E;
684 if (ret == 0) {
685 if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
686 ret = MP_EXPTMOD_E;
687 }
688 #endif
689 break;
690 }
691 }
692#else
693 if (ret == 0) {
694 if (mp_exptmod_nct(k, &key->e, &key->n, tmp) != MP_OKAY)
695 ret = MP_EXPTMOD_E;
696 }
697
698 if (ret == 0) {
699 if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
700 ret = MP_EXPTMOD_E;
701 }
702#endif /* WOLFSSL_HAVE_SP_RSA */
703
704 if (ret == 0) {
705 if (mp_cmp(k, tmp) != MP_EQ)
706 ret = RSA_KEY_PAIR_E;
707 }
708
709 /* Check d is less than n. */
710 if (ret == 0 ) {
711 if (mp_cmp(&key->d, &key->n) != MP_LT) {
712 ret = MP_EXPTMOD_E;
713 }
714 }
715 /* Check p*q = n. */
716 if (ret == 0 ) {
717 if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
718 ret = MP_EXPTMOD_E;
719 }
720 }
721 if (ret == 0 ) {
722 if (mp_cmp(&key->n, tmp) != MP_EQ) {
723 ret = MP_EXPTMOD_E;
724 }
725 }
726
727 /* Check dP, dQ and u if they exist */
728 if (ret == 0 && !mp_iszero(&key->dP)) {
729 if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) {
730 ret = MP_EXPTMOD_E;
731 }
732 /* Check dP <= p-1. */
733 if (ret == 0) {
734 if (mp_cmp(&key->dP, tmp) != MP_LT) {
735 ret = MP_EXPTMOD_E;
736 }
737 }
738 /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
739 if (ret == 0) {
740 if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
741 ret = MP_EXPTMOD_E;
742 }
743 }
744 if (ret == 0 ) {
745 if (!mp_isone(tmp)) {
746 ret = MP_EXPTMOD_E;
747 }
748 }
749
750 if (ret == 0) {
751 if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
752 ret = MP_EXPTMOD_E;
753 }
754 }
755 /* Check dQ <= q-1. */
756 if (ret == 0) {
757 if (mp_cmp(&key->dQ, tmp) != MP_LT) {
758 ret = MP_EXPTMOD_E;
759 }
760 }
761 /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
762 if (ret == 0) {
763 if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
764 ret = MP_EXPTMOD_E;
765 }
766 }
767 if (ret == 0 ) {
768 if (!mp_isone(tmp)) {
769 ret = MP_EXPTMOD_E;
770 }
771 }
772
773 /* Check u <= p. */
774 if (ret == 0) {
775 if (mp_cmp(&key->u, &key->p) != MP_LT) {
776 ret = MP_EXPTMOD_E;
777 }
778 }
779 /* Check u*q mod p = 1. (u = 1/q mod p) */
780 if (ret == 0) {
781 if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
782 ret = MP_EXPTMOD_E;
783 }
784 }
785 if (ret == 0 ) {
786 if (!mp_isone(tmp)) {
787 ret = MP_EXPTMOD_E;
788 }
789 }
790 }
791
792 mp_forcezero(tmp);
793 mp_clear(tmp);
794 mp_clear(k);
795#ifdef WOLFSSL_SMALL_STACK
796 XFREE(k, NULL, DYNAMIC_TYPE_RSA);
797#endif
798
799 return ret;
800}
801#endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */
802#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
803
804
805#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)
806/* Uses MGF1 standard as a mask generation function
807 hType: hash type used
808 seed: seed to use for generating mask
809 seedSz: size of seed buffer
810 out: mask output after generation
811 outSz: size of output buffer
812 */
813#if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
814static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
815 byte* out, word32 outSz, void* heap)
816{
817 byte* tmp;
818 /* needs to be large enough for seed size plus counter(4) */
819 byte tmpA[WC_MAX_DIGEST_SIZE + 4];
820 byte tmpF; /* 1 if dynamic memory needs freed */
821 word32 tmpSz;
822 int hLen;
823 int ret;
824 word32 counter;
825 word32 idx;
826 hLen = wc_HashGetDigestSize(hType);
827 counter = 0;
828 idx = 0;
829
830 (void)heap;
831
832 /* check error return of wc_HashGetDigestSize */
833 if (hLen < 0) {
834 return hLen;
835 }
836
837 /* if tmp is not large enough than use some dynamic memory */
838 if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
839 /* find largest amount of memory needed which will be the max of
840 * hLen and (seedSz + 4) since tmp is used to store the hash digest */
841 tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
842 tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
843 if (tmp == NULL) {
844 return MEMORY_E;
845 }
846 tmpF = 1; /* make sure to free memory when done */
847 }
848 else {
849 /* use array on the stack */
850 tmpSz = sizeof(tmpA);
851 tmp = tmpA;
852 tmpF = 0; /* no need to free memory at end */
853 }
854
855 do {
856 int i = 0;
857 XMEMCPY(tmp, seed, seedSz);
858
859 /* counter to byte array appended to tmp */
860 tmp[seedSz] = (byte)((counter >> 24) & 0xFF);
861 tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
862 tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF);
863 tmp[seedSz + 3] = (byte)((counter) & 0xFF);
864
865 /* hash and append to existing output */
866 if ((ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz)) != 0) {
867 /* check for if dynamic memory was needed, then free */
868 if (tmpF) {
869 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
870 }
871 return ret;
872 }
873
874 for (i = 0; i < hLen && idx < outSz; i++) {
875 out[idx++] = tmp[i];
876 }
877 counter++;
878 } while (idx < outSz);
879
880 /* check for if dynamic memory was needed, then free */
881 if (tmpF) {
882 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
883 }
884
885 return 0;
886}
887#endif /* SHA2 Hashes */
888
889/* helper function to direct which mask generation function is used
890 switched on type input
891 */
892static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
893 word32 outSz, void* heap)
894{
895 int ret;
896
897 switch(type) {
898 #ifndef NO_SHA
899 case WC_MGF1SHA1:
900 ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
901 break;
902 #endif
903 #ifndef NO_SHA256
904 #ifdef WOLFSSL_SHA224
905 case WC_MGF1SHA224:
906 ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
907 break;
908 #endif
909 case WC_MGF1SHA256:
910 ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
911 break;
912 #endif
913 #ifdef WOLFSSL_SHA384
914 case WC_MGF1SHA384:
915 ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
916 break;
917 #endif
918 #ifdef WOLFSSL_SHA512
919 case WC_MGF1SHA512:
920 ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
921 break;
922 #endif
923 default:
924 WOLFSSL_MSG("Unknown MGF type: check build options");
925 ret = BAD_FUNC_ARG;
926 }
927
928 /* in case of default avoid unused warning */
929 (void)seed;
930 (void)seedSz;
931 (void)out;
932 (void)outSz;
933 (void)heap;
934
935 return ret;
936}
937#endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */
938
939
940/* Padding */
941#ifndef WOLFSSL_RSA_VERIFY_ONLY
942#ifndef WC_NO_RNG
943#ifndef WC_NO_RSA_OAEP
944static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
945 word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
946 enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
947 void* heap)
948{
949 int ret;
950 int hLen;
951 int psLen;
952 int i;
953 word32 idx;
954
955 byte* dbMask;
956
957 #ifdef WOLFSSL_SMALL_STACK
958 byte* lHash = NULL;
959 byte* seed = NULL;
960 #else
961 /* must be large enough to contain largest hash */
962 byte lHash[WC_MAX_DIGEST_SIZE];
963 byte seed[ WC_MAX_DIGEST_SIZE];
964 #endif
965
966 /* no label is allowed, but catch if no label provided and length > 0 */
967 if (optLabel == NULL && labelLen > 0) {
968 return BUFFER_E;
969 }
970
971 /* limit of label is the same as limit of hash function which is massive */
972 hLen = wc_HashGetDigestSize(hType);
973 if (hLen < 0) {
974 return hLen;
975 }
976
977 #ifdef WOLFSSL_SMALL_STACK
978 lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
979 if (lHash == NULL) {
980 return MEMORY_E;
981 }
982 seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
983 if (seed == NULL) {
984 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
985 return MEMORY_E;
986 }
987 #else
988 /* hLen should never be larger than lHash since size is max digest size,
989 but check before blindly calling wc_Hash */
990 if ((word32)hLen > sizeof(lHash)) {
991 WOLFSSL_MSG("OAEP lHash to small for digest!!");
992 return MEMORY_E;
993 }
994 #endif
995
996 if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
997 WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
998 #ifdef WOLFSSL_SMALL_STACK
999 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1000 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1001 #endif
1002 return ret;
1003 }
1004
1005 /* handles check of location for idx as well as psLen, cast to int to check
1006 for pkcsBlockLen(k) - 2 * hLen - 2 being negative
1007 This check is similar to decryption where k > 2 * hLen + 2 as msg
1008 size approaches 0. In decryption if k is less than or equal -- then there
1009 is no possible room for msg.
1010 k = RSA key size
1011 hLen = hash digest size -- will always be >= 0 at this point
1012 */
1013 if ((word32)(2 * hLen + 2) > pkcsBlockLen) {
1014 WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
1015 #ifdef WOLFSSL_SMALL_STACK
1016 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1017 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1018 #endif
1019 return BAD_FUNC_ARG;
1020 }
1021
1022 if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
1023 WOLFSSL_MSG("OAEP pad error message too long");
1024 #ifdef WOLFSSL_SMALL_STACK
1025 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1026 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1027 #endif
1028 return BAD_FUNC_ARG;
1029 }
1030
1031 /* concatenate lHash || PS || 0x01 || msg */
1032 idx = pkcsBlockLen - 1 - inputLen;
1033 psLen = pkcsBlockLen - inputLen - 2 * hLen - 2;
1034 if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
1035 #ifdef WOLFSSL_SMALL_STACK
1036 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1037 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1038 #endif
1039 return BUFFER_E;
1040 }
1041 XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
1042 pkcsBlock[idx--] = 0x01; /* PS and M separator */
1043 while (psLen > 0 && idx > 0) {
1044 pkcsBlock[idx--] = 0x00;
1045 psLen--;
1046 }
1047
1048 idx = idx - hLen + 1;
1049 XMEMCPY(pkcsBlock + idx, lHash, hLen);
1050
1051 /* generate random seed */
1052 if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
1053 #ifdef WOLFSSL_SMALL_STACK
1054 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1055 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1056 #endif
1057 return ret;
1058 }
1059
1060 /* create maskedDB from dbMask */
1061 dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
1062 if (dbMask == NULL) {
1063 #ifdef WOLFSSL_SMALL_STACK
1064 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1065 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1066 #endif
1067 return MEMORY_E;
1068 }
1069 XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
1070
1071 ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
1072 if (ret != 0) {
1073 XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
1074 #ifdef WOLFSSL_SMALL_STACK
1075 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1076 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1077 #endif
1078 return ret;
1079 }
1080
1081 i = 0;
1082 idx = hLen + 1;
1083 while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) {
1084 pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx];
1085 idx++;
1086 }
1087 XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
1088
1089
1090 /* create maskedSeed from seedMask */
1091 idx = 0;
1092 pkcsBlock[idx++] = 0x00;
1093 /* create seedMask inline */
1094 if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
1095 pkcsBlock + 1, hLen, heap)) != 0) {
1096 #ifdef WOLFSSL_SMALL_STACK
1097 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1098 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1099 #endif
1100 return ret;
1101 }
1102
1103 /* xor created seedMask with seed to make maskedSeed */
1104 i = 0;
1105 while (idx < (word32)(hLen + 1) && i < hLen) {
1106 pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++];
1107 idx++;
1108 }
1109
1110 #ifdef WOLFSSL_SMALL_STACK
1111 XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1112 XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1113 #endif
1114 (void)padValue;
1115
1116 return 0;
1117}
1118#endif /* !WC_NO_RSA_OAEP */
1119
1120#ifdef WC_RSA_PSS
1121
1122/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
1123 * XOR MGF over all bytes down to end of Salt
1124 * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
1125 *
1126 * input Digest of the message.
1127 * inputLen Length of digest.
1128 * pkcsBlock Buffer to write to.
1129 * pkcsBlockLen Length of buffer to write to.
1130 * rng Random number generator (for salt).
1131 * htype Hash function to use.
1132 * mgf Mask generation function.
1133 * saltLen Length of salt to put in padding.
1134 * bits Length of key in bits.
1135 * heap Used for dynamic memory allocation.
1136 * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
1137 * and other negative values on error.
1138 */
1139static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
1140 word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
1141 int saltLen, int bits, void* heap)
1142{
1143 int ret = 0;
1144 int hLen, i, o, maskLen, hiBits;
1145 byte* m;
1146 byte* s;
1147#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
1148 byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1149#else
1150 byte* msg = NULL;
1151#endif
1152#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1153 byte* salt;
1154#else
1155 byte salt[WC_MAX_DIGEST_SIZE];
1156#endif
1157
1158#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1159 if (pkcsBlockLen > RSA_MAX_SIZE/8) {
1160 return MEMORY_E;
1161 }
1162#endif
1163
1164 hLen = wc_HashGetDigestSize(hType);
1165 if (hLen < 0)
1166 return hLen;
1167 if ((int)inputLen != hLen) {
1168 return BAD_FUNC_ARG;
1169 }
1170
1171 hiBits = (bits - 1) & 0x7;
1172 if (hiBits == 0) {
1173 /* Per RFC8017, set the leftmost 8emLen - emBits bits of the
1174 leftmost octet in DB to zero.
1175 */
1176 *(pkcsBlock++) = 0;
1177 pkcsBlockLen--;
1178 }
1179
1180 if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
1181 saltLen = hLen;
1182 #ifdef WOLFSSL_SHA512
1183 /* See FIPS 186-4 section 5.5 item (e). */
1184 if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
1185 saltLen = RSA_PSS_SALT_MAX_SZ;
1186 }
1187 #endif
1188 }
1189#ifndef WOLFSSL_PSS_LONG_SALT
1190 else if (saltLen > hLen) {
1191 return PSS_SALTLEN_E;
1192 }
1193#endif
1194#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
1195 else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
1196 return PSS_SALTLEN_E;
1197 }
1198#else
1199 else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
1200 saltLen = (int)pkcsBlockLen - hLen - 2;
1201 if (saltLen < 0) {
1202 return PSS_SALTLEN_E;
1203 }
1204 }
1205 else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
1206 return PSS_SALTLEN_E;
1207 }
1208#endif
1209 if ((int)pkcsBlockLen - hLen < saltLen + 2) {
1210 return PSS_SALTLEN_E;
1211 }
1212 maskLen = pkcsBlockLen - 1 - hLen;
1213
1214#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1215 #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1216 msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
1217 DYNAMIC_TYPE_RSA_BUFFER);
1218 if (msg == NULL) {
1219 return MEMORY_E;
1220 }
1221 #endif
1222 salt = s = m = msg;
1223 XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1224 m += RSA_PSS_PAD_SZ;
1225 XMEMCPY(m, input, inputLen);
1226 m += inputLen;
1227 o = (int)(m - s);
1228 if (saltLen > 0) {
1229 ret = wc_RNG_GenerateBlock(rng, m, saltLen);
1230 if (ret == 0) {
1231 m += saltLen;
1232 }
1233 }
1234#else
1235 if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) {
1236 #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1237 msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
1238 DYNAMIC_TYPE_RSA_BUFFER);
1239 if (msg == NULL) {
1240 return MEMORY_E;
1241 }
1242 #endif
1243 m = msg;
1244 }
1245 else {
1246 m = pkcsBlock;
1247 }
1248 s = m;
1249 XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1250 m += RSA_PSS_PAD_SZ;
1251 XMEMCPY(m, input, inputLen);
1252 m += inputLen;
1253 o = 0;
1254 if (saltLen > 0) {
1255 ret = wc_RNG_GenerateBlock(rng, salt, saltLen);
1256 if (ret == 0) {
1257 XMEMCPY(m, salt, saltLen);
1258 m += saltLen;
1259 }
1260 }
1261#endif
1262 if (ret == 0) {
1263 /* Put Hash at end of pkcsBlock - 1 */
1264 ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen);
1265 }
1266 if (ret == 0) {
1267 /* Set the last eight bits or trailer field to the octet 0xbc */
1268 pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
1269
1270 ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap);
1271 }
1272 if (ret == 0) {
1273 /* Clear the first high bit when "8emLen - emBits" is non-zero.
1274 where emBits = n modBits - 1 */
1275 if (hiBits)
1276 pkcsBlock[0] &= (1 << hiBits) - 1;
1277
1278 m = pkcsBlock + maskLen - saltLen - 1;
1279 *(m++) ^= 0x01;
1280 for (i = 0; i < saltLen; i++) {
1281 m[i] ^= salt[o + i];
1282 }
1283 }
1284
1285 #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1286 if (msg != NULL) {
1287 XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER);
1288 }
1289 #endif
1290 return ret;
1291}
1292#endif /* WC_RSA_PSS */
1293#endif /* !WC_NO_RNG */
1294
1295static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
1296 word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
1297{
1298 if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
1299 pkcsBlockLen == 0) {
1300 return BAD_FUNC_ARG;
1301 }
1302
1303 if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
1304 WOLFSSL_MSG("RsaPad error, invalid length");
1305 return RSA_PAD_E;
1306 }
1307 pkcsBlock[0] = 0x0; /* set first byte to zero and advance */
1308 pkcsBlock++; pkcsBlockLen--;
1309 pkcsBlock[0] = padValue; /* insert padValue */
1310
1311 if (padValue == RSA_BLOCK_TYPE_1) {
1312
1313 /* pad with 0xff bytes */
1314 XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
1315 }
1316 else {
1317#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
1318 /* pad with non-zero random bytes */
1319 word32 padLen, i;
1320 int ret;
1321 padLen = pkcsBlockLen - inputLen - 1;
1322 ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
1323 if (ret != 0) {
1324 return ret;
1325 }
1326
1327 /* remove zeros */
1328 for (i = 1; i < padLen; i++) {
1329 if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
1330 }
1331#else
1332 (void)rng;
1333 return RSA_WRONG_TYPE_E;
1334#endif
1335 }
1336
1337 pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */
1338 XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
1339
1340 return 0;
1341}
1342
1343/* helper function to direct which padding is used */
1344int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
1345 word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
1346 enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
1347 int saltLen, int bits, void* heap)
1348{
1349 int ret;
1350
1351 switch (padType)
1352 {
1353 case WC_RSA_PKCSV15_PAD:
1354 /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
1355 ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
1356 padValue, rng);
1357 break;
1358
1359#ifndef WC_NO_RNG
1360 #ifndef WC_NO_RSA_OAEP
1361 case WC_RSA_OAEP_PAD:
1362 WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
1363 ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
1364 padValue, rng, hType, mgf, optLabel, labelLen, heap);
1365 break;
1366 #endif
1367
1368 #ifdef WC_RSA_PSS
1369 case WC_RSA_PSS_PAD:
1370 WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
1371 ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
1372 hType, mgf, saltLen, bits, heap);
1373 break;
1374 #endif
1375#endif /* !WC_NO_RNG */
1376
1377 #ifdef WC_RSA_NO_PADDING
1378 case WC_RSA_NO_PAD:
1379 WOLFSSL_MSG("wolfSSL Using NO padding");
1380
1381 /* In the case of no padding being used check that input is exactly
1382 * the RSA key length */
1383 if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) {
1384 WOLFSSL_MSG("Bad input size");
1385 ret = RSA_PAD_E;
1386 }
1387 else {
1388 XMEMCPY(pkcsBlock, input, inputLen);
1389 ret = 0;
1390 }
1391 break;
1392 #endif
1393
1394 default:
1395 WOLFSSL_MSG("Unknown RSA Pad Type");
1396 ret = RSA_PAD_E;
1397 }
1398
1399 /* silence warning if not used with padding scheme */
1400 (void)input;
1401 (void)inputLen;
1402 (void)pkcsBlock;
1403 (void)pkcsBlockLen;
1404 (void)padValue;
1405 (void)rng;
1406 (void)padType;
1407 (void)hType;
1408 (void)mgf;
1409 (void)optLabel;
1410 (void)labelLen;
1411 (void)saltLen;
1412 (void)bits;
1413 (void)heap;
1414
1415 return ret;
1416}
1417#endif /* WOLFSSL_RSA_VERIFY_ONLY */
1418
1419
1420/* UnPadding */
1421#ifndef WC_NO_RSA_OAEP
1422/* UnPad plaintext, set start to *output, return length of plaintext,
1423 * < 0 on error */
1424static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
1425 byte **output, enum wc_HashType hType, int mgf,
1426 byte* optLabel, word32 labelLen, void* heap)
1427{
1428 int hLen;
1429 int ret;
1430 byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
1431 byte* tmp;
1432 word32 idx;
1433
1434 /* no label is allowed, but catch if no label provided and length > 0 */
1435 if (optLabel == NULL && labelLen > 0) {
1436 return BUFFER_E;
1437 }
1438
1439 hLen = wc_HashGetDigestSize(hType);
1440 if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) {
1441 return BAD_FUNC_ARG;
1442 }
1443
1444 tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1445 if (tmp == NULL) {
1446 return MEMORY_E;
1447 }
1448 XMEMSET(tmp, 0, pkcsBlockLen);
1449
1450 /* find seedMask value */
1451 if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
1452 pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) {
1453 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1454 return ret;
1455 }
1456
1457 /* xor seedMask value with maskedSeed to get seed value */
1458 for (idx = 0; idx < (word32)hLen; idx++) {
1459 tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx];
1460 }
1461
1462 /* get dbMask value */
1463 if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen,
1464 pkcsBlockLen - hLen - 1, heap)) != 0) {
1465 XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER);
1466 return ret;
1467 }
1468
1469 /* get DB value by doing maskedDB xor dbMask */
1470 for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) {
1471 pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen];
1472 }
1473
1474 /* done with use of tmp buffer */
1475 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1476
1477 /* advance idx to index of PS and msg separator, account for PS size of 0*/
1478 idx = hLen + 1 + hLen;
1479 while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;}
1480
1481 /* create hash of label for comparison with hash sent */
1482 if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) {
1483 return ret;
1484 }
1485
1486 /* say no to chosen ciphertext attack.
1487 Comparison of lHash, Y, and separator value needs to all happen in
1488 constant time.
1489 Attackers should not be able to get error condition from the timing of
1490 these checks.
1491 */
1492 ret = 0;
1493 ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen);
1494 ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */
1495 ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */
1496
1497 /* Return 0 data length on error. */
1498 idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen);
1499
1500 /* adjust pointer to correct location in array and return size of M */
1501 *output = (byte*)(pkcsBlock + idx);
1502 return pkcsBlockLen - idx;
1503}
1504#endif /* WC_NO_RSA_OAEP */
1505
1506#ifdef WC_RSA_PSS
1507/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
1508 * MGF over all bytes down to end of Salt
1509 *
1510 * pkcsBlock Buffer holding decrypted data.
1511 * pkcsBlockLen Length of buffer.
1512 * htype Hash function to use.
1513 * mgf Mask generation function.
1514 * saltLen Length of salt to put in padding.
1515 * bits Length of key in bits.
1516 * heap Used for dynamic memory allocation.
1517 * returns the sum of salt length and SHA-256 digest size on success.
1518 * Otherwise, PSS_SALTLEN_E for an incorrect salt length,
1519 * WC_KEY_SIZE_E for an incorrect encoded message (EM) size
1520 and other negative values on error.
1521 */
1522static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
1523 byte **output, enum wc_HashType hType, int mgf,
1524 int saltLen, int bits, void* heap)
1525{
1526 int ret;
1527 byte* tmp;
1528 int hLen, i, maskLen;
1529#ifdef WOLFSSL_SHA512
1530 int orig_bits = bits;
1531#endif
1532#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
1533 byte tmp_buf[RSA_MAX_SIZE/8];
1534 tmp = tmp_buf;
1535
1536 if (pkcsBlockLen > RSA_MAX_SIZE/8) {
1537 return MEMORY_E;
1538 }
1539#endif
1540
1541 hLen = wc_HashGetDigestSize(hType);
1542 if (hLen < 0)
1543 return hLen;
1544 bits = (bits - 1) & 0x7;
1545 if ((pkcsBlock[0] & (0xff << bits)) != 0) {
1546 return BAD_PADDING_E;
1547 }
1548 if (bits == 0) {
1549 pkcsBlock++;
1550 pkcsBlockLen--;
1551 }
1552 maskLen = (int)pkcsBlockLen - 1 - hLen;
1553 if (maskLen < 0) {
1554 WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
1555 return WC_KEY_SIZE_E;
1556 }
1557
1558 if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
1559 saltLen = hLen;
1560 #ifdef WOLFSSL_SHA512
1561 /* See FIPS 186-4 section 5.5 item (e). */
1562 if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
1563 saltLen = RSA_PSS_SALT_MAX_SZ;
1564 #endif
1565 }
1566#ifndef WOLFSSL_PSS_LONG_SALT
1567 else if (saltLen > hLen)
1568 return PSS_SALTLEN_E;
1569#endif
1570#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
1571 else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
1572 return PSS_SALTLEN_E;
1573 if (maskLen < saltLen + 1) {
1574 return PSS_SALTLEN_E;
1575 }
1576#else
1577 else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
1578 return PSS_SALTLEN_E;
1579 if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
1580 return WC_KEY_SIZE_E;
1581 }
1582#endif
1583
1584 if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
1585 WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
1586 return BAD_PADDING_E;
1587 }
1588
1589#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1590 tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1591 if (tmp == NULL) {
1592 return MEMORY_E;
1593 }
1594#endif
1595
1596 if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen,
1597 heap)) != 0) {
1598 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1599 return ret;
1600 }
1601
1602 tmp[0] &= (1 << bits) - 1;
1603 pkcsBlock[0] &= (1 << bits) - 1;
1604#ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
1605 if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
1606 for (i = 0; i < maskLen - 1; i++) {
1607 if (tmp[i] != pkcsBlock[i]) {
1608 break;
1609 }
1610 }
1611 if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
1612 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1613 WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
1614 return PSS_SALTLEN_RECOVER_E;
1615 }
1616 saltLen = maskLen - (i + 1);
1617 }
1618 else
1619#endif
1620 {
1621 for (i = 0; i < maskLen - 1 - saltLen; i++) {
1622 if (tmp[i] != pkcsBlock[i]) {
1623 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1624 WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
1625 return PSS_SALTLEN_E;
1626 }
1627 }
1628 if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
1629 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1630 WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
1631 return PSS_SALTLEN_E;
1632 }
1633 }
1634 for (i++; i < maskLen; i++)
1635 pkcsBlock[i] ^= tmp[i];
1636
1637#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1638 XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1639#endif
1640
1641 *output = pkcsBlock + maskLen - saltLen;
1642 return saltLen + hLen;
1643}
1644#endif
1645
1646/* UnPad plaintext, set start to *output, return length of plaintext,
1647 * < 0 on error */
1648static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
1649 byte **output, byte padValue)
1650{
1651 int ret = BAD_FUNC_ARG;
1652 word16 i;
1653#ifndef WOLFSSL_RSA_VERIFY_ONLY
1654 byte invalid = 0;
1655#endif
1656
1657 if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
1658 return BAD_FUNC_ARG;
1659 }
1660
1661 if (padValue == RSA_BLOCK_TYPE_1) {
1662 /* First byte must be 0x00 and Second byte, block type, 0x01 */
1663 if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
1664 WOLFSSL_MSG("RsaUnPad error, invalid formatting");
1665 return RSA_PAD_E;
1666 }
1667
1668 /* check the padding until we find the separator */
1669 for (i = 2; i < pkcsBlockLen && pkcsBlock[i++] == 0xFF; ) { }
1670
1671 /* Minimum of 11 bytes of pre-message data and must have separator. */
1672 if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
1673 WOLFSSL_MSG("RsaUnPad error, bad formatting");
1674 return RSA_PAD_E;
1675 }
1676
1677 *output = (byte *)(pkcsBlock + i);
1678 ret = pkcsBlockLen - i;
1679 }
1680#ifndef WOLFSSL_RSA_VERIFY_ONLY
1681 else {
1682 word16 j;
1683 word16 pastSep = 0;
1684
1685 /* Decrypted with private key - unpad must be constant time. */
1686 for (i = 0, j = 2; j < pkcsBlockLen; j++) {
1687 /* Update i if not passed the separator and at separator. */
1688 i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1);
1689 pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
1690 }
1691
1692 /* Minimum of 11 bytes of pre-message data - including leading 0x00. */
1693 invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ);
1694 /* Must have seen separator. */
1695 invalid |= ~pastSep;
1696 /* First byte must be 0x00. */
1697 invalid |= ctMaskNotEq(pkcsBlock[0], 0x00);
1698 /* Check against expected block type: padValue */
1699 invalid |= ctMaskNotEq(pkcsBlock[1], padValue);
1700
1701 *output = (byte *)(pkcsBlock + i);
1702 ret = ((int)~invalid) & (pkcsBlockLen - i);
1703 }
1704#endif
1705
1706 return ret;
1707}
1708
1709/* helper function to direct unpadding
1710 *
1711 * bits is the key modulus size in bits
1712 */
1713int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
1714 byte padValue, int padType, enum wc_HashType hType,
1715 int mgf, byte* optLabel, word32 labelLen, int saltLen,
1716 int bits, void* heap)
1717{
1718 int ret;
1719
1720 switch (padType) {
1721 case WC_RSA_PKCSV15_PAD:
1722 /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
1723 ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue);
1724 break;
1725
1726 #ifndef WC_NO_RSA_OAEP
1727 case WC_RSA_OAEP_PAD:
1728 WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
1729 ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
1730 hType, mgf, optLabel, labelLen, heap);
1731 break;
1732 #endif
1733
1734 #ifdef WC_RSA_PSS
1735 case WC_RSA_PSS_PAD:
1736 WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
1737 ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
1738 saltLen, bits, heap);
1739 break;
1740 #endif
1741
1742 #ifdef WC_RSA_NO_PADDING
1743 case WC_RSA_NO_PAD:
1744 WOLFSSL_MSG("wolfSSL Using NO un-padding");
1745
1746 /* In the case of no padding being used check that input is exactly
1747 * the RSA key length */
1748 if (bits <= 0 || pkcsBlockLen !=
1749 ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
1750 WOLFSSL_MSG("Bad input size");
1751 ret = RSA_PAD_E;
1752 }
1753 else {
1754 if (out != NULL) {
1755 *out = pkcsBlock;
1756 }
1757 ret = pkcsBlockLen;
1758 }
1759 break;
1760 #endif /* WC_RSA_NO_PADDING */
1761
1762 default:
1763 WOLFSSL_MSG("Unknown RSA UnPad Type");
1764 ret = RSA_PAD_E;
1765 }
1766
1767 /* silence warning if not used with padding scheme */
1768 (void)hType;
1769 (void)mgf;
1770 (void)optLabel;
1771 (void)labelLen;
1772 (void)saltLen;
1773 (void)bits;
1774 (void)heap;
1775
1776 return ret;
1777}
1778
1779int wc_hash2mgf(enum wc_HashType hType)
1780{
1781 switch (hType) {
1782 case WC_HASH_TYPE_NONE:
1783 return WC_MGF1NONE;
1784 case WC_HASH_TYPE_SHA:
1785#ifndef NO_SHA
1786 return WC_MGF1SHA1;
1787#else
1788 break;
1789#endif
1790 case WC_HASH_TYPE_SHA224:
1791#ifdef WOLFSSL_SHA224
1792 return WC_MGF1SHA224;
1793#else
1794 break;
1795#endif
1796 case WC_HASH_TYPE_SHA256:
1797#ifndef NO_SHA256
1798 return WC_MGF1SHA256;
1799#else
1800 break;
1801#endif
1802 case WC_HASH_TYPE_SHA384:
1803#ifdef WOLFSSL_SHA384
1804 return WC_MGF1SHA384;
1805#else
1806 break;
1807#endif
1808 case WC_HASH_TYPE_SHA512:
1809#ifdef WOLFSSL_SHA512
1810 return WC_MGF1SHA512;
1811#else
1812 break;
1813#endif
1814 case WC_HASH_TYPE_MD2:
1815 case WC_HASH_TYPE_MD4:
1816 case WC_HASH_TYPE_MD5:
1817 case WC_HASH_TYPE_MD5_SHA:
1818 case WC_HASH_TYPE_SHA3_224:
1819 case WC_HASH_TYPE_SHA3_256:
1820 case WC_HASH_TYPE_SHA3_384:
1821 case WC_HASH_TYPE_SHA3_512:
1822 case WC_HASH_TYPE_BLAKE2B:
1823 case WC_HASH_TYPE_BLAKE2S:
1824 default:
1825 break;
1826 }
1827 WOLFSSL_MSG("Unrecognized or unsupported hash function");
1828 return WC_MGF1NONE;
1829}
1830
1831#ifdef WC_RSA_NONBLOCK
1832static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
1833 word32* outLen, int type, RsaKey* key)
1834{
1835 int ret = 0;
1836 word32 keyLen, len;
1837
1838 if (key == NULL || key->nb == NULL) {
1839 return BAD_FUNC_ARG;
1840 }
1841
1842 if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
1843 if (mp_init(&key->nb->tmp) != MP_OKAY) {
1844 ret = MP_INIT_E;
1845 }
1846
1847 if (ret == 0) {
1848 if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
1849 ret = MP_READ_E;
1850 }
1851 }
1852 }
1853
1854 if (ret == 0) {
1855 switch(type) {
1856 case RSA_PRIVATE_DECRYPT:
1857 case RSA_PRIVATE_ENCRYPT:
1858 ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
1859 &key->n, &key->nb->tmp);
1860 if (ret == FP_WOULDBLOCK)
1861 return ret;
1862 if (ret != MP_OKAY)
1863 ret = MP_EXPTMOD_E;
1864 break;
1865
1866 case RSA_PUBLIC_ENCRYPT:
1867 case RSA_PUBLIC_DECRYPT:
1868 ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
1869 &key->n, &key->nb->tmp);
1870 if (ret == FP_WOULDBLOCK)
1871 return ret;
1872 if (ret != MP_OKAY)
1873 ret = MP_EXPTMOD_E;
1874 break;
1875 default:
1876 ret = RSA_WRONG_TYPE_E;
1877 break;
1878 }
1879 }
1880
1881 if (ret == 0) {
1882 keyLen = wc_RsaEncryptSize(key);
1883 if (keyLen > *outLen)
1884 ret = RSA_BUFFER_E;
1885 }
1886 if (ret == 0) {
1887 len = mp_unsigned_bin_size(&key->nb->tmp);
1888
1889 /* pad front w/ zeros to match key length */
1890 while (len < keyLen) {
1891 *out++ = 0x00;
1892 len++;
1893 }
1894
1895 *outLen = keyLen;
1896
1897 /* convert */
1898 if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
1899 ret = MP_TO_E;
1900 }
1901 }
1902
1903 mp_clear(&key->nb->tmp);
1904
1905 return ret;
1906}
1907#endif /* WC_RSA_NONBLOCK */
1908
1909#ifdef WOLFSSL_XILINX_CRYPT
1910/*
1911 * Xilinx hardened crypto acceleration.
1912 *
1913 * Returns 0 on success and negative values on error.
1914 */
1915static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
1916 word32* outLen, int type, RsaKey* key, WC_RNG* rng)
1917{
1918 int ret = 0;
1919 word32 keyLen;
1920 (void)rng;
1921
1922 keyLen = wc_RsaEncryptSize(key);
1923 if (keyLen > *outLen) {
1924 WOLFSSL_MSG("Output buffer is not big enough");
1925 return BAD_FUNC_ARG;
1926 }
1927
1928 if (inLen != keyLen) {
1929 WOLFSSL_MSG("Expected that inLen equals RSA key length");
1930 return BAD_FUNC_ARG;
1931 }
1932
1933 switch(type) {
1934 case RSA_PRIVATE_DECRYPT:
1935 case RSA_PRIVATE_ENCRYPT:
1936 #ifdef WOLFSSL_XILINX_CRYPTO_OLD
1937 /* Currently public exponent is loaded by default.
1938 * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
1939 * leading to private key operations with Xsecure_RsaDecrypt not being
1940 * supported */
1941 ret = RSA_WRONG_TYPE_E;
1942 #else
1943 {
1944 byte *d;
1945 int dSz;
1946 XSecure_Rsa rsa;
1947
1948 dSz = mp_unsigned_bin_size(&key->d);
1949 d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
1950 if (d == NULL) {
1951 ret = MEMORY_E;
1952 }
1953 else {
1954 ret = mp_to_unsigned_bin(&key->d, d);
1955 XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
1956 }
1957
1958 if (ret == 0) {
1959 if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
1960 XST_SUCCESS) {
1961 ret = BAD_STATE_E;
1962 }
1963 }
1964
1965 if (d != NULL) {
1966 XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
1967 }
1968 }
1969 #endif
1970 break;
1971 case RSA_PUBLIC_ENCRYPT:
1972 case RSA_PUBLIC_DECRYPT:
1973#ifdef WOLFSSL_XILINX_CRYPTO_OLD
1974 if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
1975 ret = BAD_STATE_E;
1976 }
1977#else
1978 /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
1979 if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
1980 WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
1981 ret = BAD_STATE_E;
1982 }
1983#endif
1984 break;
1985 default:
1986 ret = RSA_WRONG_TYPE_E;
1987 }
1988
1989 *outLen = keyLen;
1990
1991 return ret;
1992}
1993
1994#elif defined(WOLFSSL_AFALG_XILINX_RSA)
1995#ifndef ERROR_OUT
1996#define ERROR_OUT(x) ret = (x); goto done
1997#endif
1998
1999static const char WC_TYPE_ASYMKEY[] = "skcipher";
2000static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
2001#ifndef MAX_XILINX_RSA_KEY
2002 /* max key size of 4096 bits / 512 bytes */
2003 #define MAX_XILINX_RSA_KEY 512
2004#endif
2005static const byte XILINX_RSA_FLAG[] = {0x1};
2006
2007
2008/* AF_ALG implementation of RSA */
2009static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2010 word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2011{
2012 struct msghdr msg;
2013 struct cmsghdr* cmsg;
2014 struct iovec iov;
2015 byte* keyBuf = NULL;
2016 word32 keyBufSz = 0;
2017 char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
2018 int ret = 0;
2019 int op = 0; /* decryption vs encryption flag */
2020 word32 keyLen;
2021
2022 /* input and output buffer need to be aligned */
2023 ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
2024 ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
2025
2026 XMEMSET(&msg, 0, sizeof(struct msghdr));
2027 (void)rng;
2028
2029 keyLen = wc_RsaEncryptSize(key);
2030 if (keyLen > *outLen) {
2031 ERROR_OUT(RSA_BUFFER_E);
2032 }
2033
2034 if (keyLen > MAX_XILINX_RSA_KEY) {
2035 WOLFSSL_MSG("RSA key size larger than supported");
2036 ERROR_OUT(BAD_FUNC_ARG);
2037 }
2038
2039 if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
2040 == NULL) {
2041 ERROR_OUT(MEMORY_E);
2042 }
2043
2044 if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
2045 ERROR_OUT(MP_TO_E);
2046 }
2047
2048 switch(type) {
2049 case RSA_PRIVATE_DECRYPT:
2050 case RSA_PRIVATE_ENCRYPT:
2051 op = 1; /* set as decrypt */
2052 {
2053 keyBufSz = mp_unsigned_bin_size(&(key->d));
2054 if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
2055 != MP_OKAY) {
2056 ERROR_OUT(MP_TO_E);
2057 }
2058 }
2059 break;
2060
2061 case RSA_PUBLIC_DECRYPT:
2062 case RSA_PUBLIC_ENCRYPT: {
2063 word32 exp = 0;
2064 word32 eSz = mp_unsigned_bin_size(&(key->e));
2065 if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
2066 (sizeof(word32) - eSz))) != MP_OKAY) {
2067 ERROR_OUT(MP_TO_E);
2068 }
2069 keyBufSz = sizeof(word32);
2070 XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
2071 break;
2072 }
2073
2074 default:
2075 ERROR_OUT(RSA_WRONG_TYPE_E);
2076 }
2077 keyBufSz += keyLen; /* add size of modulus */
2078
2079 /* check for existing sockets before creating new ones */
2080 if (key->alFd > 0) {
2081 close(key->alFd);
2082 key->alFd = WC_SOCK_NOTSET;
2083 }
2084 if (key->rdFd > 0) {
2085 close(key->rdFd);
2086 key->rdFd = WC_SOCK_NOTSET;
2087 }
2088
2089 /* create new sockets and set the key to use */
2090 if ((key->alFd = wc_Afalg_Socket()) < 0) {
2091 WOLFSSL_MSG("Unable to create socket");
2092 ERROR_OUT(key->alFd);
2093 }
2094 if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
2095 WC_NAME_RSA)) < 0) {
2096 WOLFSSL_MSG("Unable to bind and create read/send socket");
2097 ERROR_OUT(key->rdFd);
2098 }
2099 if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
2100 keyBufSz)) < 0) {
2101 WOLFSSL_MSG("Error setting RSA key");
2102 ERROR_OUT(ret);
2103 }
2104
2105 msg.msg_control = cbuf;
2106 msg.msg_controllen = sizeof(cbuf);
2107 cmsg = CMSG_FIRSTHDR(&msg);
2108 if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
2109 ERROR_OUT(ret);
2110 }
2111
2112 /* set flag in IV spot, needed for Xilinx hardware acceleration use */
2113 cmsg = CMSG_NXTHDR(&msg, cmsg);
2114 if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
2115 sizeof(XILINX_RSA_FLAG))) != 0) {
2116 ERROR_OUT(ret);
2117 }
2118
2119 /* compose and send msg */
2120 XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
2121 iov.iov_base = inBuf;
2122 iov.iov_len = inLen;
2123 msg.msg_iov = &iov;
2124 msg.msg_iovlen = 1;
2125 if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
2126 ERROR_OUT(WC_AFALG_SOCK_E);
2127 }
2128
2129 if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
2130 ERROR_OUT(WC_AFALG_SOCK_E);
2131 }
2132 XMEMCPY(out, outBuf, ret);
2133 *outLen = keyLen;
2134
2135done:
2136 /* clear key data and free buffer */
2137 if (keyBuf != NULL) {
2138 ForceZero(keyBuf, keyBufSz);
2139 }
2140 XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
2141
2142 if (key->alFd > 0) {
2143 close(key->alFd);
2144 key->alFd = WC_SOCK_NOTSET;
2145 }
2146 if (key->rdFd > 0) {
2147 close(key->rdFd);
2148 key->rdFd = WC_SOCK_NOTSET;
2149 }
2150
2151 return ret;
2152}
2153
2154#else
2155static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2156 word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2157{
2158#if !defined(WOLFSSL_SP_MATH)
2159#ifdef WOLFSSL_SMALL_STACK
2160 mp_int* tmp;
2161#ifdef WC_RSA_BLINDING
2162 mp_int* rnd;
2163 mp_int* rndi;
2164#endif
2165#else
2166 mp_int tmp[1];
2167#ifdef WC_RSA_BLINDING
2168 mp_int rnd[1], rndi[1];
2169#endif
2170#endif
2171 int ret = 0;
2172 word32 keyLen = 0;
2173#endif
2174
2175#ifdef WOLFSSL_HAVE_SP_RSA
2176#ifndef WOLFSSL_SP_NO_2048
2177 if (mp_count_bits(&key->n) == 2048) {
2178 switch(type) {
2179#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2180 case RSA_PRIVATE_DECRYPT:
2181 case RSA_PRIVATE_ENCRYPT:
2182 #ifdef WC_RSA_BLINDING
2183 if (rng == NULL)
2184 return MISSING_RNG_E;
2185 #endif
2186 #ifndef RSA_LOW_MEM
2187 if ((mp_count_bits(&key->p) == 1024) &&
2188 (mp_count_bits(&key->q) == 1024)) {
2189 return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
2190 &key->dP, &key->dQ, &key->u, &key->n,
2191 out, outLen);
2192 }
2193 break;
2194 #else
2195 return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
2196 NULL, NULL, &key->n, out, outLen);
2197 #endif
2198#endif
2199 case RSA_PUBLIC_ENCRYPT:
2200 case RSA_PUBLIC_DECRYPT:
2201 return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
2202 }
2203 }
2204#endif
2205#ifndef WOLFSSL_SP_NO_3072
2206 if (mp_count_bits(&key->n) == 3072) {
2207 switch(type) {
2208#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2209 case RSA_PRIVATE_DECRYPT:
2210 case RSA_PRIVATE_ENCRYPT:
2211 #ifdef WC_RSA_BLINDING
2212 if (rng == NULL)
2213 return MISSING_RNG_E;
2214 #endif
2215 #ifndef RSA_LOW_MEM
2216 if ((mp_count_bits(&key->p) == 1536) &&
2217 (mp_count_bits(&key->q) == 1536)) {
2218 return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
2219 &key->dP, &key->dQ, &key->u, &key->n,
2220 out, outLen);
2221 }
2222 break;
2223 #else
2224 return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
2225 NULL, NULL, &key->n, out, outLen);
2226 #endif
2227#endif
2228 case RSA_PUBLIC_ENCRYPT:
2229 case RSA_PUBLIC_DECRYPT:
2230 return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
2231 }
2232 }
2233#endif
2234#ifdef WOLFSSL_SP_4096
2235 if (mp_count_bits(&key->n) == 4096) {
2236 switch(type) {
2237#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2238 case RSA_PRIVATE_DECRYPT:
2239 case RSA_PRIVATE_ENCRYPT:
2240 #ifdef WC_RSA_BLINDING
2241 if (rng == NULL)
2242 return MISSING_RNG_E;
2243 #endif
2244 #ifndef RSA_LOW_MEM
2245 if ((mp_count_bits(&key->p) == 2048) &&
2246 (mp_count_bits(&key->q) == 2048)) {
2247 return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
2248 &key->dP, &key->dQ, &key->u, &key->n,
2249 out, outLen);
2250 }
2251 break;
2252 #else
2253 return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
2254 NULL, NULL, &key->n, out, outLen);
2255 #endif
2256#endif
2257 case RSA_PUBLIC_ENCRYPT:
2258 case RSA_PUBLIC_DECRYPT:
2259 return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
2260 }
2261 }
2262#endif
2263#endif /* WOLFSSL_HAVE_SP_RSA */
2264
2265#if defined(WOLFSSL_SP_MATH)
2266 (void)rng;
2267 WOLFSSL_MSG("SP Key Size Error");
2268 return WC_KEY_SIZE_E;
2269#else
2270 (void)rng;
2271
2272#ifdef WOLFSSL_SMALL_STACK
2273 tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
2274 if (tmp == NULL)
2275 return MEMORY_E;
2276#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
2277#ifdef WC_RSA_BLINDING
2278 rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA);
2279 if (rnd == NULL) {
2280 XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
2281 return MEMORY_E;
2282 }
2283 rndi = rnd + 1;
2284#endif /* WC_RSA_BLINDING */
2285#endif
2286#endif /* WOLFSSL_SMALL_STACK */
2287
2288 if (mp_init(tmp) != MP_OKAY)
2289 ret = MP_INIT_E;
2290
2291#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
2292#ifdef WC_RSA_BLINDING
2293 if (ret == 0) {
2294 if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
2295 if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) {
2296 mp_clear(tmp);
2297 ret = MP_INIT_E;
2298 }
2299 }
2300 }
2301#endif
2302#endif
2303
2304#ifndef TEST_UNPAD_CONSTANT_TIME
2305 if (ret == 0 && mp_read_unsigned_bin(tmp, (byte*)in, inLen) != MP_OKAY)
2306 ret = MP_READ_E;
2307
2308 if (ret == 0) {
2309 switch(type) {
2310 #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
2311 case RSA_PRIVATE_DECRYPT:
2312 case RSA_PRIVATE_ENCRYPT:
2313 {
2314 #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2315 /* blind */
2316 ret = mp_rand(rnd, get_digit_count(&key->n), rng);
2317
2318 /* rndi = 1/rnd mod n */
2319 if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY)
2320 ret = MP_INVMOD_E;
2321
2322 /* rnd = rnd^e */
2323 #ifndef WOLFSSL_SP_MATH_ALL
2324 if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY)
2325 ret = MP_EXPTMOD_E;
2326 #else
2327 if (ret == 0 && mp_exptmod_nct(rnd, &key->e, &key->n,
2328 rnd) != MP_OKAY) {
2329 ret = MP_EXPTMOD_E;
2330 }
2331 #endif
2332
2333 /* tmp = tmp*rnd mod n */
2334 if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY)
2335 ret = MP_MULMOD_E;
2336 #endif /* WC_RSA_BLINDING && !WC_NO_RNG */
2337
2338 #ifdef RSA_LOW_MEM /* half as much memory but twice as slow */
2339 if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
2340 ret = MP_EXPTMOD_E;
2341 #else
2342 if (ret == 0) {
2343 #ifdef WOLFSSL_SMALL_STACK
2344 mp_int* tmpa;
2345 mp_int* tmpb = NULL;
2346 #else
2347 mp_int tmpa[1], tmpb[1];
2348 #endif
2349 int cleara = 0, clearb = 0;
2350
2351 #ifdef WOLFSSL_SMALL_STACK
2352 tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2,
2353 key->heap, DYNAMIC_TYPE_RSA);
2354 if (tmpa != NULL)
2355 tmpb = tmpa + 1;
2356 else
2357 ret = MEMORY_E;
2358 #endif
2359
2360 if (ret == 0) {
2361 if (mp_init(tmpa) != MP_OKAY)
2362 ret = MP_INIT_E;
2363 else
2364 cleara = 1;
2365 }
2366
2367 if (ret == 0) {
2368 if (mp_init(tmpb) != MP_OKAY)
2369 ret = MP_INIT_E;
2370 else
2371 clearb = 1;
2372 }
2373
2374 /* tmpa = tmp^dP mod p */
2375 if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p,
2376 tmpa) != MP_OKAY)
2377 ret = MP_EXPTMOD_E;
2378
2379 /* tmpb = tmp^dQ mod q */
2380 if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q,
2381 tmpb) != MP_OKAY)
2382 ret = MP_EXPTMOD_E;
2383
2384 /* tmp = (tmpa - tmpb) * qInv (mod p) */
2385#if defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL) && \
2386 !defined(WOLFSSL_SP_INT_NEGATIVE))
2387 if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY)
2388 ret = MP_SUB_E;
2389#else
2390 if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
2391 ret = MP_SUB_E;
2392#endif
2393
2394 if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p,
2395 tmp) != MP_OKAY)
2396 ret = MP_MULMOD_E;
2397
2398 /* tmp = tmpb + q * tmp */
2399 if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
2400 ret = MP_MUL_E;
2401
2402 if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
2403 ret = MP_ADD_E;
2404
2405 #ifdef WOLFSSL_SMALL_STACK
2406 if (tmpa != NULL)
2407 #endif
2408 {
2409 if (cleara)
2410 mp_clear(tmpa);
2411 if (clearb)
2412 mp_clear(tmpb);
2413 #ifdef WOLFSSL_SMALL_STACK
2414 XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA);
2415 #endif
2416 }
2417 } /* tmpa/b scope */
2418 #endif /* RSA_LOW_MEM */
2419
2420 #ifdef WC_RSA_BLINDING
2421 /* unblind */
2422 if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
2423 ret = MP_MULMOD_E;
2424 #endif /* WC_RSA_BLINDING */
2425
2426 break;
2427 }
2428 #endif
2429 case RSA_PUBLIC_ENCRYPT:
2430 case RSA_PUBLIC_DECRYPT:
2431 if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY)
2432 ret = MP_EXPTMOD_E;
2433 break;
2434 default:
2435 ret = RSA_WRONG_TYPE_E;
2436 break;
2437 }
2438 }
2439
2440 if (ret == 0) {
2441 keyLen = wc_RsaEncryptSize(key);
2442 if (keyLen > *outLen)
2443 ret = RSA_BUFFER_E;
2444 }
2445
2446#ifndef WOLFSSL_XILINX_CRYPT
2447 if (ret == 0) {
2448 *outLen = keyLen;
2449 if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY)
2450 ret = MP_TO_E;
2451 }
2452#endif
2453#else
2454 (void)type;
2455 (void)key;
2456 (void)keyLen;
2457 XMEMCPY(out, in, inLen);
2458 *outLen = inLen;
2459#endif
2460
2461 mp_clear(tmp);
2462#ifdef WOLFSSL_SMALL_STACK
2463 XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
2464#endif
2465#ifdef WC_RSA_BLINDING
2466 if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
2467 mp_clear(rndi);
2468 mp_clear(rnd);
2469 }
2470#ifdef WOLFSSL_SMALL_STACK
2471 XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA);
2472#endif
2473#endif /* WC_RSA_BLINDING */
2474 return ret;
2475#endif /* WOLFSSL_SP_MATH */
2476}
2477#endif
2478
2479#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
2480static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
2481 word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2482{
2483 int ret = 0;
2484
2485 (void)rng;
2486
2487#ifdef WOLFSSL_ASYNC_CRYPT_TEST
2488 if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) {
2489 WC_ASYNC_TEST* testDev = &key->asyncDev.test;
2490 testDev->rsaFunc.in = in;
2491 testDev->rsaFunc.inSz = inLen;
2492 testDev->rsaFunc.out = out;
2493 testDev->rsaFunc.outSz = outLen;
2494 testDev->rsaFunc.type = type;
2495 testDev->rsaFunc.key = key;
2496 testDev->rsaFunc.rng = rng;
2497 return WC_PENDING_E;
2498 }
2499#endif /* WOLFSSL_ASYNC_CRYPT_TEST */
2500
2501 switch(type) {
2502#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2503 case RSA_PRIVATE_DECRYPT:
2504 case RSA_PRIVATE_ENCRYPT:
2505 #ifdef HAVE_CAVIUM
2506 key->dataLen = key->n.raw.len;
2507 ret = NitroxRsaExptMod(in, inLen,
2508 key->d.raw.buf, key->d.raw.len,
2509 key->n.raw.buf, key->n.raw.len,
2510 out, outLen, key);
2511 #elif defined(HAVE_INTEL_QA)
2512 #ifdef RSA_LOW_MEM
2513 ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
2514 &key->d.raw, &key->n.raw,
2515 out, outLen);
2516 #else
2517 ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
2518 &key->p.raw, &key->q.raw,
2519 &key->dP.raw, &key->dQ.raw,
2520 &key->u.raw,
2521 out, outLen);
2522 #endif
2523 #else /* WOLFSSL_ASYNC_CRYPT_TEST */
2524 ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2525 #endif
2526 break;
2527#endif
2528
2529 case RSA_PUBLIC_ENCRYPT:
2530 case RSA_PUBLIC_DECRYPT:
2531 #ifdef HAVE_CAVIUM
2532 key->dataLen = key->n.raw.len;
2533 ret = NitroxRsaExptMod(in, inLen,
2534 key->e.raw.buf, key->e.raw.len,
2535 key->n.raw.buf, key->n.raw.len,
2536 out, outLen, key);
2537 #elif defined(HAVE_INTEL_QA)
2538 ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
2539 &key->e.raw, &key->n.raw,
2540 out, outLen);
2541 #else /* WOLFSSL_ASYNC_CRYPT_TEST */
2542 ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2543 #endif
2544 break;
2545
2546 default:
2547 ret = RSA_WRONG_TYPE_E;
2548 }
2549
2550 return ret;
2551}
2552#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
2553
2554#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING)
2555/* Function that does the RSA operation directly with no padding.
2556 *
2557 * in buffer to do operation on
2558 * inLen length of input buffer
2559 * out buffer to hold results
2560 * outSz gets set to size of result buffer. Should be passed in as length
2561 * of out buffer. If the pointer "out" is null then outSz gets set to
2562 * the expected buffer size needed and LENGTH_ONLY_E gets returned.
2563 * key RSA key to use for encrypt/decrypt
2564 * type if using private or public key {RSA_PUBLIC_ENCRYPT,
2565 * RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT}
2566 * rng wolfSSL RNG to use if needed
2567 *
2568 * returns size of result on success
2569 */
2570int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz,
2571 RsaKey* key, int type, WC_RNG* rng)
2572{
2573 int ret;
2574
2575 if (in == NULL || outSz == NULL || key == NULL) {
2576 return BAD_FUNC_ARG;
2577 }
2578
2579 /* sanity check on type of RSA operation */
2580 switch (type) {
2581 case RSA_PUBLIC_ENCRYPT:
2582 case RSA_PUBLIC_DECRYPT:
2583 case RSA_PRIVATE_ENCRYPT:
2584 case RSA_PRIVATE_DECRYPT:
2585 break;
2586 default:
2587 WOLFSSL_MSG("Bad RSA type");
2588 return BAD_FUNC_ARG;
2589 }
2590
2591 if ((ret = wc_RsaEncryptSize(key)) < 0) {
2592 return BAD_FUNC_ARG;
2593 }
2594
2595 if (inLen != (word32)ret) {
2596 WOLFSSL_MSG("Bad input length. Should be RSA key size");
2597 return BAD_FUNC_ARG;
2598 }
2599
2600 if (out == NULL) {
2601 *outSz = inLen;
2602 return LENGTH_ONLY_E;
2603 }
2604
2605 switch (key->state) {
2606 case RSA_STATE_NONE:
2607 case RSA_STATE_ENCRYPT_PAD:
2608 case RSA_STATE_ENCRYPT_EXPTMOD:
2609 case RSA_STATE_DECRYPT_EXPTMOD:
2610 case RSA_STATE_DECRYPT_UNPAD:
2611 key->state = (type == RSA_PRIVATE_ENCRYPT ||
2612 type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
2613 RSA_STATE_DECRYPT_EXPTMOD;
2614
2615 key->dataLen = *outSz;
2616
2617 ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
2618 if (ret >= 0 || ret == WC_PENDING_E) {
2619 key->state = (type == RSA_PRIVATE_ENCRYPT ||
2620 type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
2621 RSA_STATE_DECRYPT_RES;
2622 }
2623 if (ret < 0) {
2624 break;
2625 }
2626
2627 FALL_THROUGH;
2628
2629 case RSA_STATE_ENCRYPT_RES:
2630 case RSA_STATE_DECRYPT_RES:
2631 ret = key->dataLen;
2632 break;
2633
2634 default:
2635 ret = BAD_STATE_E;
2636 }
2637
2638 /* if async pending then skip cleanup*/
2639 if (ret == WC_PENDING_E
2640 #ifdef WC_RSA_NONBLOCK
2641 || ret == FP_WOULDBLOCK
2642 #endif
2643 ) {
2644 return ret;
2645 }
2646
2647 key->state = RSA_STATE_NONE;
2648 wc_RsaCleanup(key);
2649
2650 return ret;
2651}
2652#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */
2653
2654#if defined(WOLFSSL_CRYPTOCELL)
2655static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
2656 word32 outLen, RsaKey* key)
2657{
2658 CRYSError_t ret = 0;
2659 CRYS_RSAPrimeData_t primeData;
2660 int modulusSize = wc_RsaEncryptSize(key);
2661
2662 /* The out buffer must be at least modulus size bytes long. */
2663 if (outLen < modulusSize)
2664 return BAD_FUNC_ARG;
2665
2666 ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState,
2667 wc_rndGenVectFunc,
2668 &key->ctx.pubKey,
2669 &primeData,
2670 (byte*)in,
2671 inLen,
2672 out);
2673
2674 if (ret != SA_SILIB_RET_OK){
2675 WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed");
2676 return -1;
2677 }
2678
2679 return modulusSize;
2680}
2681static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out,
2682 word32 outLen, RsaKey* key)
2683{
2684 CRYSError_t ret = 0;
2685 CRYS_RSAPrimeData_t primeData;
2686 word16 actualOutLen = outLen;
2687
2688 ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
2689 &primeData,
2690 (byte*)in,
2691 inLen,
2692 out,
2693 &actualOutLen);
2694
2695 if (ret != SA_SILIB_RET_OK){
2696 WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed");
2697 return -1;
2698 }
2699 return actualOutLen;
2700}
2701
2702int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
2703 word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
2704{
2705 CRYSError_t ret = 0;
2706 word16 actualOutLen = outLen*sizeof(byte);
2707 CRYS_RSAPrivUserContext_t contextPrivate;
2708
2709 ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState,
2710 wc_rndGenVectFunc,
2711 &contextPrivate,
2712 &key->ctx.privKey,
2713 mode,
2714 (byte*)in,
2715 inLen,
2716 out,
2717 &actualOutLen);
2718
2719 if (ret != SA_SILIB_RET_OK){
2720 WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed");
2721 return -1;
2722 }
2723 return actualOutLen;
2724}
2725
2726int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig,
2727 RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
2728{
2729 CRYSError_t ret = 0;
2730 CRYS_RSAPubUserContext_t contextPub;
2731
2732 /* verify the signature in the sig pointer */
2733 ret = CRYS_RSA_PKCS1v15_Verify(&contextPub,
2734 &key->ctx.pubKey,
2735 mode,
2736 (byte*)in,
2737 inLen,
2738 sig);
2739
2740 if (ret != SA_SILIB_RET_OK){
2741 WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed");
2742 return -1;
2743 }
2744
2745 return ret;
2746}
2747#endif /* WOLFSSL_CRYPTOCELL */
2748
2749int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
2750 word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2751{
2752 int ret = 0;
2753
2754 if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
2755 outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
2756 return BAD_FUNC_ARG;
2757 }
2758
2759#ifdef WOLF_CRYPTO_CB
2760 if (key->devId != INVALID_DEVID) {
2761 ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
2762 if (ret != CRYPTOCB_UNAVAILABLE)
2763 return ret;
2764 /* fall-through when unavailable */
2765 ret = 0; /* reset error code and try using software */
2766 }
2767#endif
2768
2769#ifndef WOLFSSL_RSA_VERIFY_ONLY
2770#ifndef TEST_UNPAD_CONSTANT_TIME
2771#ifndef NO_RSA_BOUNDS_CHECK
2772 if (type == RSA_PRIVATE_DECRYPT &&
2773 key->state == RSA_STATE_DECRYPT_EXPTMOD) {
2774
2775 /* Check that 1 < in < n-1. (Requirement of 800-56B.) */
2776#ifdef WOLFSSL_SMALL_STACK
2777 mp_int* c;
2778#else
2779 mp_int c[1];
2780#endif
2781
2782#ifdef WOLFSSL_SMALL_STACK
2783 c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
2784 if (c == NULL)
2785 ret = MEMORY_E;
2786#endif
2787
2788 if (mp_init(c) != MP_OKAY)
2789 ret = MP_INIT_E;
2790 if (ret == 0) {
2791 if (mp_read_unsigned_bin(c, in, inLen) != 0)
2792 ret = MP_READ_E;
2793 }
2794 if (ret == 0) {
2795 /* check c > 1 */
2796 if (mp_cmp_d(c, 1) != MP_GT)
2797 ret = RSA_OUT_OF_RANGE_E;
2798 }
2799 if (ret == 0) {
2800 /* add c+1 */
2801 if (mp_add_d(c, 1, c) != MP_OKAY)
2802 ret = MP_ADD_E;
2803 }
2804 if (ret == 0) {
2805 /* check c+1 < n */
2806 if (mp_cmp(c, &key->n) != MP_LT)
2807 ret = RSA_OUT_OF_RANGE_E;
2808 }
2809 mp_clear(c);
2810
2811#ifdef WOLFSSL_SMALL_STACK
2812 XFREE(c, key->heap, DYNAMIC_TYPE_RSA);
2813#endif
2814
2815 if (ret != 0)
2816 return ret;
2817 }
2818#endif /* NO_RSA_BOUNDS_CHECK */
2819#endif
2820#endif
2821
2822#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
2823 if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
2824 key->n.raw.len > 0) {
2825 ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
2826 }
2827 else
2828#endif
2829#ifdef WC_RSA_NONBLOCK
2830 if (key->nb) {
2831 ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
2832 }
2833 else
2834#endif
2835 {
2836 ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2837 }
2838
2839 /* handle error */
2840 if (ret < 0 && ret != WC_PENDING_E
2841 #ifdef WC_RSA_NONBLOCK
2842 && ret != FP_WOULDBLOCK
2843 #endif
2844 ) {
2845 if (ret == MP_EXPTMOD_E) {
2846 /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
2847 WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
2848 }
2849
2850 key->state = RSA_STATE_NONE;
2851 wc_RsaCleanup(key);
2852 }
2853
2854 return ret;
2855}
2856
2857
2858#ifndef WOLFSSL_RSA_VERIFY_ONLY
2859/* Internal Wrappers */
2860/* Gives the option of choosing padding type
2861 in : input to be encrypted
2862 inLen: length of input buffer
2863 out: encrypted output
2864 outLen: length of encrypted output buffer
2865 key : wolfSSL initialized RSA key struct
2866 rng : wolfSSL initialized random number struct
2867 rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
2868 RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
2869 pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
2870 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
2871 WC_RSA_NO_PAD or WC_RSA_PSS_PAD
2872 hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
2873 mgf : type of mask generation function to use
2874 label : optional label
2875 labelSz : size of optional label buffer
2876 saltLen : Length of salt used in PSS
2877 rng : random number generator */
2878static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
2879 word32 outLen, RsaKey* key, int rsa_type,
2880 byte pad_value, int pad_type,
2881 enum wc_HashType hash, int mgf,
2882 byte* label, word32 labelSz, int saltLen,
2883 WC_RNG* rng)
2884{
2885 int ret, sz;
2886
2887 if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
2888 return BAD_FUNC_ARG;
2889 }
2890
2891 sz = wc_RsaEncryptSize(key);
2892 if (sz > (int)outLen) {
2893 return RSA_BUFFER_E;
2894 }
2895
2896 if (sz < RSA_MIN_PAD_SZ) {
2897 return WC_KEY_SIZE_E;
2898 }
2899
2900 if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
2901#ifdef WC_RSA_NO_PADDING
2902 /* In the case that no padding is used the input length can and should
2903 * be the same size as the RSA key. */
2904 if (pad_type != WC_RSA_NO_PAD)
2905#endif
2906 return RSA_BUFFER_E;
2907 }
2908
2909 switch (key->state) {
2910 case RSA_STATE_NONE:
2911 case RSA_STATE_ENCRYPT_PAD:
2912 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
2913 defined(HAVE_CAVIUM)
2914 if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
2915 pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
2916 /* Async operations that include padding */
2917 if (rsa_type == RSA_PUBLIC_ENCRYPT &&
2918 pad_value == RSA_BLOCK_TYPE_2) {
2919 key->state = RSA_STATE_ENCRYPT_RES;
2920 key->dataLen = key->n.raw.len;
2921 return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
2922 }
2923 else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
2924 pad_value == RSA_BLOCK_TYPE_1) {
2925 key->state = RSA_STATE_ENCRYPT_RES;
2926 key->dataLen = key->n.raw.len;
2927 return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
2928 }
2929 }
2930 #elif defined(WOLFSSL_CRYPTOCELL)
2931 if (rsa_type == RSA_PUBLIC_ENCRYPT &&
2932 pad_value == RSA_BLOCK_TYPE_2) {
2933
2934 return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key);
2935 }
2936 else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
2937 pad_value == RSA_BLOCK_TYPE_1) {
2938 return cc310_RsaSSL_Sign(in, inLen, out, outLen, key,
2939 cc310_hashModeRSA(hash, 0));
2940 }
2941 #endif /* WOLFSSL_CRYPTOCELL */
2942
2943 key->state = RSA_STATE_ENCRYPT_PAD;
2944 ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash,
2945 mgf, label, labelSz, saltLen, mp_count_bits(&key->n),
2946 key->heap);
2947 if (ret < 0) {
2948 break;
2949 }
2950
2951 key->state = RSA_STATE_ENCRYPT_EXPTMOD;
2952 FALL_THROUGH;
2953
2954 case RSA_STATE_ENCRYPT_EXPTMOD:
2955
2956 key->dataLen = outLen;
2957 ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng);
2958
2959 if (ret >= 0 || ret == WC_PENDING_E) {
2960 key->state = RSA_STATE_ENCRYPT_RES;
2961 }
2962 if (ret < 0) {
2963 break;
2964 }
2965
2966 FALL_THROUGH;
2967
2968 case RSA_STATE_ENCRYPT_RES:
2969 ret = key->dataLen;
2970 break;
2971
2972 default:
2973 ret = BAD_STATE_E;
2974 break;
2975 }
2976
2977 /* if async pending then return and skip done cleanup below */
2978 if (ret == WC_PENDING_E
2979 #ifdef WC_RSA_NONBLOCK
2980 || ret == FP_WOULDBLOCK
2981 #endif
2982 ) {
2983 return ret;
2984 }
2985
2986 key->state = RSA_STATE_NONE;
2987 wc_RsaCleanup(key);
2988
2989 return ret;
2990}
2991
2992#endif
2993
2994/* Gives the option of choosing padding type
2995 in : input to be decrypted
2996 inLen: length of input buffer
2997 out: decrypted message
2998 outLen: length of decrypted message in bytes
2999 outPtr: optional inline output pointer (if provided doing inline)
3000 key : wolfSSL initialized RSA key struct
3001 rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
3002 RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
3003 pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
3004 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
3005 WC_RSA_NO_PAD, WC_RSA_PSS_PAD
3006 hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
3007 mgf : type of mask generation function to use
3008 label : optional label
3009 labelSz : size of optional label buffer
3010 saltLen : Length of salt used in PSS
3011 rng : random number generator */
3012static int RsaPrivateDecryptEx(byte* in, word32 inLen, byte* out,
3013 word32 outLen, byte** outPtr, RsaKey* key,
3014 int rsa_type, byte pad_value, int pad_type,
3015 enum wc_HashType hash, int mgf,
3016 byte* label, word32 labelSz, int saltLen,
3017 WC_RNG* rng)
3018{
3019 int ret = RSA_WRONG_TYPE_E;
3020 byte* pad = NULL;
3021
3022 if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
3023 return BAD_FUNC_ARG;
3024 }
3025
3026 switch (key->state) {
3027 case RSA_STATE_NONE:
3028 key->dataLen = inLen;
3029
3030 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3031 defined(HAVE_CAVIUM)
3032 /* Async operations that include padding */
3033 if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3034 pad_type != WC_RSA_PSS_PAD) {
3035#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3036 if (rsa_type == RSA_PRIVATE_DECRYPT &&
3037 pad_value == RSA_BLOCK_TYPE_2) {
3038 key->state = RSA_STATE_DECRYPT_RES;
3039 key->data = NULL;
3040 return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
3041 key);
3042#endif
3043 }
3044 else if (rsa_type == RSA_PUBLIC_DECRYPT &&
3045 pad_value == RSA_BLOCK_TYPE_1) {
3046 key->state = RSA_STATE_DECRYPT_RES;
3047 key->data = NULL;
3048 return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
3049 }
3050 }
3051 #elif defined(WOLFSSL_CRYPTOCELL)
3052 if (rsa_type == RSA_PRIVATE_DECRYPT &&
3053 pad_value == RSA_BLOCK_TYPE_2) {
3054 ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key);
3055 if (outPtr != NULL)
3056 *outPtr = out; /* for inline */
3057 return ret;
3058 }
3059 else if (rsa_type == RSA_PUBLIC_DECRYPT &&
3060 pad_value == RSA_BLOCK_TYPE_1) {
3061 return cc310_RsaSSL_Verify(in, inLen, out, key,
3062 cc310_hashModeRSA(hash, 0));
3063 }
3064 #endif /* WOLFSSL_CRYPTOCELL */
3065
3066
3067#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
3068 /* verify the tmp ptr is NULL, otherwise indicates bad state */
3069 if (key->data != NULL) {
3070 ret = BAD_STATE_E;
3071 break;
3072 }
3073
3074 /* if not doing this inline then allocate a buffer for it */
3075 if (outPtr == NULL) {
3076 key->data = (byte*)XMALLOC(inLen, key->heap,
3077 DYNAMIC_TYPE_WOLF_BIGINT);
3078 key->dataIsAlloc = 1;
3079 if (key->data == NULL) {
3080 ret = MEMORY_E;
3081 break;
3082 }
3083 XMEMCPY(key->data, in, inLen);
3084 }
3085 else {
3086 key->data = out;
3087 }
3088#endif
3089
3090 key->state = RSA_STATE_DECRYPT_EXPTMOD;
3091 FALL_THROUGH;
3092
3093 case RSA_STATE_DECRYPT_EXPTMOD:
3094#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
3095 ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen,
3096 rsa_type, key, rng);
3097#else
3098 ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng);
3099#endif
3100
3101 if (ret >= 0 || ret == WC_PENDING_E) {
3102 key->state = RSA_STATE_DECRYPT_UNPAD;
3103 }
3104 if (ret < 0) {
3105 break;
3106 }
3107
3108 FALL_THROUGH;
3109
3110 case RSA_STATE_DECRYPT_UNPAD:
3111#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
3112 ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type,
3113 hash, mgf, label, labelSz, saltLen,
3114 mp_count_bits(&key->n), key->heap);
3115#else
3116 ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash,
3117 mgf, label, labelSz, saltLen,
3118 mp_count_bits(&key->n), key->heap);
3119#endif
3120 if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
3121 ret = RSA_BUFFER_E;
3122 else if (ret >= 0 && pad != NULL) {
3123#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
3124 signed char c;
3125#endif
3126
3127 /* only copy output if not inline */
3128 if (outPtr == NULL) {
3129#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
3130 if (rsa_type == RSA_PRIVATE_DECRYPT) {
3131 word32 i, j;
3132 int start = (int)((size_t)pad - (size_t)key->data);
3133
3134 for (i = 0, j = 0; j < key->dataLen; j++) {
3135 out[i] = key->data[j];
3136 c = ctMaskGTE(j, start);
3137 c &= ctMaskLT(i, outLen);
3138 /* 0 - no add, -1 add */
3139 i += (word32)((byte)(-c));
3140 }
3141 }
3142 else
3143#endif
3144 {
3145 XMEMCPY(out, pad, ret);
3146 }
3147 }
3148 else
3149 *outPtr = pad;
3150
3151#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
3152 ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E);
3153 ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E);
3154#else
3155 if (outLen < (word32)ret)
3156 ret = RSA_BUFFER_E;
3157#endif
3158 }
3159
3160 key->state = RSA_STATE_DECRYPT_RES;
3161 FALL_THROUGH;
3162
3163 case RSA_STATE_DECRYPT_RES:
3164 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3165 defined(HAVE_CAVIUM)
3166 if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3167 pad_type != WC_RSA_PSS_PAD) {
3168 ret = key->asyncDev.event.ret;
3169 if (ret >= 0) {
3170 /* convert result */
3171 byte* dataLen = (byte*)&key->dataLen;
3172 ret = (dataLen[0] << 8) | (dataLen[1]);
3173
3174 if (outPtr)
3175 *outPtr = in;
3176 }
3177 }
3178 #endif
3179 break;
3180
3181 default:
3182 ret = BAD_STATE_E;
3183 break;
3184 }
3185
3186 /* if async pending then return and skip done cleanup below */
3187 if (ret == WC_PENDING_E
3188 #ifdef WC_RSA_NONBLOCK
3189 || ret == FP_WOULDBLOCK
3190 #endif
3191 ) {
3192 return ret;
3193 }
3194
3195 key->state = RSA_STATE_NONE;
3196 wc_RsaCleanup(key);
3197
3198 return ret;
3199}
3200
3201
3202#ifndef WOLFSSL_RSA_VERIFY_ONLY
3203/* Public RSA Functions */
3204int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
3205 RsaKey* key, WC_RNG* rng)
3206{
3207 return RsaPublicEncryptEx(in, inLen, out, outLen, key,
3208 RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3209 WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3210}
3211
3212
3213#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
3214int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
3215 word32 outLen, RsaKey* key, WC_RNG* rng, int type,
3216 enum wc_HashType hash, int mgf, byte* label,
3217 word32 labelSz)
3218{
3219 return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
3220 RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
3221}
3222#endif /* WC_NO_RSA_OAEP */
3223#endif
3224
3225
3226#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3227int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
3228{
3229 WC_RNG* rng;
3230#ifdef WC_RSA_BLINDING
3231 rng = key->rng;
3232#else
3233 rng = NULL;
3234#endif
3235 return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3236 RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3237 WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3238}
3239
3240
3241#ifndef WC_NO_RSA_OAEP
3242int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
3243 RsaKey* key, int type, enum wc_HashType hash,
3244 int mgf, byte* label, word32 labelSz)
3245{
3246 WC_RNG* rng;
3247#ifdef WC_RSA_BLINDING
3248 rng = key->rng;
3249#else
3250 rng = NULL;
3251#endif
3252 return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3253 RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
3254 mgf, label, labelSz, 0, rng);
3255}
3256#endif /* WC_NO_RSA_OAEP */
3257
3258
3259int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
3260 word32 outLen, RsaKey* key)
3261{
3262 WC_RNG* rng;
3263#ifdef WC_RSA_BLINDING
3264 rng = key->rng;
3265#else
3266 rng = NULL;
3267#endif
3268 return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
3269 RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3270 WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3271}
3272
3273#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
3274int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
3275 word32 outLen, RsaKey* key, int type,
3276 enum wc_HashType hash, int mgf, byte* label,
3277 word32 labelSz)
3278{
3279 WC_RNG* rng;
3280#ifdef WC_RSA_BLINDING
3281 rng = key->rng;
3282#else
3283 rng = NULL;
3284#endif
3285 return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
3286 RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
3287 labelSz, 0, rng);
3288}
3289#endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
3290#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
3291
3292#if !defined(WOLFSSL_CRYPTOCELL)
3293int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
3294{
3295 WC_RNG* rng;
3296#ifdef WC_RSA_BLINDING
3297 rng = key->rng;
3298#else
3299 rng = NULL;
3300#endif
3301 return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3302 RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
3303 WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3304}
3305#endif
3306
3307#ifndef WOLFSSL_RSA_VERIFY_ONLY
3308int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
3309 RsaKey* key)
3310{
3311 return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key, WC_RSA_PKCSV15_PAD);
3312}
3313
3314int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
3315 RsaKey* key, int pad_type)
3316{
3317 return wc_RsaSSL_Verify_ex2(in, inLen, out, outLen, key, pad_type,
3318 WC_HASH_TYPE_NONE);
3319}
3320
3321int wc_RsaSSL_Verify_ex2(const byte* in, word32 inLen, byte* out, word32 outLen,
3322 RsaKey* key, int pad_type, enum wc_HashType hash)
3323{
3324 WC_RNG* rng;
3325
3326 if (key == NULL) {
3327 return BAD_FUNC_ARG;
3328 }
3329
3330#ifdef WC_RSA_BLINDING
3331 rng = key->rng;
3332#else
3333 rng = NULL;
3334#endif
3335
3336#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
3337 return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
3338 RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
3339 hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DEFAULT, rng);
3340#else
3341 return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
3342 RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
3343 hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DISCOVER, rng);
3344#endif
3345}
3346#endif
3347
3348#ifdef WC_RSA_PSS
3349/* Verify the message signed with RSA-PSS.
3350 * The input buffer is reused for the output buffer.
3351 * Salt length is equal to hash length.
3352 *
3353 * in Buffer holding encrypted data.
3354 * inLen Length of data in buffer.
3355 * out Pointer to address containing the PSS data.
3356 * hash Hash algorithm.
3357 * mgf Mask generation function.
3358 * key Public RSA key.
3359 * returns the length of the PSS data on success and negative indicates failure.
3360 */
3361int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
3362 enum wc_HashType hash, int mgf, RsaKey* key)
3363{
3364#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
3365 return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
3366 RSA_PSS_SALT_LEN_DEFAULT, key);
3367#else
3368 return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
3369 RSA_PSS_SALT_LEN_DISCOVER, key);
3370#endif
3371}
3372
3373/* Verify the message signed with RSA-PSS.
3374 * The input buffer is reused for the output buffer.
3375 *
3376 * in Buffer holding encrypted data.
3377 * inLen Length of data in buffer.
3378 * out Pointer to address containing the PSS data.
3379 * hash Hash algorithm.
3380 * mgf Mask generation function.
3381 * key Public RSA key.
3382 * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
3383 * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
3384 * indicates salt length is determined from the data.
3385 * returns the length of the PSS data on success and negative indicates failure.
3386 */
3387int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
3388 enum wc_HashType hash, int mgf, int saltLen,
3389 RsaKey* key)
3390{
3391 WC_RNG* rng;
3392#ifdef WC_RSA_BLINDING
3393 rng = key->rng;
3394#else
3395 rng = NULL;
3396#endif
3397 return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3398 RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
3399 hash, mgf, NULL, 0, saltLen, rng);
3400}
3401
3402/* Verify the message signed with RSA-PSS.
3403 * Salt length is equal to hash length.
3404 *
3405 * in Buffer holding encrypted data.
3406 * inLen Length of data in buffer.
3407 * out Pointer to address containing the PSS data.
3408 * hash Hash algorithm.
3409 * mgf Mask generation function.
3410 * key Public RSA key.
3411 * returns the length of the PSS data on success and negative indicates failure.
3412 */
3413int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen,
3414 enum wc_HashType hash, int mgf, RsaKey* key)
3415{
3416#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
3417 return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
3418 RSA_PSS_SALT_LEN_DEFAULT, key);
3419#else
3420 return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
3421 RSA_PSS_SALT_LEN_DISCOVER, key);
3422#endif
3423}
3424
3425/* Verify the message signed with RSA-PSS.
3426 *
3427 * in Buffer holding encrypted data.
3428 * inLen Length of data in buffer.
3429 * out Pointer to address containing the PSS data.
3430 * hash Hash algorithm.
3431 * mgf Mask generation function.
3432 * key Public RSA key.
3433 * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
3434 * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
3435 * indicates salt length is determined from the data.
3436 * returns the length of the PSS data on success and negative indicates failure.
3437 */
3438int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen,
3439 enum wc_HashType hash, int mgf, int saltLen,
3440 RsaKey* key)
3441{
3442 WC_RNG* rng;
3443#ifdef WC_RSA_BLINDING
3444 rng = key->rng;
3445#else
3446 rng = NULL;
3447#endif
3448 return RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
3449 RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
3450 hash, mgf, NULL, 0, saltLen, rng);
3451}
3452
3453
3454/* Checks the PSS data to ensure that the signature matches.
3455 * Salt length is equal to hash length.
3456 *
3457 * in Hash of the data that is being verified.
3458 * inSz Length of hash.
3459 * sig Buffer holding PSS data.
3460 * sigSz Size of PSS data.
3461 * hashType Hash algorithm.
3462 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
3463 * NULL is passed in to in or sig or inSz is not the same as the hash
3464 * algorithm length and 0 on success.
3465 */
3466int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig,
3467 word32 sigSz, enum wc_HashType hashType)
3468{
3469 return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, inSz, 0);
3470}
3471
3472/* Checks the PSS data to ensure that the signature matches.
3473 *
3474 * in Hash of the data that is being verified.
3475 * inSz Length of hash.
3476 * sig Buffer holding PSS data.
3477 * sigSz Size of PSS data.
3478 * hashType Hash algorithm.
3479 * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
3480 * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
3481 * indicates salt length is determined from the data.
3482 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
3483 * NULL is passed in to in or sig or inSz is not the same as the hash
3484 * algorithm length and 0 on success.
3485 */
3486int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig,
3487 word32 sigSz, enum wc_HashType hashType,
3488 int saltLen, int bits)
3489{
3490 int ret = 0;
3491#ifndef WOLFSSL_PSS_LONG_SALT
3492 byte sigCheck[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
3493#else
3494 byte *sigCheck = NULL;
3495#endif
3496
3497 (void)bits;
3498
3499 if (in == NULL || sig == NULL ||
3500 inSz != (word32)wc_HashGetDigestSize(hashType)) {
3501 ret = BAD_FUNC_ARG;
3502 }
3503
3504 if (ret == 0) {
3505 if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
3506 saltLen = inSz;
3507 #ifdef WOLFSSL_SHA512
3508 /* See FIPS 186-4 section 5.5 item (e). */
3509 if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
3510 saltLen = RSA_PSS_SALT_MAX_SZ;
3511 }
3512 #endif
3513 }
3514#ifndef WOLFSSL_PSS_LONG_SALT
3515 else if ((word32)saltLen > inSz) {
3516 ret = PSS_SALTLEN_E;
3517 }
3518#endif
3519#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
3520 else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
3521 ret = PSS_SALTLEN_E;
3522 }
3523#else
3524 else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
3525 saltLen = sigSz - inSz;
3526 if (saltLen < 0) {
3527 ret = PSS_SALTLEN_E;
3528 }
3529 }
3530 else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
3531 ret = PSS_SALTLEN_E;
3532 }
3533#endif
3534 }
3535
3536 /* Sig = Salt | Exp Hash */
3537 if (ret == 0) {
3538 if (sigSz != inSz + saltLen) {
3539 ret = PSS_SALTLEN_E;
3540 }
3541 }
3542
3543#ifdef WOLFSSL_PSS_LONG_SALT
3544 if (ret == 0) {
3545 sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, NULL,
3546 DYNAMIC_TYPE_RSA_BUFFER);
3547 if (sigCheck == NULL) {
3548 ret = MEMORY_E;
3549 }
3550 }
3551#endif
3552
3553 /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
3554 if (ret == 0) {
3555 XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
3556 XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
3557 XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen);
3558 ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen,
3559 sigCheck, inSz);
3560 }
3561 if (ret == 0) {
3562 if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
3563 WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
3564 ret = BAD_PADDING_E;
3565 }
3566 }
3567
3568#ifdef WOLFSSL_PSS_LONG_SALT
3569 if (sigCheck != NULL) {
3570 XFREE(sigCheck, NULL, DYNAMIC_TYPE_RSA_BUFFER);
3571 }
3572#endif
3573 return ret;
3574}
3575
3576
3577/* Verify the message signed with RSA-PSS.
3578 * The input buffer is reused for the output buffer.
3579 * Salt length is equal to hash length.
3580 *
3581 * in Buffer holding encrypted data.
3582 * inLen Length of data in buffer.
3583 * out Pointer to address containing the PSS data.
3584 * digest Hash of the data that is being verified.
3585 * digestLen Length of hash.
3586 * hash Hash algorithm.
3587 * mgf Mask generation function.
3588 * key Public RSA key.
3589 * returns the length of the PSS data on success and negative indicates failure.
3590 */
3591int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
3592 const byte* digest, word32 digestLen,
3593 enum wc_HashType hash, int mgf, RsaKey* key)
3594{
3595 int ret = 0, verify, saltLen, hLen, bits = 0;
3596
3597 hLen = wc_HashGetDigestSize(hash);
3598 if (hLen < 0)
3599 return BAD_FUNC_ARG;
3600 if ((word32)hLen != digestLen)
3601 return BAD_FUNC_ARG;
3602
3603 saltLen = hLen;
3604 #ifdef WOLFSSL_SHA512
3605 /* See FIPS 186-4 section 5.5 item (e). */
3606 bits = mp_count_bits(&key->n);
3607 if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
3608 saltLen = RSA_PSS_SALT_MAX_SZ;
3609 #endif
3610
3611 verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
3612 if (verify > 0)
3613 ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify,
3614 hash, saltLen, bits);
3615 if (ret == 0)
3616 ret = verify;
3617
3618 return ret;
3619}
3620
3621
3622/* Verify the message signed with RSA-PSS.
3623 * Salt length is equal to hash length.
3624 *
3625 * in Buffer holding encrypted data.
3626 * inLen Length of data in buffer.
3627 * out Pointer to address containing the PSS data.
3628 * outLen Length of the output.
3629 * digest Hash of the data that is being verified.
3630 * digestLen Length of hash.
3631 * hash Hash algorithm.
3632 * mgf Mask generation function.
3633 * key Public RSA key.
3634 * returns the length of the PSS data on success and negative indicates failure.
3635 */
3636int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen,
3637 const byte* digest, word32 digestLen,
3638 enum wc_HashType hash, int mgf,
3639 RsaKey* key)
3640{
3641 int ret = 0, verify, saltLen, hLen, bits = 0;
3642
3643 hLen = wc_HashGetDigestSize(hash);
3644 if (hLen < 0)
3645 return hLen;
3646 if ((word32)hLen != digestLen)
3647 return BAD_FUNC_ARG;
3648
3649 saltLen = hLen;
3650 #ifdef WOLFSSL_SHA512
3651 /* See FIPS 186-4 section 5.5 item (e). */
3652 bits = mp_count_bits(&key->n);
3653 if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
3654 saltLen = RSA_PSS_SALT_MAX_SZ;
3655 #endif
3656
3657 verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
3658 mgf, saltLen, key);
3659 if (verify > 0)
3660 ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify,
3661 hash, saltLen, bits);
3662 if (ret == 0)
3663 ret = verify;
3664
3665 return ret;
3666}
3667
3668#endif
3669
3670#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
3671int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
3672 RsaKey* key, WC_RNG* rng)
3673{
3674 return RsaPublicEncryptEx(in, inLen, out, outLen, key,
3675 RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
3676 WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3677}
3678
3679#ifdef WC_RSA_PSS
3680/* Sign the hash of a message using RSA-PSS.
3681 * Salt length is equal to hash length.
3682 *
3683 * in Buffer holding hash of message.
3684 * inLen Length of data in buffer (hash length).
3685 * out Buffer to write encrypted signature into.
3686 * outLen Size of buffer to write to.
3687 * hash Hash algorithm.
3688 * mgf Mask generation function.
3689 * key Public RSA key.
3690 * rng Random number generator.
3691 * returns the length of the encrypted signature on success, a negative value
3692 * indicates failure.
3693 */
3694int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
3695 enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
3696{
3697 return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
3698 RSA_PSS_SALT_LEN_DEFAULT, key, rng);
3699}
3700
3701/* Sign the hash of a message using RSA-PSS.
3702 *
3703 * in Buffer holding hash of message.
3704 * inLen Length of data in buffer (hash length).
3705 * out Buffer to write encrypted signature into.
3706 * outLen Size of buffer to write to.
3707 * hash Hash algorithm.
3708 * mgf Mask generation function.
3709 * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
3710 * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
3711 * indicates salt length is determined from the data.
3712 * key Public RSA key.
3713 * rng Random number generator.
3714 * returns the length of the encrypted signature on success, a negative value
3715 * indicates failure.
3716 */
3717int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
3718 enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
3719 WC_RNG* rng)
3720{
3721 return RsaPublicEncryptEx(in, inLen, out, outLen, key,
3722 RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
3723 hash, mgf, NULL, 0, saltLen, rng);
3724}
3725#endif
3726#endif
3727
3728#if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \
3729 defined(WC_RSA_PSS)
3730int wc_RsaEncryptSize(RsaKey* key)
3731{
3732 int ret;
3733
3734 if (key == NULL) {
3735 return BAD_FUNC_ARG;
3736 }
3737
3738 ret = mp_unsigned_bin_size(&key->n);
3739
3740#ifdef WOLF_CRYPTO_CB
3741 if (ret == 0 && key->devId != INVALID_DEVID) {
3742 ret = 2048/8; /* hardware handles, use 2048-bit as default */
3743 }
3744#endif
3745
3746 return ret;
3747}
3748#endif
3749
3750#ifndef WOLFSSL_RSA_VERIFY_ONLY
3751/* flatten RsaKey structure into individual elements (e, n) */
3752int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n,
3753 word32* nSz)
3754{
3755 int sz, ret;
3756
3757 if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
3758 return BAD_FUNC_ARG;
3759 }
3760
3761 sz = mp_unsigned_bin_size(&key->e);
3762 if ((word32)sz > *eSz)
3763 return RSA_BUFFER_E;
3764 ret = mp_to_unsigned_bin(&key->e, e);
3765 if (ret != MP_OKAY)
3766 return ret;
3767 *eSz = (word32)sz;
3768
3769 sz = wc_RsaEncryptSize(key);
3770 if ((word32)sz > *nSz)
3771 return RSA_BUFFER_E;
3772 ret = mp_to_unsigned_bin(&key->n, n);
3773 if (ret != MP_OKAY)
3774 return ret;
3775 *nSz = (word32)sz;
3776
3777 return 0;
3778}
3779#endif
3780
3781#endif /* HAVE_FIPS */
3782
3783
3784#ifndef WOLFSSL_RSA_VERIFY_ONLY
3785static int RsaGetValue(mp_int* in, byte* out, word32* outSz)
3786{
3787 word32 sz;
3788 int ret = 0;
3789
3790 /* Parameters ensured by calling function. */
3791
3792 sz = (word32)mp_unsigned_bin_size(in);
3793 if (sz > *outSz)
3794 ret = RSA_BUFFER_E;
3795
3796 if (ret == 0)
3797 ret = mp_to_unsigned_bin(in, out);
3798
3799 if (ret == MP_OKAY)
3800 *outSz = sz;
3801
3802 return ret;
3803}
3804
3805
3806int wc_RsaExportKey(RsaKey* key,
3807 byte* e, word32* eSz, byte* n, word32* nSz,
3808 byte* d, word32* dSz, byte* p, word32* pSz,
3809 byte* q, word32* qSz)
3810{
3811 int ret = BAD_FUNC_ARG;
3812
3813 if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz)
3814 ret = 0;
3815
3816 if (ret == 0)
3817 ret = RsaGetValue(&key->e, e, eSz);
3818 if (ret == 0)
3819 ret = RsaGetValue(&key->n, n, nSz);
3820#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3821 if (ret == 0)
3822 ret = RsaGetValue(&key->d, d, dSz);
3823 if (ret == 0)
3824 ret = RsaGetValue(&key->p, p, pSz);
3825 if (ret == 0)
3826 ret = RsaGetValue(&key->q, q, qSz);
3827#else
3828 /* no private parts to key */
3829 if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
3830 || qSz == NULL) {
3831 ret = BAD_FUNC_ARG;
3832 }
3833 else {
3834 *dSz = 0;
3835 *pSz = 0;
3836 *qSz = 0;
3837 }
3838#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
3839
3840 return ret;
3841}
3842#endif
3843
3844
3845#ifdef WOLFSSL_KEY_GEN
3846
3847/* Check that |p-q| > 2^((size/2)-100) */
3848static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size)
3849{
3850 mp_int c, d;
3851 int ret;
3852
3853 if (p == NULL || q == NULL)
3854 return BAD_FUNC_ARG;
3855
3856 ret = mp_init_multi(&c, &d, NULL, NULL, NULL, NULL);
3857
3858 /* c = 2^((size/2)-100) */
3859 if (ret == 0)
3860 ret = mp_2expt(&c, (size/2)-100);
3861
3862 /* d = |p-q| */
3863 if (ret == 0)
3864 ret = mp_sub(p, q, &d);
3865
3866#if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \
3867 defined(WOLFSSL_SP_INT_NEGATIVE))
3868 if (ret == 0)
3869 ret = mp_abs(&d, &d);
3870#endif
3871
3872 /* compare */
3873 if (ret == 0)
3874 ret = mp_cmp(&d, &c);
3875
3876 if (ret == MP_GT)
3877 ret = MP_OKAY;
3878
3879 mp_clear(&d);
3880 mp_clear(&c);
3881
3882 return ret;
3883}
3884
3885
3886/* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
3887 * This number was calculated using a small test tool written with a common
3888 * large number math library. Other values of nlen may be checked with a subset
3889 * of lower_bound. */
3890static const byte lower_bound[] = {
3891 0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
3892 0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
3893 0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
3894 0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
3895/* 512 */
3896 0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
3897 0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
3898 0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
3899 0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
3900/* 1024 */
3901 0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
3902 0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
3903 0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
3904 0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
3905 0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
3906 0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
3907 0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
3908 0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
3909/* 2048 */
3910 0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
3911 0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
3912 0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
3913 0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
3914 0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
3915 0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
3916 0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
3917 0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
3918/* 3072 */
3919 0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
3920 0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
3921 0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
3922 0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
3923 0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
3924 0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
3925 0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
3926 0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
3927/* 4096 */
3928};
3929
3930
3931/* returns 1 on key size ok and 0 if not ok */
3932static WC_INLINE int RsaSizeCheck(int size)
3933{
3934 if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
3935 return 0;
3936 }
3937
3938#ifdef HAVE_FIPS
3939 /* Key size requirements for CAVP */
3940 switch (size) {
3941 case 1024:
3942 case 2048:
3943 case 3072:
3944 case 4096:
3945 return 1;
3946 }
3947
3948 return 0;
3949#else
3950 return 1; /* allow unusual key sizes in non FIPS mode */
3951#endif /* HAVE_FIPS */
3952}
3953
3954
3955static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
3956 int* isPrime, WC_RNG* rng)
3957{
3958 int ret;
3959 mp_int tmp1, tmp2;
3960 mp_int* prime;
3961
3962 if (p == NULL || e == NULL || isPrime == NULL)
3963 return BAD_FUNC_ARG;
3964
3965 if (!RsaSizeCheck(nlen))
3966 return BAD_FUNC_ARG;
3967
3968 *isPrime = MP_NO;
3969
3970 if (q != NULL) {
3971 /* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
3972 ret = wc_CompareDiffPQ(p, q, nlen);
3973 if (ret != MP_OKAY) goto notOkay;
3974 prime = q;
3975 }
3976 else
3977 prime = p;
3978
3979 ret = mp_init_multi(&tmp1, &tmp2, NULL, NULL, NULL, NULL);
3980 if (ret != MP_OKAY) goto notOkay;
3981
3982 /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1))
3983 * This is a comparison against lowerBound */
3984 ret = mp_read_unsigned_bin(&tmp1, lower_bound, nlen/16);
3985 if (ret != MP_OKAY) goto notOkay;
3986 ret = mp_cmp(prime, &tmp1);
3987 if (ret == MP_LT) goto exit;
3988
3989 /* 4.5,5.6 - Check that GCD(p-1, e) == 1 */
3990 ret = mp_sub_d(prime, 1, &tmp1); /* tmp1 = prime-1 */
3991 if (ret != MP_OKAY) goto notOkay;
3992 ret = mp_gcd(&tmp1, e, &tmp2); /* tmp2 = gcd(prime-1, e) */
3993 if (ret != MP_OKAY) goto notOkay;
3994 ret = mp_cmp_d(&tmp2, 1);
3995 if (ret != MP_EQ) goto exit; /* e divides p-1 */
3996
3997 /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
3998 * mp_prime_is_prime_ex() performs test divisions against the first 256
3999 * prime numbers. After that it performs 8 rounds of M-R using random
4000 * bases between 2 and n-2.
4001 * mp_prime_is_prime() performs the same test divisions and then does
4002 * M-R with the first 8 primes. Both functions set isPrime as a
4003 * side-effect. */
4004 if (rng != NULL)
4005 ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
4006 else
4007 ret = mp_prime_is_prime(prime, 8, isPrime);
4008 if (ret != MP_OKAY) goto notOkay;
4009
4010exit:
4011 ret = MP_OKAY;
4012notOkay:
4013 mp_clear(&tmp1);
4014 mp_clear(&tmp2);
4015 return ret;
4016}
4017
4018
4019int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
4020 const byte* qRaw, word32 qRawSz,
4021 const byte* eRaw, word32 eRawSz,
4022 int nlen, int* isPrime, WC_RNG* rng)
4023{
4024 mp_int p, q, e;
4025 mp_int* Q = NULL;
4026 int ret;
4027
4028 if (pRaw == NULL || pRawSz == 0 ||
4029 eRaw == NULL || eRawSz == 0 ||
4030 isPrime == NULL) {
4031
4032 return BAD_FUNC_ARG;
4033 }
4034
4035 if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
4036 return BAD_FUNC_ARG;
4037
4038 ret = mp_init_multi(&p, &q, &e, NULL, NULL, NULL);
4039
4040 if (ret == MP_OKAY)
4041 ret = mp_read_unsigned_bin(&p, pRaw, pRawSz);
4042
4043 if (ret == MP_OKAY) {
4044 if (qRaw != NULL) {
4045 ret = mp_read_unsigned_bin(&q, qRaw, qRawSz);
4046 if (ret == MP_OKAY)
4047 Q = &q;
4048 }
4049 }
4050
4051 if (ret == MP_OKAY)
4052 ret = mp_read_unsigned_bin(&e, eRaw, eRawSz);
4053
4054 if (ret == MP_OKAY)
4055 ret = _CheckProbablePrime(&p, Q, &e, nlen, isPrime, rng);
4056
4057 ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
4058
4059 mp_clear(&p);
4060 mp_clear(&q);
4061 mp_clear(&e);
4062
4063 return ret;
4064}
4065
4066
4067int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
4068 const byte* qRaw, word32 qRawSz,
4069 const byte* eRaw, word32 eRawSz,
4070 int nlen, int* isPrime)
4071{
4072 return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
4073 eRaw, eRawSz, nlen, isPrime, NULL);
4074}
4075
4076#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
4077 defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
4078/* Make an RSA key for size bits, with e specified, 65537 is a good e */
4079int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
4080{
4081#ifndef WC_NO_RNG
4082#ifdef WOLFSSL_SMALL_STACK
4083 mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
4084 mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
4085 mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
4086 mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
4087 mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
4088#else
4089 mp_int p_buf, *p = &p_buf;
4090 mp_int q_buf, *q = &q_buf;
4091 mp_int tmp1_buf, *tmp1 = &tmp1_buf;
4092 mp_int tmp2_buf, *tmp2 = &tmp2_buf;
4093 mp_int tmp3_buf, *tmp3 = &tmp3_buf;
4094#endif
4095 int err, i, failCount, primeSz, isPrime = 0;
4096 byte* buf = NULL;
4097
4098#ifdef WOLFSSL_SMALL_STACK
4099 if ((p == NULL) ||
4100 (q == NULL) ||
4101 (tmp1 == NULL) ||
4102 (tmp2 == NULL) ||
4103 (tmp3 == NULL)) {
4104 err = MEMORY_E;
4105 goto out;
4106 }
4107#endif
4108
4109 if (key == NULL || rng == NULL) {
4110 err = BAD_FUNC_ARG;
4111 goto out;
4112 }
4113
4114 if (!RsaSizeCheck(size)) {
4115 err = BAD_FUNC_ARG;
4116 goto out;
4117 }
4118
4119 if (e < 3 || (e & 1) == 0) {
4120 err = BAD_FUNC_ARG;
4121 goto out;
4122 }
4123
4124#if defined(WOLFSSL_CRYPTOCELL)
4125
4126 err = cc310_RSA_GenerateKeyPair(key, size, e);
4127 goto out;
4128
4129#endif /*WOLFSSL_CRYPTOCELL*/
4130
4131#ifdef WOLF_CRYPTO_CB
4132 if (key->devId != INVALID_DEVID) {
4133 err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
4134 if (err != CRYPTOCB_UNAVAILABLE)
4135 goto out;
4136 /* fall-through when unavailable */
4137 }
4138#endif
4139
4140#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
4141 defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
4142 if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
4143 #ifdef HAVE_CAVIUM
4144 /* TODO: Not implemented */
4145 #elif defined(HAVE_INTEL_QA)
4146 err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
4147 goto out;
4148 #else
4149 if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) {
4150 WC_ASYNC_TEST* testDev = &key->asyncDev.test;
4151 testDev->rsaMake.rng = rng;
4152 testDev->rsaMake.key = key;
4153 testDev->rsaMake.size = size;
4154 testDev->rsaMake.e = e;
4155 err = WC_PENDING_E;
4156 goto out;
4157 }
4158 #endif
4159 }
4160#endif
4161
4162 err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
4163
4164 if (err == MP_OKAY)
4165 err = mp_set_int(tmp3, e);
4166
4167 /* The failCount value comes from NIST FIPS 186-4, section B.3.3,
4168 * process steps 4.7 and 5.8. */
4169 failCount = 5 * (size / 2);
4170 primeSz = size / 16; /* size is the size of n in bits.
4171 primeSz is in bytes. */
4172
4173 /* allocate buffer to work with */
4174 if (err == MP_OKAY) {
4175 buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
4176 if (buf == NULL)
4177 err = MEMORY_E;
4178 }
4179
4180 /* make p */
4181 if (err == MP_OKAY) {
4182 isPrime = 0;
4183 i = 0;
4184 do {
4185#ifdef SHOW_GEN
4186 printf(".");
4187 fflush(stdout);
4188#endif
4189 /* generate value */
4190 err = wc_RNG_GenerateBlock(rng, buf, primeSz);
4191 if (err == 0) {
4192 /* prime lower bound has the MSB set, set it in candidate */
4193 buf[0] |= 0x80;
4194 /* make candidate odd */
4195 buf[primeSz-1] |= 0x01;
4196 /* load value */
4197 err = mp_read_unsigned_bin(p, buf, primeSz);
4198 }
4199
4200 if (err == MP_OKAY)
4201 err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
4202
4203#ifdef HAVE_FIPS
4204 i++;
4205#else
4206 /* Keep the old retry behavior in non-FIPS build. */
4207 (void)i;
4208#endif
4209 } while (err == MP_OKAY && !isPrime && i < failCount);
4210 }
4211
4212 if (err == MP_OKAY && !isPrime)
4213 err = PRIME_GEN_E;
4214
4215 /* make q */
4216 if (err == MP_OKAY) {
4217 isPrime = 0;
4218 i = 0;
4219 do {
4220#ifdef SHOW_GEN
4221 printf(".");
4222 fflush(stdout);
4223#endif
4224 /* generate value */
4225 err = wc_RNG_GenerateBlock(rng, buf, primeSz);
4226 if (err == 0) {
4227 /* prime lower bound has the MSB set, set it in candidate */
4228 buf[0] |= 0x80;
4229 /* make candidate odd */
4230 buf[primeSz-1] |= 0x01;
4231 /* load value */
4232 err = mp_read_unsigned_bin(q, buf, primeSz);
4233 }
4234
4235 if (err == MP_OKAY)
4236 err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
4237
4238#ifdef HAVE_FIPS
4239 i++;
4240#else
4241 /* Keep the old retry behavior in non-FIPS build. */
4242 (void)i;
4243#endif
4244 } while (err == MP_OKAY && !isPrime && i < failCount);
4245 }
4246
4247 if (err == MP_OKAY && !isPrime)
4248 err = PRIME_GEN_E;
4249
4250 if (buf) {
4251 ForceZero(buf, primeSz);
4252 XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
4253 }
4254
4255 if (err == MP_OKAY && mp_cmp(p, q) < 0) {
4256 err = mp_copy(p, tmp1);
4257 if (err == MP_OKAY)
4258 err = mp_copy(q, p);
4259 if (err == MP_OKAY)
4260 mp_copy(tmp1, q);
4261 }
4262
4263 /* Setup RsaKey buffers */
4264 if (err == MP_OKAY)
4265 err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
4266 if (err == MP_OKAY)
4267 err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
4268
4269 /* Software Key Calculation */
4270 if (err == MP_OKAY) /* tmp1 = p-1 */
4271 err = mp_sub_d(p, 1, tmp1);
4272 if (err == MP_OKAY) /* tmp2 = q-1 */
4273 err = mp_sub_d(q, 1, tmp2);
4274#ifdef WC_RSA_BLINDING
4275 if (err == MP_OKAY) /* tmp3 = order of n */
4276 err = mp_mul(tmp1, tmp2, tmp3);
4277#else
4278 if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */
4279 err = mp_lcm(tmp1, tmp2, tmp3);
4280#endif
4281 /* make key */
4282 if (err == MP_OKAY) /* key->e = e */
4283 err = mp_set_int(&key->e, (mp_digit)e);
4284#ifdef WC_RSA_BLINDING
4285 /* Blind the inverse operation with a value that is invertable */
4286 if (err == MP_OKAY) {
4287 do {
4288 err = mp_rand(&key->p, get_digit_count(tmp3), rng);
4289 if (err == MP_OKAY)
4290 err = mp_set_bit(&key->p, 0);
4291 if (err == MP_OKAY)
4292 err = mp_set_bit(&key->p, size - 1);
4293 if (err == MP_OKAY)
4294 err = mp_gcd(&key->p, tmp3, &key->q);
4295 }
4296 while ((err == MP_OKAY) && !mp_isone(&key->q));
4297 }
4298 if (err == MP_OKAY)
4299 err = mp_mul_d(&key->p, (mp_digit)e, &key->e);
4300#endif
4301 if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */
4302 err = mp_invmod(&key->e, tmp3, &key->d);
4303#ifdef WC_RSA_BLINDING
4304 /* Take off blinding from d and reset e */
4305 if (err == MP_OKAY)
4306 err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
4307 if (err == MP_OKAY)
4308 err = mp_set_int(&key->e, (mp_digit)e);
4309#endif
4310 if (err == MP_OKAY) /* key->n = pq */
4311 err = mp_mul(p, q, &key->n);
4312 if (err == MP_OKAY) /* key->dP = d mod(p-1) */
4313 err = mp_mod(&key->d, tmp1, &key->dP);
4314 if (err == MP_OKAY) /* key->dQ = d mod(q-1) */
4315 err = mp_mod(&key->d, tmp2, &key->dQ);
4316#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
4317 if (err == MP_OKAY) /* key->u = 1/q mod p */
4318 err = mp_invmod(q, p, &key->u);
4319#else
4320 if (err == MP_OKAY)
4321 err = mp_sub_d(p, 2, tmp3);
4322 if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */
4323 err = mp_exptmod(q, tmp3 , p, &key->u);
4324#endif
4325 if (err == MP_OKAY)
4326 err = mp_copy(p, &key->p);
4327 if (err == MP_OKAY)
4328 err = mp_copy(q, &key->q);
4329
4330#ifdef HAVE_WOLF_BIGINT
4331 /* make sure raw unsigned bin version is available */
4332 if (err == MP_OKAY)
4333 err = wc_mp_to_bigint(&key->n, &key->n.raw);
4334 if (err == MP_OKAY)
4335 err = wc_mp_to_bigint(&key->e, &key->e.raw);
4336 if (err == MP_OKAY)
4337 err = wc_mp_to_bigint(&key->d, &key->d.raw);
4338 if (err == MP_OKAY)
4339 err = wc_mp_to_bigint(&key->p, &key->p.raw);
4340 if (err == MP_OKAY)
4341 err = wc_mp_to_bigint(&key->q, &key->q.raw);
4342 if (err == MP_OKAY)
4343 err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
4344 if (err == MP_OKAY)
4345 err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
4346 if (err == MP_OKAY)
4347 err = wc_mp_to_bigint(&key->u, &key->u.raw);
4348#endif
4349
4350 if (err == MP_OKAY)
4351 key->type = RSA_PRIVATE;
4352
4353 mp_clear(tmp1);
4354 mp_clear(tmp2);
4355 mp_clear(tmp3);
4356 mp_clear(p);
4357 mp_clear(q);
4358
4359#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
4360 /* Perform the pair-wise consistency test on the new key. */
4361 if (err == 0)
4362 err = wc_CheckRsaKey(key);
4363#endif
4364
4365 if (err != 0) {
4366 wc_FreeRsaKey(key);
4367 goto out;
4368 }
4369
4370#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
4371 if (wc_InitRsaHw(key) != 0) {
4372 return BAD_STATE_E;
4373 }
4374#endif
4375
4376 err = 0;
4377
4378 out:
4379
4380#ifdef WOLFSSL_SMALL_STACK
4381 if (p)
4382 XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
4383 if (q)
4384 XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
4385 if (tmp1)
4386 XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
4387 if (tmp2)
4388 XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
4389 if (tmp3)
4390 XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
4391#endif
4392
4393 return err;
4394#else
4395 return NOT_COMPILED_IN;
4396#endif
4397}
4398#endif /* !FIPS || FIPS_VER >= 2 */
4399#endif /* WOLFSSL_KEY_GEN */
4400
4401
4402#ifdef WC_RSA_BLINDING
4403int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
4404{
4405 if (key == NULL || rng == NULL)
4406 return BAD_FUNC_ARG;
4407
4408 key->rng = rng;
4409
4410 return 0;
4411}
4412#endif /* WC_RSA_BLINDING */
4413
4414#ifdef WC_RSA_NONBLOCK
4415int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
4416{
4417 if (key == NULL)
4418 return BAD_FUNC_ARG;
4419
4420 if (nb) {
4421 XMEMSET(nb, 0, sizeof(RsaNb));
4422 }
4423
4424 /* Allow nb == NULL to clear non-block mode */
4425 key->nb = nb;
4426
4427 return 0;
4428}
4429#ifdef WC_RSA_NONBLOCK_TIME
4430int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
4431{
4432 if (key == NULL || key->nb == NULL) {
4433 return BAD_FUNC_ARG;
4434 }
4435
4436 /* calculate maximum number of instructions to block */
4437 key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
4438
4439 return 0;
4440}
4441#endif /* WC_RSA_NONBLOCK_TIME */
4442#endif /* WC_RSA_NONBLOCK */
4443
4444#endif /* NO_RSA */
Note: See TracBrowser for help on using the repository browser.