Coverage Report

Created: 2026-04-01 07:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-openssl-api/wolfcrypt/src/rsa.c
Line
Count
Source
1
/* rsa.c
2
 *
3
 * Copyright (C) 2006-2026 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 3 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
24
DESCRIPTION
25
This library provides the interface to the RSA.
26
RSA keys can be used to encrypt, decrypt, sign and verify data.
27
28
*/
29
30
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
31
32
#ifndef NO_RSA
33
34
#if FIPS_VERSION3_GE(2,0,0)
35
    /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
36
    #define FIPS_NO_WRAPPERS
37
38
       #ifdef USE_WINDOWS_API
39
               #pragma code_seg(".fipsA$j")
40
               #pragma const_seg(".fipsB$j")
41
       #endif
42
#endif
43
44
#include <wolfssl/wolfcrypt/rsa.h>
45
#include <wolfssl/wolfcrypt/logging.h>
46
47
#ifdef WOLFSSL_AFALG_XILINX_RSA
48
#include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
49
#endif
50
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
51
#include <xsecure_rsaclient.h>
52
#endif
53
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
54
#include <wolfssl/wolfcrypt/port/nxp/se050_port.h>
55
#endif
56
#ifdef WOLFSSL_HAVE_SP_RSA
57
#include <wolfssl/wolfcrypt/sp.h>
58
#endif
59
60
#if defined(WOLFSSL_USE_SAVE_VECTOR_REGISTERS) && !defined(WOLFSSL_SP_ASM)
61
    /* force off unneeded vector register save/restore. */
62
    #undef SAVE_VECTOR_REGISTERS
63
    #define SAVE_VECTOR_REGISTERS(fail_clause) SAVE_NO_VECTOR_REGISTERS(fail_clause)
64
    #undef RESTORE_VECTOR_REGISTERS
65
    #define RESTORE_VECTOR_REGISTERS() RESTORE_NO_VECTOR_REGISTERS()
66
#endif
67
68
/*
69
 * RSA Build Options:
70
 *
71
 * Core:
72
 * NO_RSA:                  Disable RSA support entirely            default: off
73
 * WOLFSSL_RSA_PUBLIC_ONLY: Only include RSA public key operations  default: off
74
 * WOLFSSL_RSA_VERIFY_ONLY: Only include RSA verify operation       default: off
75
 * WOLFSSL_RSA_VERIFY_INLINE: RSA verify inline (no output copy)   default: off
76
 * WC_RSA_DIRECT:           Enable direct RSA encrypt/decrypt API   default: off
77
 * WC_RSA_NO_PADDING:       Enable no-padding RSA mode              default: off
78
 * WOLFSSL_RSA_KEY_CHECK:   Enable RSA key pair consistency check   default: off
79
 * WOLFSSL_RSA_CHECK_D_ON_DECRYPT: Validate private exponent d     default: off
80
 *                           before each decrypt operation
81
 * WOLFSSL_RSA_DECRYPT_TO_0_LEN: Allow RSA decrypt result of 0     default: off
82
 *                           length (empty plaintext)
83
 * NO_RSA_BOUNDS_CHECK:     Disable RSA bounds checking on input    default: off
84
 * SHOW_GEN:                Show key generation progress dots        default: off
85
 *
86
 * Padding:
87
 * WC_RSA_PSS:              Enable RSA-PSS signature support        default: off
88
 * WC_NO_RSA_OAEP:          Disable RSA OAEP padding                default: off
89
 * WOLFSSL_PSS_LONG_SALT:   Allow PSS salt longer than hash length  default: off
90
 * WOLFSSL_PSS_SALT_LEN_DISCOVER: Auto-discover PSS salt length    default: off
91
 *                           during verification
92
 *
93
 * Performance:
94
 * WC_RSA_BLINDING:         Use blinding with private key ops       default: on
95
 *                           Note: ~20% slower, protects against
96
 *                           timing side-channels
97
 * RSA_LOW_MEM:             Non-CRT private ops, less memory        default: off
98
 * WC_RSA_NONBLOCK:         Non-blocking RSA operations             default: off
99
 * WC_RSA_NONBLOCK_TIME:    Time-based non-blocking RSA             default: off
100
 * WOLFSSL_MP_INVMOD_CONSTANT_TIME: Constant-time modular inverse  default: off
101
 * WC_RSA_NO_FERMAT_CHECK:  Skip Fermat factorization check on     default: off
102
 *                           key generation (p and q closeness)
103
 *
104
 * Key Generation:
105
 * WOLFSSL_KEY_GEN:         Enable RSA private key generation       default: off
106
 * FP_MAX_BITS:             Max key bits with USE_FAST_MATH         default: 4096
107
 *                           Value is key size * 2 (e.g. RSA 3072 = 6144)
108
 *
109
 * SP Math:
110
 * WOLFSSL_HAVE_SP_RSA:     Use SP math for RSA operations          default: off
111
 * WOLFSSL_SP_MATH:         Use SP math only (no multi-precision)   default: off
112
 * WOLFSSL_SP_MATH_ALL:     SP math for all key sizes               default: off
113
 * WOLFSSL_SP_NO_2048:      Disable SP RSA 2048-bit support         default: off
114
 * WOLFSSL_SP_NO_3072:      Disable SP RSA 3072-bit support         default: off
115
 * WOLFSSL_SP_4096:         Enable SP RSA 4096-bit support          default: off
116
 * WOLFSSL_SP_ASM:          Use SP assembly optimizations           default: off
117
 *
118
 * Hardware Acceleration (RSA-specific):
119
 * WC_ASYNC_ENABLE_RSA:     Enable async RSA operations             default: off
120
 * WOLFSSL_KCAPI_RSA:       Linux kernel crypto API for RSA         default: off
121
 * WOLFSSL_AFALG_XILINX_RSA: AF_ALG Xilinx RSA acceleration        default: off
122
 * WOLFSSL_SE050_NO_RSA:    Disable SE050 RSA                       default: off
123
 * WOLFSSL_XILINX_CRYPT:    Xilinx crypto RSA acceleration          default: off
124
 */
125
126
127
#include <wolfssl/wolfcrypt/random.h>
128
#ifdef WOLF_CRYPTO_CB
129
    #include <wolfssl/wolfcrypt/cryptocb.h>
130
#endif
131
#ifdef NO_INLINE
132
    #include <wolfssl/wolfcrypt/misc.h>
133
#else
134
    #define WOLFSSL_MISC_INCLUDED
135
    #include <wolfcrypt/src/misc.c>
136
#endif
137
138
#if FIPS_VERSION3_GE(6,0,0)
139
    const unsigned int wolfCrypt_FIPS_rsa_ro_sanity[2] =
140
                                                     { 0x1a2b3c4d, 0x00000012 };
141
    int wolfCrypt_FIPS_RSA_sanity(void)
142
    {
143
        return 0;
144
    }
145
#endif
146
147
enum {
148
    RSA_STATE_NONE = 0,
149
150
    RSA_STATE_ENCRYPT_PAD,
151
    RSA_STATE_ENCRYPT_EXPTMOD,
152
    RSA_STATE_ENCRYPT_RES,
153
154
    RSA_STATE_DECRYPT_EXPTMOD,
155
    RSA_STATE_DECRYPT_UNPAD,
156
    RSA_STATE_DECRYPT_RES
157
};
158
159
static void wc_RsaCleanup(RsaKey* key)
160
38.7k
{
161
38.7k
#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \
162
38.7k
    (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)))
163
38.7k
    if (key != NULL) {
164
38.7k
    #ifndef WOLFSSL_RSA_PUBLIC_ONLY
165
        /* if private operation zero temp buffer */
166
38.7k
        if ((key->data != NULL && key->dataLen > 0) &&
167
8.69k
            (key->type == RSA_PRIVATE_DECRYPT ||
168
8.69k
             key->type == RSA_PRIVATE_ENCRYPT)) {
169
0
            ForceZero(key->data, key->dataLen);
170
0
        }
171
38.7k
    #endif
172
        /* make sure any allocated memory is free'd */
173
38.7k
        if (key->dataIsAlloc) {
174
822
            XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
175
822
            key->dataIsAlloc = 0;
176
822
        }
177
178
38.7k
        key->data = NULL;
179
38.7k
        key->dataLen = 0;
180
38.7k
    }
181
#else
182
    (void)key;
183
#endif
184
38.7k
}
185
186
#ifndef WC_NO_CONSTRUCTORS
187
RsaKey* wc_NewRsaKey(void* heap, int devId, int *result_code)
188
0
{
189
0
    int ret;
190
0
    RsaKey* key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
191
0
    if (key == NULL) {
192
0
        ret = MEMORY_E;
193
0
    }
194
0
    else {
195
0
        ret = wc_InitRsaKey_ex(key, heap, devId);
196
0
        if (ret != 0) {
197
0
            XFREE(key, heap, DYNAMIC_TYPE_RSA);
198
0
            key = NULL;
199
0
        }
200
0
    }
201
202
0
    if (result_code != NULL)
203
0
        *result_code = ret;
204
205
0
    return key;
206
0
}
207
208
int wc_DeleteRsaKey(RsaKey* key, RsaKey** key_p)
209
0
{
210
0
    if (key == NULL)
211
0
        return BAD_FUNC_ARG;
212
0
    wc_FreeRsaKey(key);
213
0
    XFREE(key, key->heap, DYNAMIC_TYPE_RSA);
214
0
    if (key_p != NULL)
215
0
        *key_p = NULL;
216
0
    return 0;
217
0
}
218
#endif /* !WC_NO_CONSTRUCTORS */
219
220
int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
221
17.7k
{
222
17.7k
    int ret = 0;
223
224
17.7k
    if (key == NULL) {
225
0
        return BAD_FUNC_ARG;
226
0
    }
227
228
17.7k
    XMEMSET(key, 0, sizeof(RsaKey));
229
230
17.7k
    key->type = RSA_TYPE_UNKNOWN;
231
17.7k
    key->state = RSA_STATE_NONE;
232
17.7k
    key->heap = heap;
233
17.7k
#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \
234
17.7k
    (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)))
235
17.7k
    key->dataIsAlloc = 0;
236
17.7k
#endif
237
238
17.7k
#ifdef WOLF_CRYPTO_CB
239
17.7k
    key->devId = devId;
240
#else
241
    (void)devId;
242
#endif
243
244
#ifdef WOLFSSL_ASYNC_CRYPT
245
    #ifdef WOLFSSL_CERT_GEN
246
        XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
247
    #endif
248
249
    #ifdef WC_ASYNC_ENABLE_RSA
250
        #ifdef WOLF_CRYPTO_CB
251
        /* prefer crypto callback */
252
        if (key->devId != INVALID_DEVID)
253
        #endif
254
        {
255
            /* handle as async */
256
            ret = wolfAsync_DevCtxInit(&key->asyncDev,
257
                    WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId);
258
            if (ret != 0)
259
                return ret;
260
        }
261
    #endif /* WC_ASYNC_ENABLE_RSA */
262
#endif /* WOLFSSL_ASYNC_CRYPT */
263
264
17.7k
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
265
17.7k
    ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
266
17.7k
    if (ret != MP_OKAY)
267
0
        return ret;
268
269
#if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
270
    ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
271
#else
272
17.7k
    ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
273
17.7k
#endif
274
17.7k
    if (ret != MP_OKAY) {
275
0
        mp_clear(&key->n);
276
0
        mp_clear(&key->e);
277
0
        return ret;
278
0
    }
279
#else
280
    ret = mp_init(&key->n);
281
    if (ret != MP_OKAY)
282
        return ret;
283
    ret = mp_init(&key->e);
284
    if (ret != MP_OKAY) {
285
        mp_clear(&key->n);
286
        return ret;
287
    }
288
#endif
289
290
#ifdef WOLFSSL_XILINX_CRYPT
291
    key->pubExp = 0;
292
    key->mod    = NULL;
293
#endif
294
295
#ifdef WOLFSSL_AFALG_XILINX_RSA
296
    key->alFd = WC_SOCK_NOTSET;
297
    key->rdFd = WC_SOCK_NOTSET;
298
#endif
299
300
#ifdef WOLFSSL_KCAPI_RSA
301
    key->handle = NULL;
302
#endif
303
304
#if defined(WOLFSSL_RENESAS_FSPSM)
305
    key->ctx.wrapped_pri1024_key = NULL;
306
    key->ctx.wrapped_pub1024_key = NULL;
307
    key->ctx.wrapped_pri2048_key = NULL;
308
    key->ctx.wrapped_pub2048_key = NULL;
309
    key->ctx.keySz = 0;
310
#endif
311
312
17.7k
    return ret;
313
17.7k
}
314
315
int wc_InitRsaKey(RsaKey* key, void* heap)
316
7.50k
{
317
7.50k
    return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
318
7.50k
}
319
320
#ifdef WOLF_PRIVATE_KEY_ID
321
int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
322
                     int devId)
323
0
{
324
0
    int ret = 0;
325
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
326
    /* SE050 TLS users store a word32 at id, need to cast back */
327
    word32* keyPtr = NULL;
328
#endif
329
330
0
    if (key == NULL)
331
0
        ret = BAD_FUNC_ARG;
332
0
    if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
333
0
        ret = BUFFER_E;
334
0
    if (ret == 0)
335
0
        ret = wc_InitRsaKey_ex(key, heap, devId);
336
0
    if (ret == 0 && id != NULL && len != 0) {
337
0
        XMEMCPY(key->id, id, (size_t)len);
338
0
        key->idLen = len;
339
    #if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
340
        /* Set SE050 ID from word32, populate RsaKey with public from SE050 */
341
        if (len == (int)sizeof(word32)) {
342
            keyPtr = (word32*)key->id;
343
            ret = wc_RsaUseKeyId(key, *keyPtr, 0);
344
        }
345
    #endif
346
0
    }
347
348
0
    return ret;
349
0
}
350
351
int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId)
352
0
{
353
0
    int ret = 0;
354
0
    int labelLen = 0;
355
356
0
    if (key == NULL || label == NULL)
357
0
        ret = BAD_FUNC_ARG;
358
0
    if (ret == 0) {
359
0
        labelLen = (int)XSTRLEN(label);
360
0
        if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN)
361
0
            ret = BUFFER_E;
362
0
    }
363
0
    if (ret == 0)
364
0
        ret = wc_InitRsaKey_ex(key, heap, devId);
365
0
    if (ret == 0) {
366
0
        XMEMCPY(key->label, label, (size_t)labelLen);
367
0
        key->labelLen = labelLen;
368
0
    }
369
370
0
    return ret;
371
0
}
372
#endif /* WOLF_PRIVATE_KEY_ID */
373
374
375
#ifdef WOLFSSL_XILINX_CRYPT
376
#define MAX_E_SIZE 4
377
/* Used to setup hardware state
378
 *
379
 * key  the RSA key to setup
380
 *
381
 * returns 0 on success
382
 */
383
int wc_InitRsaHw(RsaKey* key)
384
{
385
    unsigned char* m; /* RSA modulus */
386
    word32 e = 0;     /* RSA public exponent */
387
    int mSz;
388
    int eSz;
389
    int ret;
390
391
    if (key == NULL) {
392
        return BAD_FUNC_ARG;
393
    }
394
395
    mSz = mp_unsigned_bin_size(&(key->n));
396
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
397
    if (mSz > WOLFSSL_XSECURE_RSA_KEY_SIZE) {
398
        return BAD_FUNC_ARG;
399
    }
400
    /* Allocate 4 bytes more for the public exponent. */
401
    m = (unsigned char*) XMALLOC(WOLFSSL_XSECURE_RSA_KEY_SIZE + 4, key->heap,
402
                                 DYNAMIC_TYPE_KEY);
403
#else
404
    m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
405
#endif
406
    if (m == NULL) {
407
        return MEMORY_E;
408
    }
409
410
    if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
411
        WOLFSSL_MSG("Unable to get RSA key modulus");
412
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
413
        return MP_READ_E;
414
    }
415
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
416
    XMEMSET(m + mSz, 0, WOLFSSL_XSECURE_RSA_KEY_SIZE + 4 - mSz);
417
#endif
418
419
    eSz = mp_unsigned_bin_size(&(key->e));
420
    if (eSz > MAX_E_SIZE) {
421
        WOLFSSL_MSG("Exponent of size 4 bytes expected");
422
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
423
        return BAD_FUNC_ARG;
424
    }
425
426
    if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
427
                != MP_OKAY) {
428
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
429
        WOLFSSL_MSG("Unable to get RSA key exponent");
430
        return MP_READ_E;
431
    }
432
433
    /* check for existing mod buffer to avoid memory leak */
434
    XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
435
436
    key->pubExp = e;
437
    key->mod    = m;
438
439
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
440
    ret = wc_InitXsecure(&(key->xSec));
441
    if (ret != 0) {
442
        WOLFSSL_MSG("Unable to initialize xSecure for RSA");
443
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
444
        return ret;
445
    }
446
    XMEMCPY(&m[WOLFSSL_XSECURE_RSA_KEY_SIZE], &e, sizeof(e));
447
    key->mSz = mSz;
448
#else
449
    if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
450
                (byte*)&(key->pubExp)) != XST_SUCCESS) {
451
        WOLFSSL_MSG("Unable to initialize RSA on hardware");
452
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
453
        return BAD_STATE_E;
454
    }
455
456
#ifdef WOLFSSL_XILINX_PATCH
457
   /* currently a patch of xsecure_rsa.c for 2048 bit keys */
458
   if (wc_RsaEncryptSize(key) == 256) {
459
       if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
460
           WOLFSSL_MSG("Unable to set RSA key size on hardware");
461
           XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
462
           return BAD_STATE_E;
463
       }
464
   }
465
#endif
466
#endif
467
    return 0;
468
} /* WOLFSSL_XILINX_CRYPT*/
469
470
#elif defined(WOLFSSL_CRYPTOCELL)
471
472
int wc_InitRsaHw(RsaKey* key)
473
{
474
    CRYSError_t ret = 0;
475
    byte e[3];
476
    word32 eSz = sizeof(e);
477
    byte n[256];
478
    word32 nSz = sizeof(n);
479
    byte d[256];
480
    word32 dSz = sizeof(d);
481
    byte p[128];
482
    word32 pSz = sizeof(p);
483
    byte q[128];
484
    word32 qSz = sizeof(q);
485
486
    if (key == NULL) {
487
        return BAD_FUNC_ARG;
488
    }
489
490
    ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz);
491
    if (ret != 0)
492
        return MP_READ_E;
493
494
    ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz);
495
    if (ret != SA_SILIB_RET_OK){
496
        WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed");
497
        return ret;
498
    }
499
500
    ret =  CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz);
501
502
    if (ret != SA_SILIB_RET_OK){
503
        WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed");
504
        return ret;
505
    }
506
    key->type = RSA_PRIVATE;
507
    return 0;
508
}
509
510
static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e)
511
{
512
    CRYSError_t             ret = 0;
513
    CRYS_RSAKGData_t        KeyGenData;
514
    CRYS_RSAKGFipsContext_t FipsCtx;
515
    byte ex[3];
516
    word16 eSz = sizeof(ex);
517
    byte n[256];
518
    word16 nSz = sizeof(n);
519
520
    ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
521
                        wc_rndGenVectFunc,
522
                        (byte*)&e,
523
                        3*sizeof(byte),
524
                        size,
525
                        &key->ctx.privKey,
526
                        &key->ctx.pubKey,
527
                        &KeyGenData,
528
                        &FipsCtx);
529
530
    if (ret != SA_SILIB_RET_OK){
531
        WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed");
532
        return ret;
533
    }
534
535
    ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz);
536
    if (ret != SA_SILIB_RET_OK){
537
        WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed");
538
        return ret;
539
    }
540
    ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key);
541
542
    key->type = RSA_PRIVATE;
543
544
    return ret;
545
}
546
#endif /* WOLFSSL_CRYPTOCELL */
547
548
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
549
/* Use specified hardware key ID with RsaKey operations. Unlike devId,
550
 * keyId is a word32 so can handle key IDs larger than an int.
551
 *
552
 * key    initialized RsaKey struct
553
 * keyId  hardware key ID which stores RSA key
554
 * flags  optional flags, currently unused
555
 *
556
 * Return 0 on success, negative on error */
557
int wc_RsaUseKeyId(RsaKey* key, word32 keyId, word32 flags)
558
{
559
    (void)flags;
560
561
    if (key == NULL) {
562
        return BAD_FUNC_ARG;
563
    }
564
565
    return se050_rsa_use_key_id(key, keyId);
566
}
567
568
/* Get hardware key ID associated with this RsaKey structure.
569
 *
570
 * key    initialized RsaKey struct
571
 * keyId  [OUT] output for key ID associated with this structure
572
 *
573
 * Returns 0 on success, negative on error.
574
 */
575
int wc_RsaGetKeyId(RsaKey* key, word32* keyId)
576
{
577
    if (key == NULL || keyId == NULL) {
578
        return BAD_FUNC_ARG;
579
    }
580
581
    return se050_rsa_get_key_id(key, keyId);
582
}
583
#endif /* WOLFSSL_SE050 */
584
585
int wc_FreeRsaKey(RsaKey* key)
586
17.6k
{
587
17.6k
    int ret = 0;
588
589
17.6k
    if (key == NULL) {
590
0
        return BAD_FUNC_ARG;
591
0
    }
592
593
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
594
    se050_rsa_free_key(key);
595
#endif
596
597
17.6k
    wc_RsaCleanup(key);
598
599
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
600
    wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
601
#endif
602
603
17.6k
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
604
    /* Forcezero all private key fields that are present in this build
605
     * configuration, since they may contain residual sensitive data even when
606
     * key->type is not RSA_PRIVATE (e.g., after a partial key decode failure). */
607
17.6k
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
608
17.6k
    mp_forcezero(&key->u);
609
17.6k
    mp_forcezero(&key->dQ);
610
17.6k
    mp_forcezero(&key->dP);
611
17.6k
#endif
612
17.6k
    mp_forcezero(&key->q);
613
17.6k
    mp_forcezero(&key->p);
614
17.6k
    mp_forcezero(&key->d);
615
17.6k
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
616
617
    /* public part */
618
17.6k
    mp_clear(&key->e);
619
17.6k
    mp_clear(&key->n);
620
621
#ifdef WOLFSSL_XILINX_CRYPT
622
    XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
623
    key->mod = NULL;
624
#endif
625
626
#ifdef WOLFSSL_AFALG_XILINX_RSA
627
    /* make sure that sockets are closed on cleanup */
628
    if (key->alFd > 0) {
629
        close(key->alFd);
630
        key->alFd = WC_SOCK_NOTSET;
631
    }
632
    if (key->rdFd > 0) {
633
        close(key->rdFd);
634
        key->rdFd = WC_SOCK_NOTSET;
635
    }
636
#endif
637
638
#ifdef WOLFSSL_KCAPI_RSA
639
    KcapiRsa_Free(key);
640
#endif
641
642
#ifdef WOLFSSL_CHECK_MEM_ZERO
643
    wc_MemZero_Check(key, sizeof(RsaKey));
644
#endif
645
646
#if defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY)
647
    wc_fspsm_RsaKeyFree(key);
648
#endif
649
650
17.6k
    return ret;
651
17.6k
}
652
653
#ifdef WOLFSSL_RSA_KEY_CHECK
654
/* Check the pair-wise consistency of the RSA key. */
655
static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng)
656
0
{
657
0
    static const char* msg = "Everyone gets Friday off.";
658
0
#ifndef WOLFSSL_NO_MALLOC
659
0
    byte* sig = NULL;
660
#else
661
    byte sig[RSA_MAX_SIZE/8];
662
#endif
663
0
    byte* plain;
664
0
    int ret = 0;
665
0
    word32 msgLen, plainLen, sigLen;
666
667
0
    msgLen = (word32)XSTRLEN(msg);
668
0
    ret = wc_RsaEncryptSize(key);
669
0
    if (ret < 0)
670
0
        return ret;
671
0
    else if (ret == 0)
672
0
        return BAD_FUNC_ARG;
673
0
    sigLen = (word32)ret;
674
675
0
    WOLFSSL_MSG("Doing RSA consistency test");
676
677
0
#ifndef WOLFSSL_NO_MALLOC
678
    /* Sign and verify. */
679
0
    sig = (byte*)XMALLOC(sigLen, key->heap, DYNAMIC_TYPE_RSA);
680
0
    if (sig == NULL) {
681
0
        return MEMORY_E;
682
0
    }
683
0
#endif
684
0
    XMEMSET(sig, 0, sigLen);
685
#ifdef WOLFSSL_CHECK_MEM_ZERO
686
    wc_MemZero_Add("Pairwise CT sig", sig, sigLen);
687
#endif
688
0
    plain = sig;
689
690
#ifdef WOLFSSL_ASYNC_CRYPT
691
    /* Do blocking async calls here, caller does not support WC_PENDING_E */
692
    do {
693
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
694
            ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
695
        if (ret >= 0)
696
#endif
697
0
            ret = wc_RsaSSL_Sign((const byte*)msg, msgLen, sig, sigLen, key, rng);
698
#ifdef WOLFSSL_ASYNC_CRYPT
699
    } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E));
700
#endif
701
702
0
    if (ret > 0) {
703
0
        sigLen = (word32)ret;
704
#ifdef WOLFSSL_ASYNC_CRYPT
705
        /* Do blocking async calls here, caller does not support WC_PENDING_E */
706
        do {
707
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
708
                ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
709
            if (ret >= 0)
710
#endif
711
0
                ret = wc_RsaSSL_VerifyInline(sig, sigLen, &plain, key);
712
#ifdef WOLFSSL_ASYNC_CRYPT
713
        } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E));
714
#endif
715
0
    }
716
717
0
    if (ret > 0) {
718
0
        plainLen = (word32)ret;
719
0
        ret = (msgLen != plainLen) || (XMEMCMP(plain, msg, msgLen) != 0);
720
0
    }
721
722
0
    if (ret != 0)
723
0
        ret = RSA_KEY_PAIR_E;
724
725
0
    ForceZero(sig, sigLen);
726
0
#ifndef WOLFSSL_NO_MALLOC
727
0
    XFREE(sig, key->heap, DYNAMIC_TYPE_RSA);
728
0
#endif
729
730
0
    return ret;
731
0
}
732
733
734
int wc_CheckRsaKey(RsaKey* key)
735
0
{
736
0
    WC_RNG *rng = NULL;
737
#if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC)
738
    WC_RNG rng_buf;
739
#endif
740
0
    int ret = 0;
741
0
    DECL_MP_INT_SIZE_DYN(tmp, (key)? mp_bitsused(&key->n) : 0, RSA_MAX_SIZE);
742
743
0
    if (key == NULL) {
744
0
        return BAD_FUNC_ARG;
745
0
    }
746
747
#ifdef WOLFSSL_CAAM
748
    /* can not perform these checks on an encrypted key */
749
    if (key->blackKey != 0) {
750
        return 0;
751
    }
752
#endif
753
754
0
    NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), NULL, DYNAMIC_TYPE_RSA);
755
0
#ifdef MP_INT_SIZE_CHECK_NULL
756
0
    if (tmp == NULL) {
757
0
        return MEMORY_E;
758
0
    }
759
0
#endif
760
761
0
    if (key->rng)
762
0
        rng = key->rng;
763
0
    else {
764
#if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC)
765
        rng = &rng_buf;
766
#else
767
0
        rng = (WC_RNG *)XMALLOC(sizeof(*rng), NULL, DYNAMIC_TYPE_RNG);
768
0
        if (rng == NULL) {
769
0
            FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
770
0
            return MEMORY_E;
771
0
        }
772
0
#endif
773
0
        ret = wc_InitRng(rng);
774
0
        if (ret != 0) {
775
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
776
0
            XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
777
0
            FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
778
0
#endif
779
0
            return ret;
780
0
        }
781
0
    }
782
783
0
    SAVE_VECTOR_REGISTERS(ret = _svr_ret;);
784
785
0
    if (ret == 0) {
786
0
        if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY)
787
0
            ret = MP_INIT_E;
788
0
    }
789
790
0
    if (ret == 0)
791
0
        ret = _ifc_pairwise_consistency_test(key, rng);
792
793
    /* Check d is less than n. */
794
0
    if (ret == 0 ) {
795
0
        if (mp_cmp(&key->d, &key->n) != MP_LT) {
796
0
            ret = MP_EXPTMOD_E;
797
0
        }
798
0
    }
799
    /* Check p*q = n. */
800
0
    if (ret == 0 ) {
801
    #ifdef WOLFSSL_CHECK_MEM_ZERO
802
        mp_memzero_add("RSA CheckKey tmp", tmp);
803
    #endif
804
0
        if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
805
0
            ret = MP_EXPTMOD_E;
806
0
        }
807
0
    }
808
0
    if (ret == 0 ) {
809
0
        if (mp_cmp(&key->n, tmp) != MP_EQ) {
810
0
            ret = MP_EXPTMOD_E;
811
0
        }
812
0
    }
813
814
0
#ifndef WC_RSA_NO_FERMAT_CHECK
815
    /* Fermat's Factorization works when difference between p and q
816
     * is less than (conservatively):
817
     *     n^(1/4) + 32
818
     *  ~= 2^(bit count of n)^(1/4) + 32) = 2^((bit count of n)/4 + 32)
819
     */
820
0
    if (ret == 0) {
821
0
        ret = mp_sub(&key->p, &key->q, tmp);
822
0
    }
823
0
    if (ret == 0) {
824
0
        if (mp_count_bits(tmp) <= (mp_count_bits(&key->n) / 4 + 32)) {
825
0
            ret = MP_EXPTMOD_E;
826
0
        }
827
0
    }
828
0
#endif
829
830
    /* Check dP, dQ and u if they exist */
831
0
    if (ret == 0 && !mp_iszero(&key->dP)) {
832
0
        if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) {
833
0
            ret = MP_EXPTMOD_E;
834
0
        }
835
        /* Check dP <= p-1. */
836
0
        if (ret == 0) {
837
0
            if (mp_cmp(&key->dP, tmp) != MP_LT) {
838
0
                ret = MP_EXPTMOD_E;
839
0
            }
840
0
        }
841
        /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
842
0
        if (ret == 0) {
843
0
            if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
844
0
                ret = MP_EXPTMOD_E;
845
0
            }
846
0
        }
847
0
        if (ret == 0 ) {
848
0
            if (!mp_isone(tmp)) {
849
0
                ret = MP_EXPTMOD_E;
850
0
            }
851
0
        }
852
853
0
        if (ret == 0) {
854
0
            if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
855
0
                ret = MP_EXPTMOD_E;
856
0
            }
857
0
        }
858
        /* Check dQ <= q-1. */
859
0
        if (ret == 0) {
860
0
            if (mp_cmp(&key->dQ, tmp) != MP_LT) {
861
0
                ret = MP_EXPTMOD_E;
862
0
            }
863
0
        }
864
        /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
865
0
        if (ret == 0) {
866
0
            if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
867
0
                ret = MP_EXPTMOD_E;
868
0
            }
869
0
        }
870
0
        if (ret == 0 ) {
871
0
            if (!mp_isone(tmp)) {
872
0
                ret = MP_EXPTMOD_E;
873
0
            }
874
0
        }
875
876
        /* Check u <= p. */
877
0
        if (ret == 0) {
878
0
            if (mp_cmp(&key->u, &key->p) != MP_LT) {
879
0
                ret = MP_EXPTMOD_E;
880
0
            }
881
0
        }
882
        /* Check u*q mod p = 1. (u = 1/q mod p) */
883
0
        if (ret == 0) {
884
0
            if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
885
0
                ret = MP_EXPTMOD_E;
886
0
            }
887
0
        }
888
0
        if (ret == 0 ) {
889
0
            if (!mp_isone(tmp)) {
890
0
                ret = MP_EXPTMOD_E;
891
0
            }
892
0
        }
893
0
    }
894
895
0
    mp_forcezero(tmp);
896
897
0
    RESTORE_VECTOR_REGISTERS();
898
899
0
    if ((rng != NULL) && (rng != key->rng)) {
900
0
        wc_FreeRng(rng);
901
0
#ifdef WOLFSSL_SMALL_STACK
902
0
        XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
903
0
#endif
904
0
    }
905
0
    FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
906
#ifdef WOLFSSL_CHECK_MEM_ZERO
907
    mp_memzero_check(tmp);
908
#endif
909
910
0
    return ret;
911
0
}
912
#endif /* WOLFSSL_RSA_KEY_CHECK */
913
914
915
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)
916
/* Uses MGF1 standard as a mask generation function
917
   hType: hash type used
918
   seed:  seed to use for generating mask
919
   seedSz: size of seed buffer
920
   out:   mask output after generation
921
   outSz: size of output buffer
922
 */
923
#if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
924
static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
925
                                        byte* out, word32 outSz, void* heap)
926
2.81k
{
927
2.81k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
928
2.81k
    byte* tmp = NULL;
929
2.81k
    byte   tmpF = 0;     /* 1 if dynamic memory needs freed */
930
#else
931
    byte tmp[RSA_MAX_SIZE/8];
932
#endif
933
    /* needs to be large enough for seed size plus counter(4) */
934
2.81k
    byte  tmpA[WC_MAX_DIGEST_SIZE + 4];
935
2.81k
    word32 tmpSz = 0;
936
2.81k
    int hLen;
937
2.81k
    int ret;
938
2.81k
    word32 counter;
939
2.81k
    word32 idx;
940
#ifdef WOLFSSL_SMALL_STACK_CACHE
941
    wc_HashAlg *hash;
942
#endif
943
2.81k
    hLen    = wc_HashGetDigestSize(hType);
944
2.81k
    counter = 0;
945
2.81k
    idx     = 0;
946
947
2.81k
    (void)heap;
948
949
2.81k
    XMEMSET(tmpA, 0, sizeof(tmpA));
950
    /* check error return of wc_HashGetDigestSize */
951
2.81k
    if (hLen < 0) {
952
0
        return hLen;
953
0
    }
954
955
    /* if tmp is not large enough than use some dynamic memory */
956
2.81k
    if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
957
        /* find largest amount of memory needed which will be the max of
958
         * hLen and (seedSz + 4) since tmp is used to store the hash digest */
959
339
        tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
960
339
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
961
339
        tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
962
339
        if (tmp == NULL) {
963
0
            return MEMORY_E;
964
0
        }
965
339
        tmpF = 1; /* make sure to free memory when done */
966
#else
967
        if (tmpSz > RSA_MAX_SIZE/8)
968
            return BAD_FUNC_ARG;
969
#endif
970
339
    }
971
2.47k
    else {
972
        /* use array on the stack */
973
2.47k
    #ifndef WOLFSSL_SMALL_STACK_CACHE
974
2.47k
        tmpSz = sizeof(tmpA);
975
2.47k
    #endif
976
2.47k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
977
2.47k
        tmp  = tmpA;
978
2.47k
        tmpF = 0; /* no need to free memory at end */
979
2.47k
#endif
980
2.47k
    }
981
982
#ifdef WOLFSSL_SMALL_STACK_CACHE
983
    hash = (wc_HashAlg*)XMALLOC(sizeof(*hash), heap, DYNAMIC_TYPE_DIGEST);
984
    if (hash == NULL) {
985
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
986
        if (tmpF) {
987
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
988
        }
989
    #endif
990
        return MEMORY_E;
991
    }
992
    ret = wc_HashInit_ex(hash, hType, heap, INVALID_DEVID);
993
    if (ret != 0) {
994
        XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
995
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
996
        if (tmpF) {
997
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
998
        }
999
    #endif
1000
        return ret;
1001
    }
1002
#endif
1003
1004
15.3k
    do {
1005
15.3k
        int i = 0;
1006
15.3k
        XMEMCPY(tmp, seed, seedSz);
1007
1008
        /* counter to byte array appended to tmp */
1009
15.3k
        tmp[seedSz]     = (byte)((counter >> 24) & 0xFF);
1010
15.3k
        tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
1011
15.3k
        tmp[seedSz + 2] = (byte)((counter >>  8) & 0xFF);
1012
15.3k
        tmp[seedSz + 3] = (byte)((counter)       & 0xFF);
1013
1014
        /* hash and append to existing output */
1015
#ifdef WOLFSSL_SMALL_STACK_CACHE
1016
        ret = wc_HashUpdate(hash, hType, tmp, (seedSz + 4));
1017
        if (ret == 0) {
1018
            ret = wc_HashFinal(hash, hType, tmp);
1019
        }
1020
#else
1021
15.3k
        ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz);
1022
15.3k
#endif
1023
15.3k
        if (ret != 0) {
1024
            /* check for if dynamic memory was needed, then free */
1025
#ifdef WOLFSSL_SMALL_STACK_CACHE
1026
            wc_HashFree(hash, hType);
1027
            XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
1028
#endif
1029
49
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1030
49
            if (tmpF) {
1031
0
                XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1032
0
            }
1033
49
#endif
1034
49
            return ret;
1035
49
        }
1036
1037
534k
        for (i = 0; i < hLen && idx < outSz; i++) {
1038
519k
            out[idx++] = tmp[i];
1039
519k
        }
1040
15.3k
        counter++;
1041
15.3k
    } while (idx < outSz);
1042
2.76k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1043
    /* check for if dynamic memory was needed, then free */
1044
2.76k
    if (tmpF) {
1045
339
        XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1046
339
    }
1047
2.76k
#endif
1048
#ifdef WOLFSSL_SMALL_STACK_CACHE
1049
    wc_HashFree(hash, hType);
1050
    XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
1051
#endif
1052
1053
2.76k
    return 0;
1054
2.81k
}
1055
#endif /* SHA2 Hashes */
1056
1057
/* helper function to direct which mask generation function is used
1058
   switched on type input
1059
 */
1060
static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
1061
                                                    word32 outSz, void* heap)
1062
2.88k
{
1063
2.88k
    int ret;
1064
1065
2.88k
    switch(type) {
1066
0
    #ifndef NO_SHA
1067
155
        case WC_MGF1SHA1:
1068
155
            ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
1069
155
            break;
1070
0
    #endif
1071
0
    #ifndef NO_SHA256
1072
0
    #ifdef WOLFSSL_SHA224
1073
149
        case WC_MGF1SHA224:
1074
149
            ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
1075
149
            break;
1076
0
    #endif
1077
1.43k
        case WC_MGF1SHA256:
1078
1.43k
            ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
1079
1.43k
            break;
1080
0
    #endif
1081
0
    #ifdef WOLFSSL_SHA384
1082
454
        case WC_MGF1SHA384:
1083
454
            ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
1084
454
            break;
1085
0
    #endif
1086
0
    #ifdef WOLFSSL_SHA512
1087
428
        case WC_MGF1SHA512:
1088
428
            ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
1089
428
            break;
1090
0
        #ifndef WOLFSSL_NOSHA512_224
1091
144
        case WC_MGF1SHA512_224:
1092
144
            ret = RsaMGF1(WC_HASH_TYPE_SHA512_224, seed, seedSz, out, outSz,
1093
144
                heap);
1094
144
            break;
1095
0
        #endif
1096
0
        #ifndef WOLFSSL_NOSHA512_256
1097
49
        case WC_MGF1SHA512_256:
1098
49
            ret = RsaMGF1(WC_HASH_TYPE_SHA512_256, seed, seedSz, out, outSz,
1099
49
                heap);
1100
49
            break;
1101
0
        #endif
1102
0
    #endif
1103
75
        default:
1104
75
            WOLFSSL_MSG("Unknown MGF type: check build options");
1105
75
            ret = BAD_FUNC_ARG;
1106
2.88k
    }
1107
1108
    /* in case of default avoid unused warning */
1109
2.88k
    (void)seed;
1110
2.88k
    (void)seedSz;
1111
2.88k
    (void)out;
1112
2.88k
    (void)outSz;
1113
2.88k
    (void)heap;
1114
1115
2.88k
    return ret;
1116
2.88k
}
1117
#endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */
1118
1119
1120
/* Padding */
1121
#ifndef WOLFSSL_RSA_VERIFY_ONLY
1122
#ifndef WC_NO_RNG
1123
#ifndef WC_NO_RSA_OAEP
1124
static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
1125
        word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
1126
        enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
1127
        void* heap)
1128
434
{
1129
434
    int ret;
1130
434
    word32 hLen;
1131
434
    int psLen;
1132
434
    word32 idx;
1133
1134
434
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1135
434
        byte* dbMask = NULL;
1136
434
        byte* lHash = NULL;
1137
434
        byte* seed  = NULL;
1138
    #else
1139
        byte dbMask[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1140
        /* must be large enough to contain largest hash */
1141
        byte lHash[WC_MAX_DIGEST_SIZE];
1142
        byte seed[WC_MAX_DIGEST_SIZE];
1143
    #endif
1144
1145
    /* no label is allowed, but catch if no label provided and length > 0 */
1146
434
    if (optLabel == NULL && labelLen > 0) {
1147
0
        return BUFFER_E;
1148
0
    }
1149
1150
    /* limit of label is the same as limit of hash function which is massive */
1151
434
    ret = wc_HashGetDigestSize(hType);
1152
434
    if (ret < 0) {
1153
2
        return ret;
1154
2
    }
1155
432
    hLen = (word32)ret;
1156
1157
432
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1158
432
        lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1159
432
        if (lHash == NULL) {
1160
0
            return MEMORY_E;
1161
0
        }
1162
432
        seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1163
432
        if (seed == NULL) {
1164
0
            XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1165
0
            return MEMORY_E;
1166
0
        }
1167
    #else
1168
        /* hLen should never be larger than lHash since size is max digest size,
1169
           but check before blindly calling wc_Hash */
1170
        if (hLen > sizeof(lHash)) {
1171
            WOLFSSL_MSG("OAEP lHash to small for digest!!");
1172
            return MEMORY_E;
1173
        }
1174
    #endif
1175
1176
432
    if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
1177
4
        WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
1178
4
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1179
4
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1180
4
        return ret;
1181
4
    }
1182
1183
    /* handles check of location for idx as well as psLen, cast to int to check
1184
       for pkcsBlockLen(k) - 2 * hLen - 2 being negative
1185
       This check is similar to decryption where k > 2 * hLen + 2 as msg
1186
       size approaches 0. In decryption if k is less than or equal -- then there
1187
       is no possible room for msg.
1188
       k = RSA key size
1189
       hLen = hash digest size -- will always be >= 0 at this point
1190
     */
1191
428
    if ((2 * hLen + 2) > pkcsBlockLen) {
1192
7
        WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
1193
7
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1194
7
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1195
7
        return BAD_FUNC_ARG;
1196
7
    }
1197
1198
421
    if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
1199
7
        WOLFSSL_MSG("OAEP pad error message too long");
1200
7
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1201
7
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1202
7
        return BAD_FUNC_ARG;
1203
7
    }
1204
1205
    /* concatenate lHash || PS || 0x01 || msg */
1206
414
    idx = pkcsBlockLen - 1 - inputLen;
1207
414
    psLen = (int)pkcsBlockLen - (int)inputLen - 2 * (int)hLen - 2;
1208
414
    if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
1209
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1210
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1211
0
        return BUFFER_E;
1212
0
    }
1213
414
    XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
1214
414
    pkcsBlock[idx--] = 0x01; /* PS and M separator */
1215
414
    XMEMSET(pkcsBlock + idx - psLen + 1, 0, (size_t)psLen);
1216
414
    idx -= (word32)psLen;
1217
1218
414
    idx = idx - hLen + 1;
1219
414
    XMEMCPY(pkcsBlock + idx, lHash, hLen);
1220
1221
    /* generate random seed */
1222
414
    if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
1223
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1224
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1225
0
        return ret;
1226
0
    }
1227
1228
414
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1229
    /* create maskedDB from dbMask */
1230
414
    dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
1231
414
    if (dbMask == NULL) {
1232
1233
0
            XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1234
0
            XFREE(seed,  heap, DYNAMIC_TYPE_RSA_BUFFER);
1235
0
        return MEMORY_E;
1236
0
    }
1237
#else
1238
    if (pkcsBlockLen - hLen - 1 > sizeof(dbMask)) {
1239
        return MEMORY_E;
1240
    }
1241
#endif
1242
414
    XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
1243
414
    ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
1244
414
    if (ret != 0) {
1245
68
            WC_FREE_VAR_EX(dbMask, heap, DYNAMIC_TYPE_RSA);
1246
68
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1247
68
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1248
68
        return ret;
1249
68
    }
1250
1251
346
    xorbuf(pkcsBlock + hLen + 1, dbMask,pkcsBlockLen - hLen - 1);
1252
1253
346
    WC_FREE_VAR_EX(dbMask, heap, DYNAMIC_TYPE_RSA);
1254
1255
    /* create maskedSeed from seedMask */
1256
346
    pkcsBlock[0] = 0x00;
1257
    /* create seedMask inline */
1258
346
    if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
1259
346
                                           pkcsBlock + 1, hLen, heap)) != 0) {
1260
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1261
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1262
0
        return ret;
1263
0
    }
1264
1265
    /* xor created seedMask with seed to make maskedSeed */
1266
346
    xorbuf(pkcsBlock + 1, seed, hLen);
1267
#ifdef WOLFSSL_CHECK_MEM_ZERO
1268
    /* Seed must be zeroized now that it has been used. */
1269
    wc_MemZero_Add("Pad OAEP seed", seed, hLen);
1270
#endif
1271
1272
    /* Zeroize masking bytes so that padding can't be unmasked. */
1273
346
    ForceZero(seed, hLen);
1274
346
    #ifdef WOLFSSL_SMALL_STACK
1275
346
        XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1276
346
        XFREE(seed,  heap, DYNAMIC_TYPE_RSA_BUFFER);
1277
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
1278
        wc_MemZero_Check(seed, hLen);
1279
    #endif
1280
346
    (void)padValue;
1281
1282
346
    return 0;
1283
346
}
1284
#endif /* !WC_NO_RSA_OAEP */
1285
1286
#ifdef WC_RSA_PSS
1287
1288
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
1289
 * XOR MGF over all bytes down to end of Salt
1290
 * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
1291
 *
1292
 * input         Digest of the message.
1293
 * inputLen      Length of digest.
1294
 * pkcsBlock     Buffer to write to.
1295
 * pkcsBlockLen  Length of buffer to write to.
1296
 * rng           Random number generator (for salt).
1297
 * htype         Hash function to use.
1298
 * mgf           Mask generation function.
1299
 * saltLen       Length of salt to put in padding.
1300
 * bits          Length of key in bits.
1301
 * heap          Used for dynamic memory allocation.
1302
 * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
1303
 * and other negative values on error.
1304
 */
1305
static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
1306
        word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
1307
        int saltLen, int bits, void* heap)
1308
1.34k
{
1309
1.34k
    int   ret = 0;
1310
1.34k
    int   hLen, o, maskLen, hiBits;
1311
1.34k
    byte* m;
1312
1.34k
    byte* s;
1313
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
1314
    byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1315
#else
1316
1.34k
    byte* msg = NULL;
1317
1.34k
#endif
1318
1.34k
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1319
1.34k
    byte* salt;
1320
#else
1321
    byte salt[WC_MAX_DIGEST_SIZE];
1322
#endif
1323
1324
1.34k
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1325
1.34k
    if (pkcsBlockLen > RSA_MAX_SIZE/8) {
1326
0
        return MEMORY_E;
1327
0
    }
1328
1.34k
#endif
1329
1330
1.34k
    hLen = wc_HashGetDigestSize(hType);
1331
1.34k
    if (hLen < 0)
1332
7
        return hLen;
1333
1.33k
    if ((int)inputLen != hLen) {
1334
11
        return BAD_FUNC_ARG;
1335
11
    }
1336
1337
1.32k
    hiBits = (bits - 1) & 0x7;
1338
1.32k
    if (hiBits == 0) {
1339
        /* Per RFC8017, set the leftmost 8emLen - emBits bits of the
1340
           leftmost octet in DB to zero.
1341
        */
1342
13
        *(pkcsBlock++) = 0;
1343
13
        pkcsBlockLen--;
1344
13
    }
1345
1346
1.32k
    if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
1347
1.31k
        saltLen = hLen;
1348
1.31k
        #ifdef WOLFSSL_SHA512
1349
            /* See FIPS 186-4 section 5.5 item (e). */
1350
1.31k
            if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
1351
6
                saltLen = RSA_PSS_SALT_MAX_SZ;
1352
6
            }
1353
1.31k
        #endif
1354
1.31k
    }
1355
#ifndef WOLFSSL_PSS_LONG_SALT
1356
    else if (saltLen > hLen) {
1357
        return PSS_SALTLEN_E;
1358
    }
1359
#endif
1360
13
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
1361
13
    else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
1362
0
        return PSS_SALTLEN_E;
1363
0
    }
1364
#else
1365
    else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
1366
        saltLen = (int)pkcsBlockLen - hLen - 2;
1367
        if (saltLen < 0) {
1368
            return PSS_SALTLEN_E;
1369
        }
1370
    }
1371
    else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
1372
        return PSS_SALTLEN_E;
1373
    }
1374
#endif
1375
1.32k
    if ((int)pkcsBlockLen - hLen < saltLen + 2) {
1376
1
        return PSS_SALTLEN_E;
1377
1
    }
1378
1.32k
    maskLen = (int)pkcsBlockLen - 1 - hLen;
1379
1380
1.32k
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1381
1.32k
    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1382
1.32k
        msg = (byte*)XMALLOC(
1383
1.32k
                          (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen),
1384
1.32k
                          heap, DYNAMIC_TYPE_RSA_BUFFER);
1385
1.32k
        if (msg == NULL) {
1386
9
            return MEMORY_E;
1387
9
        }
1388
1.31k
    #endif
1389
1.31k
    salt = s = m = msg;
1390
1.31k
    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1391
1.31k
    m += RSA_PSS_PAD_SZ;
1392
1.31k
    XMEMCPY(m, input, inputLen);
1393
1.31k
    m += inputLen;
1394
1.31k
    o = (int)(m - s);
1395
1.31k
    if (saltLen > 0) {
1396
1.30k
        ret = wc_RNG_GenerateBlock(rng, m, (word32)saltLen);
1397
1.30k
        if (ret == 0) {
1398
1.28k
            m += saltLen;
1399
1.28k
        }
1400
1.30k
    }
1401
#else
1402
    if ((int)pkcsBlockLen < RSA_PSS_PAD_SZ + (int)inputLen + saltLen) {
1403
    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1404
        msg = (byte*)XMALLOC(
1405
                          (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen),
1406
                          heap, DYNAMIC_TYPE_RSA_BUFFER);
1407
        if (msg == NULL) {
1408
            return MEMORY_E;
1409
        }
1410
    #endif
1411
        m = msg;
1412
    }
1413
    else {
1414
        m = pkcsBlock;
1415
    }
1416
    s = m;
1417
    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1418
    m += RSA_PSS_PAD_SZ;
1419
    XMEMCPY(m, input, inputLen);
1420
    m += inputLen;
1421
    o = 0;
1422
    if (saltLen > 0) {
1423
        ret = wc_RNG_GenerateBlock(rng, salt, (word32)saltLen);
1424
        if (ret == 0) {
1425
            XMEMCPY(m, salt, (size_t)saltLen);
1426
            m += saltLen;
1427
        }
1428
    }
1429
#endif
1430
1.31k
    if (ret == 0) {
1431
        /* Put Hash at end of pkcsBlock - 1 */
1432
1.29k
        ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, (word32)hLen);
1433
1.29k
    }
1434
1.31k
    if (ret == 0) {
1435
       /* Set the last eight bits or trailer field to the octet 0xbc */
1436
1.28k
        pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
1437
1438
1.28k
        ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, pkcsBlock, (word32)maskLen, heap);
1439
1.28k
    }
1440
1.31k
    if (ret == 0) {
1441
        /* Clear the first high bit when "8emLen - emBits" is non-zero.
1442
           where emBits = n modBits - 1 */
1443
1.23k
        if (hiBits)
1444
1.22k
            pkcsBlock[0] &= (byte)((1 << hiBits) - 1);
1445
1446
1.23k
        m = pkcsBlock + maskLen - saltLen - 1;
1447
1.23k
        *(m++) ^= 0x01;
1448
1.23k
        xorbuf(m, salt + o, (word32)saltLen);
1449
1.23k
    }
1450
1451
1.31k
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1452
    /* msg is always not NULL as we bail on allocation failure */
1453
1.31k
    XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER);
1454
1.31k
#endif
1455
1.31k
    return ret;
1456
1.32k
}
1457
#endif /* WC_RSA_PSS */
1458
#endif /* !WC_NO_RNG */
1459
1460
static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
1461
                           word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
1462
8.87k
{
1463
8.87k
    if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
1464
8.87k
                                                        pkcsBlockLen == 0) {
1465
0
        return BAD_FUNC_ARG;
1466
0
    }
1467
1468
8.87k
    if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
1469
0
        WOLFSSL_MSG("RsaPad error, invalid length");
1470
0
        return RSA_PAD_E;
1471
0
    }
1472
8.87k
    pkcsBlock[0] = 0x0;       /* set first byte to zero and advance */
1473
8.87k
    pkcsBlock++; pkcsBlockLen--;
1474
8.87k
    pkcsBlock[0] = padValue;  /* insert padValue */
1475
1476
8.87k
    if (padValue == RSA_BLOCK_TYPE_1) {
1477
1478
        /* pad with 0xff bytes */
1479
8.82k
        XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
1480
8.82k
    }
1481
48
    else {
1482
48
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
1483
        /* pad with non-zero random bytes */
1484
48
        word32 padLen, i;
1485
48
        int    ret;
1486
48
        padLen = pkcsBlockLen - inputLen - 1;
1487
48
        ret    = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
1488
48
        if (ret != 0) {
1489
0
            return ret;
1490
0
        }
1491
1492
        /* remove zeros */
1493
8.84k
        for (i = 1; i < padLen; i++) {
1494
8.79k
            if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
1495
8.79k
        }
1496
#else
1497
        (void)rng;
1498
        return RSA_WRONG_TYPE_E;
1499
#endif
1500
48
    }
1501
1502
8.87k
    pkcsBlock[pkcsBlockLen-inputLen-1] = 0;     /* separator */
1503
8.87k
    XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
1504
1505
8.87k
    return 0;
1506
8.87k
}
1507
1508
/* helper function to direct which padding is used */
1509
int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
1510
    word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
1511
    enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
1512
    int saltLen, int bits, void* heap)
1513
10.6k
{
1514
10.6k
    int ret;
1515
1516
10.6k
    switch (padType)
1517
10.6k
    {
1518
8.87k
        case WC_RSA_PKCSV15_PAD:
1519
            /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
1520
8.87k
            ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
1521
8.87k
                                                                 padValue, rng);
1522
8.87k
            break;
1523
1524
0
#ifndef WC_NO_RNG
1525
0
    #ifndef WC_NO_RSA_OAEP
1526
434
        case WC_RSA_OAEP_PAD:
1527
434
            WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
1528
434
            ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
1529
434
                           padValue, rng, hType, mgf, optLabel, labelLen, heap);
1530
434
            break;
1531
0
    #endif
1532
1533
0
    #ifdef WC_RSA_PSS
1534
1.34k
        case WC_RSA_PSS_PAD:
1535
1.34k
            WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
1536
1.34k
            ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
1537
1.34k
                                               hType, mgf, saltLen, bits, heap);
1538
1.34k
            break;
1539
0
    #endif
1540
0
#endif /* !WC_NO_RNG */
1541
1542
0
    #ifdef WC_RSA_NO_PADDING
1543
27
        case WC_RSA_NO_PAD:
1544
27
        {
1545
27
            int bytes = (bits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
1546
1547
27
            WOLFSSL_MSG("wolfSSL Using NO padding");
1548
1549
            /* In the case of no padding being used check that input is exactly
1550
             * the RSA key length */
1551
27
            if ((bits <= 0) || (inputLen != (word32)bytes)) {
1552
25
                WOLFSSL_MSG("Bad input size");
1553
25
                ret = RSA_PAD_E;
1554
25
            }
1555
2
            else {
1556
2
                XMEMCPY(pkcsBlock, input, inputLen);
1557
2
                ret = 0;
1558
2
            }
1559
27
            break;
1560
0
        }
1561
0
    #endif
1562
1563
0
        default:
1564
0
            WOLFSSL_MSG("Unknown RSA Pad Type");
1565
0
            ret = RSA_PAD_E;
1566
10.6k
    }
1567
1568
    /* silence warning if not used with padding scheme */
1569
10.6k
    (void)input;
1570
10.6k
    (void)inputLen;
1571
10.6k
    (void)pkcsBlock;
1572
10.6k
    (void)pkcsBlockLen;
1573
10.6k
    (void)padValue;
1574
10.6k
    (void)rng;
1575
10.6k
    (void)padType;
1576
10.6k
    (void)hType;
1577
10.6k
    (void)mgf;
1578
10.6k
    (void)optLabel;
1579
10.6k
    (void)labelLen;
1580
10.6k
    (void)saltLen;
1581
10.6k
    (void)bits;
1582
10.6k
    (void)heap;
1583
1584
10.6k
    return ret;
1585
10.6k
}
1586
#endif /* WOLFSSL_RSA_VERIFY_ONLY */
1587
1588
1589
/* UnPadding */
1590
#if !defined(WC_NO_RSA_OAEP) && !defined(NO_HASH_WRAPPER)
1591
/* UnPad plaintext, set start to *output, return length of plaintext,
1592
 * < 0 on error */
1593
static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
1594
                            byte **output, enum wc_HashType hType, int mgf,
1595
                            byte* optLabel, word32 labelLen, void* heap)
1596
0
{
1597
0
    word32 hLen;
1598
0
    int ret;
1599
0
    byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
1600
0
    word32 idx;
1601
0
    word32 i;
1602
0
    volatile word32 inc;
1603
1604
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1605
0
    byte* tmp  = NULL;
1606
#else
1607
    byte tmp[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1608
#endif
1609
1610
    /* no label is allowed, but catch if no label provided and length > 0 */
1611
0
    if (optLabel == NULL && labelLen > 0) {
1612
0
        return BUFFER_E;
1613
0
    }
1614
1615
0
    ret = wc_HashGetDigestSize(hType);
1616
0
    if ((ret < 0) || (pkcsBlockLen < (2 * (word32)ret + 2))) {
1617
0
        return BAD_FUNC_ARG;
1618
0
    }
1619
0
    hLen = (word32)ret;
1620
1621
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1622
0
    tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1623
0
    if (tmp == NULL) {
1624
0
        return MEMORY_E;
1625
0
    }
1626
0
#endif
1627
0
    XMEMSET(tmp, 0, pkcsBlockLen);
1628
#ifdef WOLFSSL_CHECK_MEM_ZERO
1629
    wc_MemZero_Add("OAEP UnPad temp", tmp, pkcsBlockLen);
1630
#endif
1631
1632
    /* find seedMask value */
1633
0
    ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
1634
0
                 pkcsBlockLen - hLen - 1, tmp, hLen, heap);
1635
0
    if (ret != 0) {
1636
0
        WC_FREE_VAR_EX(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1637
0
        return ret;
1638
0
    }
1639
1640
    /* xor seedMask value with maskedSeed to get seed value */
1641
0
    xorbuf(tmp, pkcsBlock + 1, hLen);
1642
1643
    /* get dbMask value */
1644
0
    ret = RsaMGF(mgf, tmp, hLen, tmp + hLen, pkcsBlockLen - hLen - 1, heap);
1645
0
    if (ret != 0) {
1646
0
        ForceZero(tmp, hLen);
1647
0
#ifdef WOLFSSL_SMALL_STACK
1648
0
        XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER);
1649
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
1650
        wc_MemZero_Check(tmp, hLen);
1651
#endif
1652
0
        return ret;
1653
0
    }
1654
1655
    /* get DB value by doing maskedDB xor dbMask */
1656
0
    xorbuf(pkcsBlock + hLen + 1, tmp + hLen, pkcsBlockLen - hLen - 1);
1657
1658
0
    ForceZero(tmp, pkcsBlockLen);
1659
0
#ifdef WOLFSSL_SMALL_STACK
1660
    /* done with use of tmp buffer */
1661
0
    XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1662
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
1663
    wc_MemZero_Check(tmp, pkcsBlockLen);
1664
#endif
1665
1666
    /* advance idx to index of PS and msg separator, account for PS size of 0*/
1667
0
    idx = hLen + 1 + hLen;
1668
    /* Don't reveal length of message: look at every byte. */
1669
0
    inc = 1;
1670
0
    for (i = hLen + 1 + hLen; i < pkcsBlockLen - 1; i++) {
1671
        /* Looking for non-zero byte. */
1672
0
        inc &= 1 - (((word32)0 - pkcsBlock[i]) >> 31);
1673
0
        idx += inc;
1674
0
    }
1675
1676
    /* create hash of label for comparison with hash sent */
1677
0
    ret = wc_Hash(hType, optLabel, labelLen, h, hLen);
1678
0
    if (ret != 0) {
1679
0
        return ret;
1680
0
    }
1681
1682
    /* say no to chosen ciphertext attack.
1683
       Comparison of lHash, Y, and separator value needs to all happen in
1684
       constant time.
1685
       Attackers should not be able to get error condition from the timing of
1686
       these checks.
1687
     */
1688
0
    {
1689
0
        volatile int c = ConstantCompare(pkcsBlock + hLen + 1, h, (int)hLen);
1690
0
        c = c + (pkcsBlock[idx++] ^ 0x01); /* separator value is 0x01 */
1691
0
        c = c + (pkcsBlock[0]     ^ 0x00); /* Y, the first value, should be 0 */
1692
1693
        /* Return 0 data length on error. */
1694
0
        idx = ctMaskSelWord32(ctMaskEq(c, 0), idx, pkcsBlockLen);
1695
0
    }
1696
1697
    /* adjust pointer to correct location in array and return size of M */
1698
0
    *output = (byte*)(pkcsBlock + idx);
1699
0
    return (int)(pkcsBlockLen - idx);
1700
0
}
1701
#endif /* !WC_NO_RSA_OAEP */
1702
1703
#ifdef WC_RSA_PSS
1704
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
1705
 * MGF over all bytes down to end of Salt
1706
 *
1707
 * pkcsBlock     Buffer holding decrypted data.
1708
 * pkcsBlockLen  Length of buffer.
1709
 * htype         Hash function to use.
1710
 * mgf           Mask generation function.
1711
 * saltLen       Length of salt to put in padding.
1712
 * bits          Length of key in bits.
1713
 * heap          Used for dynamic memory allocation.
1714
 * returns       the sum of salt length and SHA-256 digest size on success.
1715
 *               Otherwise, PSS_SALTLEN_E for an incorrect salt length,
1716
 *               WC_KEY_SIZE_E for an incorrect encoded message (EM) size
1717
                 and other negative values on error.
1718
 */
1719
static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
1720
                        byte **output, enum wc_HashType hType, int mgf,
1721
                        int saltLen, int bits, void* heap)
1722
1.03k
{
1723
1.03k
    int   ret;
1724
1.03k
    byte* tmp;
1725
1.03k
    int   hLen, i, maskLen;
1726
1.03k
#ifdef WOLFSSL_SHA512
1727
1.03k
    int orig_bits = bits;
1728
1.03k
#endif
1729
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
1730
    byte tmp_buf[RSA_MAX_SIZE/8];
1731
    tmp = tmp_buf;
1732
1733
    if (pkcsBlockLen > RSA_MAX_SIZE/8) {
1734
        return MEMORY_E;
1735
    }
1736
#endif
1737
1738
1.03k
    hLen = wc_HashGetDigestSize(hType);
1739
1.03k
    if (hLen < 0)
1740
57
        return hLen;
1741
978
    bits = (bits - 1) & 0x7;
1742
978
    if ((pkcsBlock[0] & (0xff << bits)) != 0) {
1743
28
        return BAD_PADDING_E;
1744
28
    }
1745
950
    if (bits == 0) {
1746
54
        pkcsBlock++;
1747
54
        pkcsBlockLen--;
1748
54
    }
1749
950
    maskLen = (int)pkcsBlockLen - 1 - hLen;
1750
950
    if (maskLen < 0) {
1751
80
        WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
1752
80
        return WC_KEY_SIZE_E;
1753
80
    }
1754
1755
870
    if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
1756
865
        saltLen = hLen;
1757
865
        #ifdef WOLFSSL_SHA512
1758
            /* See FIPS 186-4 section 5.5 item (e). */
1759
865
            if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
1760
10
                saltLen = RSA_PSS_SALT_MAX_SZ;
1761
865
        #endif
1762
865
    }
1763
#ifndef WOLFSSL_PSS_LONG_SALT
1764
    else if (saltLen > hLen)
1765
        return PSS_SALTLEN_E;
1766
#endif
1767
5
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
1768
5
    else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
1769
0
        return PSS_SALTLEN_E;
1770
870
    if (maskLen < saltLen + 1) {
1771
1
        return PSS_SALTLEN_E;
1772
1
    }
1773
#else
1774
    else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
1775
        return PSS_SALTLEN_E;
1776
    if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
1777
        return WC_KEY_SIZE_E;
1778
    }
1779
#endif
1780
1781
869
    if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
1782
27
        WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
1783
27
        return BAD_PADDING_E;
1784
27
    }
1785
1786
842
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1787
842
    tmp = (byte*)XMALLOC((size_t)maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1788
842
    if (tmp == NULL) {
1789
1
        return MEMORY_E;
1790
1
    }
1791
841
    XMEMSET(tmp, 0, (size_t)maskLen);
1792
841
#endif
1793
1794
841
    if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, tmp, (word32)maskLen,
1795
841
                                                                  heap)) != 0) {
1796
5
        #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1797
5
        XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1798
5
        #endif
1799
5
        return ret;
1800
5
    }
1801
1802
836
    tmp[0] &= (byte)((1 << bits) - 1);
1803
836
    pkcsBlock[0] &= (byte)((1 << bits) - 1);
1804
#ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
1805
    if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
1806
        for (i = 0; i < maskLen - 1; i++) {
1807
            if (tmp[i] != pkcsBlock[i]) {
1808
                break;
1809
            }
1810
        }
1811
        if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
1812
            #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1813
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1814
            #endif
1815
            WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
1816
            return PSS_SALTLEN_RECOVER_E;
1817
        }
1818
        saltLen = maskLen - (i + 1);
1819
    }
1820
    else
1821
#endif
1822
836
    {
1823
140k
        for (i = 0; i < maskLen - 1 - saltLen; i++) {
1824
139k
            if (tmp[i] != pkcsBlock[i]) {
1825
19
                #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1826
19
                XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1827
19
                #endif
1828
19
                WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
1829
19
                return PSS_SALTLEN_E;
1830
19
            }
1831
139k
        }
1832
817
        if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
1833
10
            #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1834
10
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1835
10
            #endif
1836
10
            WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
1837
10
            return PSS_SALTLEN_E;
1838
10
        }
1839
817
    }
1840
807
    xorbuf(pkcsBlock + i, tmp + i, (word32)(maskLen - i));
1841
1842
807
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1843
807
    XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1844
807
#endif
1845
1846
807
    *output = pkcsBlock + maskLen - saltLen;
1847
807
    return saltLen + hLen;
1848
817
}
1849
#endif
1850
1851
/* UnPad plaintext, set start to *output, return length of plaintext,
1852
 * < 0 on error */
1853
static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
1854
                    byte **output, byte padValue)
1855
7.05k
{
1856
7.05k
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
1857
7.05k
    word16 i;
1858
1859
7.05k
    if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
1860
24
        return BAD_FUNC_ARG;
1861
24
    }
1862
1863
7.03k
    if (padValue == RSA_BLOCK_TYPE_1) {
1864
        /* First byte must be 0x00 and Second byte, block type, 0x01 */
1865
7.03k
        if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
1866
577
            WOLFSSL_MSG("RsaUnPad error, invalid formatting");
1867
577
            return RSA_PAD_E;
1868
577
        }
1869
1870
        /* check the padding until we find the separator */
1871
1.33M
        for (i = 2; i < pkcsBlockLen; ) {
1872
1.33M
            if (pkcsBlock[i++] != 0xFF) {
1873
6.45k
                break;
1874
6.45k
            }
1875
1.33M
        }
1876
1877
        /* Minimum of 11 bytes of pre-message data and must have separator. */
1878
6.45k
        if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
1879
12
            WOLFSSL_MSG("RsaUnPad error, bad formatting");
1880
12
            return RSA_PAD_E;
1881
12
        }
1882
1883
6.44k
        *output = (byte *)(pkcsBlock + i);
1884
6.44k
        ret = (int)pkcsBlockLen - i;
1885
6.44k
    }
1886
0
#ifndef WOLFSSL_RSA_VERIFY_ONLY
1887
0
    else {
1888
0
        unsigned int    j;
1889
0
        volatile word16 pastSep = 0;
1890
0
        volatile byte   invalid = 0;
1891
0
        volatile byte   minPad;
1892
0
        volatile int    invalidMask;
1893
0
        byte inv;
1894
0
        word16 sep;
1895
1896
0
        i = 0;
1897
        /* Decrypted with private key - unpad must be constant time. */
1898
0
        for (j = 2; j < pkcsBlockLen; j++) {
1899
           /* Update i if not passed the separator and at separator. */
1900
0
            i |= (word16)(~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) &
1901
0
                (word16)(j + 1);
1902
0
            pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
1903
0
        }
1904
1905
        /* Snapshot volatiles to avoid multiple volatile accesses per
1906
         * expression. */
1907
0
        inv = invalid;
1908
0
        sep = pastSep;
1909
1910
        /* Minimum of 11 bytes of pre-message data - including leading 0x00. */
1911
0
        minPad = ctMaskLT(i, RSA_MIN_PAD_SZ);
1912
0
        inv |= minPad;
1913
        /* Must have seen separator. */
1914
0
        inv |= (byte)~sep;
1915
        /* First byte must be 0x00. */
1916
0
        inv |= ctMaskNotEq(pkcsBlock[0], 0x00);
1917
        /* Check against expected block type: padValue */
1918
0
        inv |= ctMaskNotEq(pkcsBlock[1], padValue);
1919
1920
0
        invalid = inv;
1921
0
        *output = (byte *)(pkcsBlock + i);
1922
0
        invalidMask = (int)-1 + (int)(inv >> 7);
1923
0
        ret = invalidMask & ((int)pkcsBlockLen - i);
1924
0
    }
1925
6.44k
#endif
1926
1927
6.44k
    return ret;
1928
7.03k
}
1929
1930
/* helper function to direct unpadding
1931
 *
1932
 * bits is the key modulus size in bits
1933
 */
1934
int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
1935
                   byte padValue, int padType, enum wc_HashType hType,
1936
                   int mgf, byte* optLabel, word32 labelLen, int saltLen,
1937
                   int bits, void* heap)
1938
7.83k
{
1939
7.83k
    int ret;
1940
1941
7.83k
    switch (padType) {
1942
6.80k
        case WC_RSA_PKCSV15_PAD:
1943
            /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
1944
6.80k
            ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue);
1945
6.80k
            break;
1946
1947
0
    #ifndef WC_NO_RSA_OAEP
1948
0
        case WC_RSA_OAEP_PAD:
1949
0
            WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
1950
0
            ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
1951
0
                                        hType, mgf, optLabel, labelLen, heap);
1952
0
            break;
1953
0
    #endif
1954
1955
0
    #ifdef WC_RSA_PSS
1956
1.03k
        case WC_RSA_PSS_PAD:
1957
1.03k
            WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
1958
1.03k
            ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
1959
1.03k
                                                           saltLen, bits, heap);
1960
1.03k
            break;
1961
0
    #endif
1962
1963
0
    #ifdef WC_RSA_NO_PADDING
1964
0
        case WC_RSA_NO_PAD:
1965
0
            WOLFSSL_MSG("wolfSSL Using NO un-padding");
1966
1967
            /* In the case of no padding being used check that input is exactly
1968
             * the RSA key length */
1969
0
            if (bits <= 0 || pkcsBlockLen !=
1970
0
                         ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
1971
0
                WOLFSSL_MSG("Bad input size");
1972
0
                ret = RSA_PAD_E;
1973
0
            }
1974
0
            else {
1975
0
                if (out != NULL) {
1976
0
                    *out = pkcsBlock;
1977
0
                }
1978
0
                ret = (int)pkcsBlockLen;
1979
0
            }
1980
0
            break;
1981
0
    #endif /* WC_RSA_NO_PADDING */
1982
1983
0
        default:
1984
0
            WOLFSSL_MSG("Unknown RSA UnPad Type");
1985
0
            ret = RSA_PAD_E;
1986
7.83k
    }
1987
1988
    /* silence warning if not used with padding scheme */
1989
7.83k
    (void)hType;
1990
7.83k
    (void)mgf;
1991
7.83k
    (void)optLabel;
1992
7.83k
    (void)labelLen;
1993
7.83k
    (void)saltLen;
1994
7.83k
    (void)bits;
1995
7.83k
    (void)heap;
1996
1997
7.83k
    return ret;
1998
7.83k
}
1999
2000
int wc_hash2mgf(enum wc_HashType hType)
2001
351
{
2002
351
    switch (hType) {
2003
351
    case WC_HASH_TYPE_NONE:
2004
351
        return WC_MGF1NONE;
2005
0
    case WC_HASH_TYPE_SHA:
2006
0
#ifndef NO_SHA
2007
0
        return WC_MGF1SHA1;
2008
#else
2009
        break;
2010
#endif
2011
0
    case WC_HASH_TYPE_SHA224:
2012
0
#ifdef WOLFSSL_SHA224
2013
0
        return WC_MGF1SHA224;
2014
#else
2015
        break;
2016
#endif
2017
0
    case WC_HASH_TYPE_SHA256:
2018
0
#ifndef NO_SHA256
2019
0
        return WC_MGF1SHA256;
2020
#else
2021
        break;
2022
#endif
2023
0
    case WC_HASH_TYPE_SHA384:
2024
0
#ifdef WOLFSSL_SHA384
2025
0
        return WC_MGF1SHA384;
2026
#else
2027
        break;
2028
#endif
2029
0
    case WC_HASH_TYPE_SHA512:
2030
0
#ifdef WOLFSSL_SHA512
2031
0
        return WC_MGF1SHA512;
2032
#else
2033
        break;
2034
#endif
2035
0
    case WC_HASH_TYPE_MD2:
2036
0
    case WC_HASH_TYPE_MD4:
2037
0
    case WC_HASH_TYPE_MD5:
2038
0
    case WC_HASH_TYPE_MD5_SHA:
2039
0
    case WC_HASH_TYPE_SHA512_224:
2040
0
    case WC_HASH_TYPE_SHA512_256:
2041
0
    case WC_HASH_TYPE_SHA3_224:
2042
0
    case WC_HASH_TYPE_SHA3_256:
2043
0
    case WC_HASH_TYPE_SHA3_384:
2044
0
    case WC_HASH_TYPE_SHA3_512:
2045
0
    case WC_HASH_TYPE_BLAKE2B:
2046
0
    case WC_HASH_TYPE_BLAKE2S:
2047
0
    case WC_HASH_TYPE_SM3:
2048
0
    case WC_HASH_TYPE_SHAKE128:
2049
0
    case WC_HASH_TYPE_SHAKE256:
2050
0
    default:
2051
0
        break;
2052
351
    }
2053
0
    WOLFSSL_MSG("Unrecognized or unsupported hash function");
2054
0
    return WC_MGF1NONE;
2055
351
}
2056
2057
#ifdef WC_RSA_NONBLOCK
2058
static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
2059
                          word32* outLen, int type, RsaKey* key)
2060
{
2061
    int    ret = 0;
2062
    word32 keyLen, len;
2063
2064
    if (key == NULL || key->nb == NULL) {
2065
        return BAD_FUNC_ARG;
2066
    }
2067
2068
    if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
2069
        if (mp_init(&key->nb->tmp) != MP_OKAY) {
2070
            ret = MP_INIT_E;
2071
        }
2072
2073
        if (ret == 0) {
2074
            if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
2075
                ret = MP_READ_E;
2076
            }
2077
        }
2078
    }
2079
2080
    if (ret == 0) {
2081
        switch(type) {
2082
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
2083
        case RSA_PRIVATE_DECRYPT:
2084
        case RSA_PRIVATE_ENCRYPT:
2085
            ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
2086
                &key->n, &key->nb->tmp);
2087
            if (ret == FP_WOULDBLOCK)
2088
                return ret;
2089
            if (ret != MP_OKAY)
2090
                ret = MP_EXPTMOD_E;
2091
            break;
2092
#endif
2093
        case RSA_PUBLIC_ENCRYPT:
2094
        case RSA_PUBLIC_DECRYPT:
2095
            ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
2096
                &key->n, &key->nb->tmp);
2097
            if (ret == FP_WOULDBLOCK)
2098
                return ret;
2099
            if (ret != MP_OKAY)
2100
                ret = MP_EXPTMOD_E;
2101
            break;
2102
        default:
2103
            ret = RSA_WRONG_TYPE_E;
2104
            break;
2105
        }
2106
    }
2107
2108
    if (ret == 0) {
2109
        keyLen = wc_RsaEncryptSize(key);
2110
        if (keyLen > *outLen)
2111
            ret = RSA_BUFFER_E;
2112
    }
2113
    if (ret == 0) {
2114
        len = mp_unsigned_bin_size(&key->nb->tmp);
2115
2116
        /* pad front w/ zeros to match key length */
2117
        while (len < keyLen) {
2118
            *out++ = 0x00;
2119
            len++;
2120
        }
2121
2122
        *outLen = keyLen;
2123
2124
        /* convert */
2125
        if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
2126
             ret = MP_TO_E;
2127
        }
2128
    }
2129
2130
    mp_clear(&key->nb->tmp);
2131
2132
    return ret;
2133
}
2134
#endif /* WC_RSA_NONBLOCK */
2135
2136
#ifdef WOLFSSL_XILINX_CRYPT
2137
/*
2138
 * Xilinx hardened crypto acceleration.
2139
 *
2140
 * Returns 0 on success and negative values on error.
2141
 */
2142
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2143
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2144
{
2145
    int    ret = 0;
2146
    word32 keyLen;
2147
    (void)rng;
2148
2149
    keyLen = wc_RsaEncryptSize(key);
2150
    if (keyLen > *outLen) {
2151
        WOLFSSL_MSG("Output buffer is not big enough");
2152
        return BAD_FUNC_ARG;
2153
    }
2154
2155
    if (inLen != keyLen) {
2156
        WOLFSSL_MSG("Expected that inLen equals RSA key length");
2157
        return BAD_FUNC_ARG;
2158
    }
2159
2160
    switch(type) {
2161
    case RSA_PRIVATE_DECRYPT:
2162
    case RSA_PRIVATE_ENCRYPT:
2163
    #ifdef WOLFSSL_XILINX_CRYPTO_OLD
2164
        /* Currently public exponent is loaded by default.
2165
         * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
2166
         * leading to private key operations with Xsecure_RsaDecrypt not being
2167
         * supported */
2168
        ret = RSA_WRONG_TYPE_E;
2169
    #else
2170
        {
2171
            byte *d;
2172
            int dSz;
2173
#if !defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2174
            XSecure_Rsa rsa;
2175
#endif
2176
2177
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2178
            dSz = WOLFSSL_XSECURE_RSA_KEY_SIZE * 2;
2179
#else
2180
            dSz = mp_unsigned_bin_size(&key->d);
2181
#endif
2182
            d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
2183
            if (d == NULL) {
2184
                ret = MEMORY_E;
2185
            } else {
2186
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2187
                XMEMSET(d, 0, dSz);
2188
                XMEMCPY(d, key->mod, key->mSz);
2189
                ret = mp_to_unsigned_bin(&key->d, &d[WOLFSSL_XSECURE_RSA_KEY_SIZE]);
2190
#else
2191
                ret = mp_to_unsigned_bin(&key->d, d);
2192
                XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
2193
#endif
2194
            }
2195
2196
            if (ret == 0) {
2197
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2198
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)d, dSz);
2199
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)in, inLen);
2200
                if (XSecure_RsaPrivateDecrypt(&(key->xSec.cinst), XIL_CAST_U64(d),
2201
                                              XIL_CAST_U64(in), inLen,
2202
                                              XIL_CAST_U64(out)) != XST_SUCCESS) {
2203
                    ret = BAD_STATE_E;
2204
                }
2205
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)out, inLen);
2206
#else
2207
                if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
2208
                        XST_SUCCESS) {
2209
                    ret = BAD_STATE_E;
2210
                }
2211
#endif
2212
            }
2213
2214
            XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
2215
        }
2216
    #endif
2217
        break;
2218
    case RSA_PUBLIC_ENCRYPT:
2219
    case RSA_PUBLIC_DECRYPT:
2220
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2221
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)key->mod,
2222
                                       WOLFSSL_XSECURE_RSA_KEY_SIZE + 4);
2223
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)in, inLen);
2224
        if (XSecure_RsaPublicEncrypt(&(key->xSec.cinst),
2225
                                     XIL_CAST_U64(key->mod),
2226
                                     XIL_CAST_U64(in), inLen,
2227
                                     XIL_CAST_U64(out))) {
2228
            WOLFSSL_MSG("RSA public operation failed");
2229
            ret = BAD_STATE_E;
2230
        }
2231
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)out, inLen);
2232
#elif defined(WOLFSSL_XILINX_CRYPTO_OLD)
2233
        if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
2234
            ret = BAD_STATE_E;
2235
        }
2236
#else
2237
        /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
2238
        if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
2239
            WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
2240
            ret = BAD_STATE_E;
2241
        }
2242
#endif
2243
        break;
2244
    default:
2245
        ret = RSA_WRONG_TYPE_E;
2246
    }
2247
2248
    *outLen = keyLen;
2249
2250
    return ret;
2251
}
2252
2253
#elif defined(WOLFSSL_AFALG_XILINX_RSA)
2254
#ifndef ERROR_OUT
2255
#define ERROR_OUT(x) ret = (x); goto done
2256
#endif
2257
2258
static const char WC_TYPE_ASYMKEY[] = "skcipher";
2259
static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
2260
#ifndef MAX_XILINX_RSA_KEY
2261
    /* max key size of 4096 bits / 512 bytes */
2262
    #define MAX_XILINX_RSA_KEY 512
2263
#endif
2264
static const byte XILINX_RSA_FLAG[] = {0x1};
2265
2266
2267
/* AF_ALG implementation of RSA */
2268
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2269
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2270
{
2271
    struct msghdr   msg;
2272
    struct cmsghdr* cmsg;
2273
    struct iovec      iov;
2274
    byte*  keyBuf   = NULL;
2275
    word32 keyBufSz = 0;
2276
    char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
2277
    int    ret = 0;
2278
    int    op  = 0;    /* decryption vs encryption flag */
2279
    word32 keyLen;
2280
2281
    /* input and output buffer need to be aligned */
2282
    ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
2283
    ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
2284
2285
    XMEMSET(&msg, 0, sizeof(struct msghdr));
2286
    (void)rng;
2287
2288
    keyLen = wc_RsaEncryptSize(key);
2289
    if (keyLen > *outLen) {
2290
        ERROR_OUT(RSA_BUFFER_E);
2291
    }
2292
2293
    if (keyLen > MAX_XILINX_RSA_KEY) {
2294
        WOLFSSL_MSG("RSA key size larger than supported");
2295
        ERROR_OUT(BAD_FUNC_ARG);
2296
    }
2297
2298
    if (inLen != keyLen) {
2299
        WOLFSSL_MSG("Expected that inLen equals RSA key length");
2300
        ERROR_OUT(BAD_FUNC_ARG);
2301
    }
2302
2303
    if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
2304
            == NULL) {
2305
        ERROR_OUT(MEMORY_E);
2306
    }
2307
2308
    if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
2309
        ERROR_OUT(MP_TO_E);
2310
    }
2311
2312
    switch(type) {
2313
        case RSA_PRIVATE_DECRYPT:
2314
        case RSA_PRIVATE_ENCRYPT:
2315
            op = 1; /* set as decrypt */
2316
            {
2317
                keyBufSz = mp_unsigned_bin_size(&(key->d));
2318
                if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
2319
                        != MP_OKAY) {
2320
                    ERROR_OUT(MP_TO_E);
2321
                }
2322
            #ifdef WOLFSSL_CHECK_MEM_ZERO
2323
                /* Seed must be zeroized now that it has been used. */
2324
                wc_MemZero_Add("RSA Sync Priv Enc/Dec keyBuf", keyBuf + keyLen,
2325
                    keyBufSz);
2326
            #endif
2327
            }
2328
            break;
2329
2330
        case RSA_PUBLIC_DECRYPT:
2331
        case RSA_PUBLIC_ENCRYPT: {
2332
            word32 exp = 0;
2333
            word32 eSz = mp_unsigned_bin_size(&(key->e));
2334
            if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
2335
                            (sizeof(word32) - eSz))) != MP_OKAY) {
2336
                ERROR_OUT(MP_TO_E);
2337
            }
2338
            keyBufSz = sizeof(word32);
2339
            XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
2340
            break;
2341
        }
2342
2343
        default:
2344
            ERROR_OUT(RSA_WRONG_TYPE_E);
2345
    }
2346
    keyBufSz += keyLen; /* add size of modulus */
2347
2348
    /* check for existing sockets before creating new ones */
2349
    if (key->alFd > 0) {
2350
        close(key->alFd);
2351
        key->alFd = WC_SOCK_NOTSET;
2352
    }
2353
    if (key->rdFd > 0) {
2354
        close(key->rdFd);
2355
        key->rdFd = WC_SOCK_NOTSET;
2356
    }
2357
2358
    /* create new sockets and set the key to use */
2359
    if ((key->alFd = wc_Afalg_Socket()) < 0) {
2360
        WOLFSSL_MSG("Unable to create socket");
2361
        ERROR_OUT(key->alFd);
2362
    }
2363
    if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
2364
                    WC_NAME_RSA)) < 0) {
2365
        WOLFSSL_MSG("Unable to bind and create read/send socket");
2366
        ERROR_OUT(key->rdFd);
2367
    }
2368
    if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
2369
                    keyBufSz)) < 0) {
2370
        WOLFSSL_MSG("Error setting RSA key");
2371
        ERROR_OUT(ret);
2372
    }
2373
2374
    msg.msg_control    = cbuf;
2375
    msg.msg_controllen = sizeof(cbuf);
2376
    cmsg = CMSG_FIRSTHDR(&msg);
2377
    if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
2378
        ERROR_OUT(ret);
2379
    }
2380
2381
    /* set flag in IV spot, needed for Xilinx hardware acceleration use */
2382
    cmsg = CMSG_NXTHDR(&msg, cmsg);
2383
    if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
2384
                    sizeof(XILINX_RSA_FLAG))) != 0) {
2385
        ERROR_OUT(ret);
2386
    }
2387
2388
    /* compose and send msg */
2389
    XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
2390
    iov.iov_base = inBuf;
2391
    iov.iov_len  = inLen;
2392
    msg.msg_iov  = &iov;
2393
    msg.msg_iovlen = 1;
2394
    if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
2395
        ERROR_OUT(WC_AFALG_SOCK_E);
2396
    }
2397
2398
    if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
2399
        ERROR_OUT(WC_AFALG_SOCK_E);
2400
    }
2401
    XMEMCPY(out, outBuf, ret);
2402
    *outLen = keyLen;
2403
2404
done:
2405
    /* clear key data and free buffer */
2406
    if (keyBuf != NULL) {
2407
        ForceZero(keyBuf, keyBufSz);
2408
    }
2409
    XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
2410
2411
    if (key->alFd > 0) {
2412
        close(key->alFd);
2413
        key->alFd = WC_SOCK_NOTSET;
2414
    }
2415
    if (key->rdFd > 0) {
2416
        close(key->rdFd);
2417
        key->rdFd = WC_SOCK_NOTSET;
2418
    }
2419
2420
    return ret;
2421
}
2422
2423
#elif defined(WOLFSSL_KCAPI_RSA)
2424
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2425
                              word32* outLen, int type, RsaKey* key,
2426
                              WC_RNG* rng)
2427
{
2428
    int ret;
2429
2430
    (void)rng;
2431
2432
    switch(type) {
2433
        case RSA_PRIVATE_DECRYPT:
2434
        case RSA_PRIVATE_ENCRYPT:
2435
            ret = KcapiRsa_Decrypt(key, in, inLen, out, outLen);
2436
            break;
2437
2438
        case RSA_PUBLIC_DECRYPT:
2439
        case RSA_PUBLIC_ENCRYPT:
2440
            ret = KcapiRsa_Encrypt(key, in, inLen, out, outLen);
2441
            break;
2442
2443
        default:
2444
            ret = RSA_WRONG_TYPE_E;
2445
    }
2446
2447
    return ret;
2448
}
2449
#else
2450
#ifndef WOLF_CRYPTO_CB_ONLY_RSA
2451
#ifdef WOLFSSL_HAVE_SP_RSA
2452
static int RsaFunction_SP(const byte* in, word32 inLen, byte* out,
2453
    word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2454
{
2455
    (void)rng;
2456
2457
#ifndef WOLFSSL_SP_NO_2048
2458
    if (mp_count_bits(&key->n) == 2048) {
2459
        switch(type) {
2460
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2461
        case RSA_PRIVATE_DECRYPT:
2462
        case RSA_PRIVATE_ENCRYPT:
2463
    #ifdef WC_RSA_BLINDING
2464
            if (rng == NULL)
2465
                return MISSING_RNG_E;
2466
    #endif
2467
    #ifndef RSA_LOW_MEM
2468
            if ((mp_count_bits(&key->p) == 1024) &&
2469
                    (mp_count_bits(&key->q) == 1024) &&
2470
                    (mp_count_bits(&key->dP) > 0) &&
2471
                    (mp_count_bits(&key->dQ) > 0) &&
2472
                    (mp_count_bits(&key->u) > 0)) {
2473
                return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
2474
                                          &key->dP, &key->dQ, &key->u, &key->n,
2475
                                          out, outLen);
2476
            }
2477
            break;
2478
    #else
2479
            return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
2480
                                      NULL, NULL, &key->n, out, outLen);
2481
    #endif
2482
#endif
2483
        case RSA_PUBLIC_ENCRYPT:
2484
        case RSA_PUBLIC_DECRYPT:
2485
            return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
2486
        default:
2487
            break;
2488
        }
2489
    }
2490
#endif
2491
#ifndef WOLFSSL_SP_NO_3072
2492
    if (mp_count_bits(&key->n) == 3072) {
2493
        switch(type) {
2494
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2495
        case RSA_PRIVATE_DECRYPT:
2496
        case RSA_PRIVATE_ENCRYPT:
2497
    #ifdef WC_RSA_BLINDING
2498
            if (rng == NULL)
2499
                return MISSING_RNG_E;
2500
    #endif
2501
    #ifndef RSA_LOW_MEM
2502
            if ((mp_count_bits(&key->p) == 1536) &&
2503
                    (mp_count_bits(&key->q) == 1536) &&
2504
                    (mp_count_bits(&key->dP) > 0) &&
2505
                    (mp_count_bits(&key->dQ) > 0) &&
2506
                    (mp_count_bits(&key->u) > 0)) {
2507
                return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
2508
                                          &key->dP, &key->dQ, &key->u, &key->n,
2509
                                          out, outLen);
2510
            }
2511
            break;
2512
    #else
2513
            return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
2514
                                      NULL, NULL, &key->n, out, outLen);
2515
    #endif
2516
#endif
2517
        case RSA_PUBLIC_ENCRYPT:
2518
        case RSA_PUBLIC_DECRYPT:
2519
            return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
2520
        default:
2521
            break;
2522
        }
2523
    }
2524
#endif
2525
#ifdef WOLFSSL_SP_4096
2526
    if (mp_count_bits(&key->n) == 4096) {
2527
        switch(type) {
2528
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2529
        case RSA_PRIVATE_DECRYPT:
2530
        case RSA_PRIVATE_ENCRYPT:
2531
    #ifdef WC_RSA_BLINDING
2532
            if (rng == NULL)
2533
                return MISSING_RNG_E;
2534
    #endif
2535
    #ifndef RSA_LOW_MEM
2536
            if ((mp_count_bits(&key->p) == 2048) &&
2537
                    (mp_count_bits(&key->q) == 2048) &&
2538
                    (mp_count_bits(&key->dP) > 0) &&
2539
                    (mp_count_bits(&key->dQ) > 0) &&
2540
                    (mp_count_bits(&key->u) > 0)) {
2541
                return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
2542
                                          &key->dP, &key->dQ, &key->u, &key->n,
2543
                                          out, outLen);
2544
            }
2545
            break;
2546
    #else
2547
            return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
2548
                                      NULL, NULL, &key->n, out, outLen);
2549
    #endif
2550
#endif
2551
        case RSA_PUBLIC_ENCRYPT:
2552
        case RSA_PUBLIC_DECRYPT:
2553
            return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
2554
        default:
2555
            break;
2556
        }
2557
    }
2558
#endif
2559
2560
    /* SP not able to do operation. */
2561
    return WC_KEY_SIZE_E;
2562
}
2563
#endif
2564
2565
#if !defined(WOLFSSL_SP_MATH)
2566
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
2567
static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
2568
10.0k
{
2569
10.0k
    int    ret = 0;
2570
10.0k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2571
10.0k
    mp_digit mp = 0;
2572
10.0k
    DECL_MP_INT_SIZE_DYN(rnd, mp_bitsused(&key->n), RSA_MAX_SIZE);
2573
10.0k
    DECL_MP_INT_SIZE_DYN(rndi, mp_bitsused(&key->n), RSA_MAX_SIZE);
2574
10.0k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
2575
2576
10.0k
    (void)rng;
2577
2578
10.0k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2579
10.0k
    NEW_MP_INT_SIZE(rnd, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
2580
10.0k
    NEW_MP_INT_SIZE(rndi, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
2581
10.0k
#ifdef MP_INT_SIZE_CHECK_NULL
2582
10.0k
    if ((rnd == NULL) || (rndi == NULL)) {
2583
37
        FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA);
2584
37
        FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA);
2585
37
        return MEMORY_E;
2586
37
    }
2587
9.98k
#endif
2588
2589
9.98k
    if ((INIT_MP_INT_SIZE(rnd, mp_bitsused(&key->n)) != MP_OKAY) ||
2590
9.98k
            (INIT_MP_INT_SIZE(rndi, mp_bitsused(&key->n)) != MP_OKAY)) {
2591
0
        ret = MP_INIT_E;
2592
0
    }
2593
2594
9.98k
    if (ret == 0) {
2595
        /* blind */
2596
9.98k
        ret = mp_rand(rnd, mp_get_digit_count(&key->n), rng);
2597
9.98k
    }
2598
9.98k
    if (ret == 0) {
2599
        /* rndi = 1/rnd mod n */
2600
9.90k
        if (mp_invmod(rnd, &key->n, rndi) != MP_OKAY) {
2601
860
            ret = MP_INVMOD_E;
2602
860
        }
2603
9.90k
    }
2604
9.98k
    if (ret == 0) {
2605
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2606
        mp_memzero_add("RSA Private rnd", rnd);
2607
        mp_memzero_add("RSA Private rndi", rndi);
2608
    #endif
2609
2610
        /* rnd = rnd^e */
2611
    #ifndef WOLFSSL_SP_MATH_ALL
2612
        if (mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) {
2613
            ret = MP_EXPTMOD_E;
2614
        }
2615
    #else
2616
9.04k
        if (mp_exptmod_nct(rnd, &key->e, &key->n, rnd) != MP_OKAY) {
2617
31
            ret = MP_EXPTMOD_E;
2618
31
        }
2619
9.04k
    #endif
2620
9.04k
    }
2621
2622
9.98k
    if (ret == 0) {
2623
        /* tmp = tmp*rnd mod n */
2624
9.01k
        if (mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) {
2625
3
            ret = MP_MULMOD_E;
2626
3
        }
2627
9.01k
    }
2628
9.98k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
2629
2630
#ifdef RSA_LOW_MEM      /* half as much memory but twice as slow */
2631
    if (ret == 0) {
2632
        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) {
2633
            ret = MP_EXPTMOD_E;
2634
        }
2635
    }
2636
#else
2637
9.98k
    if (ret == 0 && (mp_iszero(&key->p) || mp_iszero(&key->q) ||
2638
9.00k
            mp_iszero(&key->dP) || mp_iszero(&key->dQ) || mp_iszero(&key->u))) {
2639
1.50k
        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) {
2640
9
            ret = MP_EXPTMOD_E;
2641
9
        }
2642
1.50k
    }
2643
8.47k
    else if (ret == 0) {
2644
7.49k
        mp_int* tmpa = tmp;
2645
7.49k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2646
7.49k
        mp_int* tmpb = rnd;
2647
#else
2648
        DECL_MP_INT_SIZE_DYN(tmpb, mp_bitsused(&key->n), RSA_MAX_SIZE);
2649
#endif
2650
2651
#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG)
2652
        NEW_MP_INT_SIZE(tmpb, mp_bitsused(&key->n), key->heap,
2653
            DYNAMIC_TYPE_RSA);
2654
    #ifdef MP_INT_SIZE_CHECK_NULL
2655
        if (tmpb == NULL) {
2656
            ret = MEMORY_E;
2657
        }
2658
    #endif
2659
        if ((ret == 0) && INIT_MP_INT_SIZE(tmpb, mp_bitsused(&key->n)) !=
2660
                MP_OKAY) {
2661
            ret = MP_INIT_E;
2662
        }
2663
#endif
2664
2665
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2666
        if (ret == 0) {
2667
            mp_memzero_add("RSA Sync tmpb", tmpb);
2668
        }
2669
    #endif
2670
2671
        /* tmpb = tmp^dQ mod q */
2672
7.49k
        if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, tmpb) != MP_OKAY)
2673
102
            ret = MP_EXPTMOD_E;
2674
2675
        /* tmpa = tmp^dP mod p */
2676
7.49k
        if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, tmpa) != MP_OKAY)
2677
75
            ret = MP_EXPTMOD_E;
2678
2679
        /* tmp = (tmp - tmpb) * qInv (mod p) */
2680
    #if (defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL)) && \
2681
                                              !defined(WOLFSSL_SP_INT_NEGATIVE))
2682
        if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY)
2683
            ret = MP_SUB_E;
2684
    #else
2685
7.49k
        if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
2686
0
            ret = MP_SUB_E;
2687
7.49k
    #endif
2688
2689
7.49k
        if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, tmp) != MP_OKAY)
2690
1
            ret = MP_MULMOD_E;
2691
2692
        /* tmp = tmpb + q * tmp */
2693
7.49k
        if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
2694
1
            ret = MP_MUL_E;
2695
2696
7.49k
        if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
2697
0
            ret = MP_ADD_E;
2698
2699
#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG)
2700
        mp_forcezero(tmpb);
2701
        FREE_MP_INT_SIZE(tmpb, key->heap, DYNAMIC_TYPE_RSA);
2702
    #if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
2703
        mp_memzero_check(tmpb);
2704
    #endif
2705
#endif
2706
7.49k
    }
2707
9.98k
#endif   /* RSA_LOW_MEM */
2708
2709
9.98k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2710
    /* Multiply result (tmp) by blinding invertor (rndi).
2711
     * Use Montgomery form to make operation more constant time.
2712
     */
2713
9.98k
    if ((ret == 0) && (mp_montgomery_setup(&key->n, &mp) != MP_OKAY)) {
2714
0
        ret = MP_MULMOD_E;
2715
0
    }
2716
9.98k
    if ((ret == 0) && (mp_montgomery_calc_normalization(rnd, &key->n) !=
2717
8.81k
            MP_OKAY)) {
2718
0
        ret = MP_MULMOD_E;
2719
0
    }
2720
    /* Convert blinding invert to Montgomery form. */
2721
9.98k
    if ((ret == 0) && (mp_mul(rndi, rnd, rndi) != MP_OKAY)) {
2722
1
        ret = MP_MULMOD_E;
2723
1
    }
2724
9.98k
    if ((ret == 0) && (mp_mod(rndi, &key->n, rndi) != MP_OKAY)) {
2725
2
        ret = MP_MULMOD_E;
2726
2
    }
2727
    /* Multiply result by blinding invert. */
2728
9.98k
    if ((ret == 0) && (mp_mul(tmp, rndi, tmp) != MP_OKAY)) {
2729
1
        ret = MP_MULMOD_E;
2730
1
    }
2731
    /* Reduce result. */
2732
9.98k
    if ((ret == 0) && (mp_montgomery_reduce_ct(tmp, &key->n, mp) != MP_OKAY)) {
2733
0
        ret = MP_MULMOD_E;
2734
0
    }
2735
2736
9.98k
    mp_forcezero(rndi);
2737
9.98k
    mp_forcezero(rnd);
2738
9.98k
    FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA);
2739
9.98k
    FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA);
2740
#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
2741
    mp_memzero_check(rnd);
2742
    mp_memzero_check(rndi);
2743
#endif
2744
9.98k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
2745
9.98k
    return ret;
2746
10.0k
}
2747
#endif
2748
2749
static int RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2750
    word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2751
18.2k
{
2752
18.2k
    DECL_MP_INT_SIZE_DYN(tmp, mp_bitsused(&key->n), RSA_MAX_SIZE);
2753
18.2k
    int    ret = 0;
2754
2755
18.2k
    (void)rng;
2756
2757
18.2k
    NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
2758
18.2k
#ifdef MP_INT_SIZE_CHECK_NULL
2759
18.2k
    if (tmp == NULL) {
2760
17
        WOLFSSL_MSG("NEW_MP_INT_SIZE tmp is NULL, return MEMORY_E");
2761
17
        return MEMORY_E;
2762
17
    }
2763
18.2k
#endif
2764
2765
18.2k
    if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY) {
2766
0
        WOLFSSL_MSG("INIT_MP_INT_SIZE failed.");
2767
0
        ret = MP_INIT_E;
2768
0
    }
2769
2770
18.2k
#ifndef TEST_UNPAD_CONSTANT_TIME
2771
18.2k
    if (ret == 0 && mp_read_unsigned_bin(tmp, in, inLen) != MP_OKAY)
2772
0
        ret = MP_READ_E;
2773
2774
#ifdef WOLFSSL_CHECK_MEM_ZERO
2775
    if (ret == 0) {
2776
        mp_memzero_add("RSA sync tmp", tmp);
2777
    }
2778
#endif
2779
2780
18.2k
    if (ret == 0) {
2781
18.2k
        switch(type) {
2782
0
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
2783
0
        case RSA_PRIVATE_DECRYPT:
2784
10.0k
        case RSA_PRIVATE_ENCRYPT:
2785
10.0k
        {
2786
10.0k
            ret = RsaFunctionPrivate(tmp, key, rng);
2787
10.0k
            break;
2788
0
        }
2789
0
    #endif
2790
374
        case RSA_PUBLIC_ENCRYPT:
2791
8.23k
        case RSA_PUBLIC_DECRYPT:
2792
8.23k
            if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY) {
2793
27
                WOLFSSL_MSG_CERT_LOG("mp_exptmod_nct failed");
2794
27
                ret = MP_EXPTMOD_E;
2795
27
            }
2796
8.23k
            break;
2797
0
        default:
2798
0
            ret = RSA_WRONG_TYPE_E;
2799
0
            break;
2800
18.2k
        }
2801
18.2k
    }
2802
2803
18.2k
    if (ret == 0) {
2804
17.0k
        WOLFSSL_MSG("mp_to_unsigned_bin_len_ct...");
2805
17.0k
        if (mp_to_unsigned_bin_len_ct(tmp, out, (int)*outLen) != MP_OKAY) {
2806
0
            WOLFSSL_MSG("mp_to_unsigned_bin_len_ct failed");
2807
0
            ret = MP_TO_E;
2808
0
        }
2809
17.0k
    }
2810
#ifdef WOLFSSL_RSA_CHECK_D_ON_DECRYPT
2811
    if ((ret == 0) && (type == RSA_PRIVATE_DECRYPT)) {
2812
        mp_sub(&key->n, &key->p, tmp);
2813
        mp_sub(tmp, &key->q, tmp);
2814
        mp_add_d(tmp, 1, tmp);
2815
        mp_mulmod(&key->d, &key->e, tmp, tmp);
2816
        if (!mp_isone(tmp)) {
2817
            ret = MP_EXPTMOD_E;
2818
        }
2819
    }
2820
#endif
2821
#else
2822
    (void)type;
2823
    (void)key;
2824
    XMEMCPY(out, in, inLen);
2825
#endif
2826
2827
18.2k
    mp_forcezero(tmp);
2828
18.2k
    FREE_MP_INT_SIZE(tmp, key->heap, DYNAMIC_TYPE_RSA);
2829
#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
2830
    mp_memzero_check(tmp);
2831
#endif
2832
18.2k
    return ret;
2833
18.2k
}
2834
#endif /* !WOLFSSL_SP_MATH */
2835
2836
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2837
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2838
19.0k
{
2839
19.0k
    int ret;
2840
19.0k
    word32 keyLen;
2841
2842
19.0k
    ret = wc_RsaEncryptSize(key);
2843
19.0k
    if (ret < 0) {
2844
#ifdef DEBUG_WOLFSSL
2845
        WOLFSSL_MSG_EX("wc_RsaEncryptSize failed err = %d", ret);
2846
#endif
2847
0
        return ret;
2848
0
    }
2849
19.0k
    keyLen = (word32)ret;
2850
2851
19.0k
    if (inLen > keyLen) {
2852
6
        WOLFSSL_MSG("Expected that inLen be no longer RSA key length");
2853
6
        return BAD_FUNC_ARG;
2854
6
    }
2855
18.9k
    if (keyLen > *outLen) {
2856
405
        WOLFSSL_MSG("Expected that outLen be no shorter RSA key length");
2857
405
        return RSA_BUFFER_E;
2858
405
    }
2859
2860
18.5k
    if (mp_iseven(&key->n)) {
2861
57
        WOLFSSL_MSG("MP_VAL is even");
2862
57
        return MP_VAL;
2863
57
    }
2864
2865
#ifdef WOLFSSL_HAVE_SP_RSA
2866
    ret = RsaFunction_SP(in, inLen, out, outLen, type, key, rng);
2867
    if (ret != WC_NO_ERR_TRACE(WC_KEY_SIZE_E))
2868
        return ret;
2869
#endif /* WOLFSSL_HAVE_SP_RSA */
2870
2871
#if defined(WOLFSSL_SP_MATH)
2872
    (void)rng;
2873
#ifndef WOLFSSL_HAVE_SP_RSA
2874
    (void)in;
2875
    (void)inLen;
2876
    (void)out;
2877
    (void)outLen;
2878
    (void)type;
2879
    (void)key;
2880
    #error RSA SP option invalid (enable WOLFSSL_HAVE_SP_RSA or disable WOLFSSL_SP_MATH)
2881
    return NOT_COMPILED_IN;
2882
#else
2883
    WOLFSSL_MSG("SP Key Size Error");
2884
    return WC_KEY_SIZE_E;
2885
#endif
2886
#else
2887
18.5k
    *outLen = keyLen;
2888
18.5k
    return RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2889
18.5k
#endif /* WOLFSSL_SP_MATH */
2890
18.5k
} /* wc_RsaFunctionSync */
2891
#endif /* WOLF_CRYPTO_CB_ONLY_RSA */
2892
#endif
2893
2894
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
2895
static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
2896
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2897
{
2898
    int ret = 0;
2899
2900
    (void)rng;
2901
2902
#ifdef WOLFSSL_ASYNC_CRYPT_SW
2903
    if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_RSA_FUNC)) {
2904
        WC_ASYNC_SW* sw = &key->asyncDev.sw;
2905
        sw->rsaFunc.in = in;
2906
        sw->rsaFunc.inSz = inLen;
2907
        sw->rsaFunc.out = out;
2908
        sw->rsaFunc.outSz = outLen;
2909
        sw->rsaFunc.type = type;
2910
        sw->rsaFunc.key = key;
2911
        sw->rsaFunc.rng = rng;
2912
        return WC_PENDING_E;
2913
    }
2914
#endif /* WOLFSSL_ASYNC_CRYPT_SW */
2915
2916
    switch (type) {
2917
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2918
    case RSA_PRIVATE_DECRYPT:
2919
    case RSA_PRIVATE_ENCRYPT:
2920
    #ifdef HAVE_CAVIUM
2921
        key->dataLen = key->n.raw.len;
2922
        ret = NitroxRsaExptMod(in, inLen,
2923
                               key->d.raw.buf, key->d.raw.len,
2924
                               key->n.raw.buf, key->n.raw.len,
2925
                               out, outLen, key);
2926
    #elif defined(HAVE_INTEL_QA)
2927
        #ifdef RSA_LOW_MEM
2928
            ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
2929
                                    &key->d.raw, &key->n.raw,
2930
                                    out, outLen);
2931
        #else
2932
            ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
2933
                                &key->p.raw, &key->q.raw,
2934
                                &key->dP.raw, &key->dQ.raw,
2935
                                &key->u.raw,
2936
                                out, outLen);
2937
        #endif
2938
    #else
2939
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2940
    #endif
2941
        break;
2942
#endif
2943
2944
    case RSA_PUBLIC_ENCRYPT:
2945
    case RSA_PUBLIC_DECRYPT:
2946
    #ifdef HAVE_CAVIUM
2947
        key->dataLen = key->n.raw.len;
2948
        ret = NitroxRsaExptMod(in, inLen,
2949
                               key->e.raw.buf, key->e.raw.len,
2950
                               key->n.raw.buf, key->n.raw.len,
2951
                               out, outLen, key);
2952
    #elif defined(HAVE_INTEL_QA)
2953
        ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
2954
                               &key->e.raw, &key->n.raw,
2955
                               out, outLen);
2956
    #else
2957
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
2958
    #endif
2959
        break;
2960
2961
    default:
2962
        ret = RSA_WRONG_TYPE_E;
2963
    }
2964
2965
    return ret;
2966
}
2967
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
2968
2969
#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || \
2970
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
2971
/* Performs direct RSA computation without padding. The input and output must
2972
 * match the key size (ex: 2048-bits = 256 bytes). Returns the size of the
2973
 * output on success or negative value on failure. */
2974
int wc_RsaDirect(const byte* in, word32 inLen, byte* out, word32* outSz,
2975
        RsaKey* key, int type, WC_RNG* rng)
2976
0
{
2977
0
    int ret;
2978
2979
0
    if (in == NULL || outSz == NULL || key == NULL) {
2980
0
        return BAD_FUNC_ARG;
2981
0
    }
2982
2983
    /* sanity check on type of RSA operation */
2984
0
    switch (type) {
2985
0
        case RSA_PUBLIC_ENCRYPT:
2986
0
        case RSA_PUBLIC_DECRYPT:
2987
0
        case RSA_PRIVATE_ENCRYPT:
2988
0
        case RSA_PRIVATE_DECRYPT:
2989
0
            break;
2990
0
        default:
2991
0
            WOLFSSL_MSG("Bad RSA type");
2992
0
            return BAD_FUNC_ARG;
2993
0
    }
2994
2995
0
    if ((ret = wc_RsaEncryptSize(key)) < 0) {
2996
0
        return BAD_FUNC_ARG;
2997
0
    }
2998
2999
0
    if (inLen != (word32)ret) {
3000
0
        WOLFSSL_MSG("Bad input length. Should be RSA key size");
3001
0
        return BAD_FUNC_ARG;
3002
0
    }
3003
3004
0
    if (out == NULL) {
3005
0
        *outSz = inLen;
3006
0
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
3007
0
    }
3008
3009
0
    switch (key->state) {
3010
0
        case RSA_STATE_NONE:
3011
0
        case RSA_STATE_ENCRYPT_PAD:
3012
0
        case RSA_STATE_ENCRYPT_EXPTMOD:
3013
0
        case RSA_STATE_DECRYPT_EXPTMOD:
3014
0
        case RSA_STATE_DECRYPT_UNPAD:
3015
0
            key->state = (type == RSA_PRIVATE_ENCRYPT ||
3016
0
                    type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
3017
0
                                                  RSA_STATE_DECRYPT_EXPTMOD;
3018
3019
0
            key->dataLen = *outSz;
3020
3021
0
            ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
3022
0
            if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3023
0
                key->state = (type == RSA_PRIVATE_ENCRYPT ||
3024
0
                    type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
3025
0
                                                  RSA_STATE_DECRYPT_RES;
3026
0
            }
3027
0
            if (ret < 0) {
3028
0
                break;
3029
0
            }
3030
3031
0
            FALL_THROUGH;
3032
3033
0
        case RSA_STATE_ENCRYPT_RES:
3034
0
        case RSA_STATE_DECRYPT_RES:
3035
0
            ret = (int)key->dataLen;
3036
0
            break;
3037
3038
0
        default:
3039
0
            ret = BAD_STATE_E;
3040
0
    }
3041
3042
    /* if async pending then skip cleanup*/
3043
0
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
3044
    #ifdef WC_RSA_NONBLOCK
3045
        || ret == FP_WOULDBLOCK
3046
    #endif
3047
0
    ) {
3048
0
        return ret;
3049
0
    }
3050
3051
0
    key->state = RSA_STATE_NONE;
3052
0
    wc_RsaCleanup(key);
3053
3054
0
    return ret;
3055
0
}
3056
#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING || OPENSSL_EXTRA || \
3057
        * OPENSSL_EXTRA_X509_SMALL */
3058
3059
#if defined(WOLFSSL_CRYPTOCELL)
3060
static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
3061
                            word32 outLen, RsaKey* key)
3062
{
3063
    CRYSError_t ret = 0;
3064
    CRYS_RSAPrimeData_t primeData;
3065
    int modulusSize = wc_RsaEncryptSize(key);
3066
3067
    /* The out buffer must be at least modulus size bytes long. */
3068
    if (outLen < modulusSize)
3069
        return BAD_FUNC_ARG;
3070
3071
    ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState,
3072
                                    wc_rndGenVectFunc,
3073
                                    &key->ctx.pubKey,
3074
                                    &primeData,
3075
                                    (byte*)in,
3076
                                    inLen,
3077
                                    out);
3078
3079
    if (ret != SA_SILIB_RET_OK){
3080
        WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed");
3081
        return -1;
3082
    }
3083
3084
    return modulusSize;
3085
}
3086
static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out,
3087
                            word32 outLen, RsaKey* key)
3088
{
3089
    CRYSError_t ret = 0;
3090
    CRYS_RSAPrimeData_t primeData;
3091
    word16 actualOutLen = outLen;
3092
3093
    ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
3094
                                    &primeData,
3095
                                    (byte*)in,
3096
                                    inLen,
3097
                                    out,
3098
                                    &actualOutLen);
3099
3100
    if (ret != SA_SILIB_RET_OK){
3101
        WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed");
3102
        return -1;
3103
    }
3104
    return actualOutLen;
3105
}
3106
3107
int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
3108
                  word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
3109
{
3110
    CRYSError_t ret = 0;
3111
    word16 actualOutLen = outLen*sizeof(byte);
3112
    CRYS_RSAPrivUserContext_t  contextPrivate;
3113
3114
    ret =  CRYS_RSA_PKCS1v15_Sign(&wc_rndState,
3115
                wc_rndGenVectFunc,
3116
                &contextPrivate,
3117
                &key->ctx.privKey,
3118
                mode,
3119
                (byte*)in,
3120
                inLen,
3121
                out,
3122
                &actualOutLen);
3123
3124
    if (ret != SA_SILIB_RET_OK){
3125
        WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed");
3126
        return -1;
3127
    }
3128
    return actualOutLen;
3129
}
3130
3131
int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig,
3132
                               RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
3133
{
3134
    CRYSError_t ret = 0;
3135
    CRYS_RSAPubUserContext_t contextPub;
3136
3137
    /* verify the signature in the sig pointer */
3138
    ret =  CRYS_RSA_PKCS1v15_Verify(&contextPub,
3139
                &key->ctx.pubKey,
3140
                mode,
3141
                (byte*)in,
3142
                inLen,
3143
                sig);
3144
3145
    if (ret != SA_SILIB_RET_OK){
3146
        WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed");
3147
        return -1;
3148
    }
3149
3150
    return ret;
3151
}
3152
#endif /* WOLFSSL_CRYPTOCELL */
3153
3154
#ifndef WOLF_CRYPTO_CB_ONLY_RSA
3155
#if !defined(NO_RSA_BOUNDS_CHECK)
3156
/* Check that 1 < in < n-1. (Requirement of 800-56B.) */
3157
int RsaFunctionCheckIn(const byte* in, word32 inLen, RsaKey* key,
3158
    int checkSmallCt)
3159
8.31k
{
3160
8.31k
    int ret = 0;
3161
8.31k
    DECL_MP_INT_SIZE_DYN(c, mp_bitsused(&key->n), RSA_MAX_SIZE);
3162
3163
8.31k
    NEW_MP_INT_SIZE(c, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3164
8.31k
#ifdef MP_INT_SIZE_CHECK_NULL
3165
8.31k
    if (c == NULL)
3166
1
        ret = MEMORY_E;
3167
8.31k
#endif
3168
3169
8.31k
    if (ret == 0 && INIT_MP_INT_SIZE(c, mp_bitsused(&key->n)) != MP_OKAY) {
3170
2
        ret = MP_INIT_E;
3171
2
    }
3172
8.31k
    if (ret == 0) {
3173
8.30k
        if (mp_read_unsigned_bin(c, in, inLen) != 0)
3174
14
            ret = MP_READ_E;
3175
8.30k
    }
3176
8.31k
    if (ret == 0) {
3177
        /* check c > 1 */
3178
8.29k
        if (checkSmallCt && (mp_cmp_d(c, 1) != MP_GT))
3179
10
            ret = RSA_OUT_OF_RANGE_E;
3180
8.29k
    }
3181
8.31k
    if (ret == 0) {
3182
        /* add c+1 */
3183
8.28k
        if (mp_add_d(c, 1, c) != MP_OKAY)
3184
1
            ret = MP_ADD_E;
3185
8.28k
    }
3186
8.31k
    if (ret == 0) {
3187
        /* check c+1 < n */
3188
8.28k
        if (mp_cmp(c, &key->n) != MP_LT)
3189
85
            ret = RSA_OUT_OF_RANGE_E;
3190
8.28k
    }
3191
8.31k
    mp_clear(c);
3192
3193
8.31k
    FREE_MP_INT_SIZE(c, key->heap, DYNAMIC_TYPE_RSA);
3194
3195
8.31k
    return ret;
3196
8.31k
}
3197
#endif /* !NO_RSA_BOUNDS_CHECK */
3198
#endif /* WOLF_CRYPTO_CB_ONLY_RSA */
3199
3200
static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out,
3201
                             word32* outLen, int type, RsaKey* key, WC_RNG* rng,
3202
                             int checkSmallCt)
3203
18.7k
{
3204
18.7k
    int ret = 0;
3205
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3206
    RsaPadding padding;
3207
#endif
3208
3209
18.7k
    (void)rng;
3210
18.7k
    (void)checkSmallCt;
3211
3212
18.7k
    if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
3213
18.7k
            outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
3214
0
        return BAD_FUNC_ARG;
3215
0
    }
3216
3217
18.7k
#ifdef WOLF_CRYPTO_CB
3218
18.7k
    #ifndef WOLF_CRYPTO_CB_FIND
3219
18.7k
    if (key->devId != INVALID_DEVID)
3220
0
    #endif
3221
0
    {
3222
    #if defined(WOLF_CRYPTO_CB_RSA_PAD)
3223
        /* If we are here, either the RSA PAD callback was already called
3224
         * and returned that it could not implement for that padding scheme,
3225
         * or this is a public verify operation. Either way indicate to the
3226
         * callback that this should be a raw RSA operation with no padding.*/
3227
        XMEMSET(&padding, 0, sizeof(RsaPadding));
3228
        padding.pad_type = WC_RSA_NO_PAD;
3229
        ret = wc_CryptoCb_RsaPad(in, inLen, out,
3230
                            outLen, type, key, rng, &padding);
3231
    #else
3232
0
        ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
3233
0
    #endif
3234
0
        #ifndef WOLF_CRYPTO_CB_ONLY_RSA
3235
0
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
3236
0
            return ret;
3237
        /* fall-through when unavailable and try using software */
3238
0
        #endif
3239
        #ifdef WOLF_CRYPTO_CB_ONLY_RSA
3240
        if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3241
            return NO_VALID_DEVID;
3242
        }
3243
        return ret;
3244
        #endif
3245
0
    }
3246
18.7k
#endif
3247
3248
#ifdef WOLF_CRYPTO_CB_ONLY_RSA
3249
    return NO_VALID_DEVID;
3250
#else /* !WOLF_CRYPTO_CB_ONLY_RSA */
3251
18.7k
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3252
3253
18.7k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(TEST_UNPAD_CONSTANT_TIME) && \
3254
18.7k
    !defined(NO_RSA_BOUNDS_CHECK)
3255
18.7k
    if (type == RSA_PRIVATE_DECRYPT &&
3256
0
        key->state == RSA_STATE_DECRYPT_EXPTMOD) {
3257
3258
0
        ret = RsaFunctionCheckIn(in, inLen, key, checkSmallCt);
3259
0
        if (ret != 0) {
3260
0
            RESTORE_VECTOR_REGISTERS();
3261
0
            return ret;
3262
0
        }
3263
0
    }
3264
18.7k
#endif /* !WOLFSSL_RSA_VERIFY_ONLY && !TEST_UNPAD_CONSTANT_TIME && \
3265
        * !NO_RSA_BOUNDS_CHECK */
3266
18.7k
#if !defined(NO_RSA_BOUNDS_CHECK)
3267
18.7k
    if (type == RSA_PUBLIC_DECRYPT &&
3268
8.31k
        key->state == RSA_STATE_DECRYPT_EXPTMOD) {
3269
3270
8.31k
        ret = RsaFunctionCheckIn(in, inLen, key, checkSmallCt);
3271
8.31k
        if (ret != 0) {
3272
113
            RESTORE_VECTOR_REGISTERS();
3273
113
            return ret;
3274
113
        }
3275
8.31k
    }
3276
18.6k
#endif
3277
3278
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
3279
    if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3280
                                                        key->n.raw.len > 0) {
3281
        ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
3282
    }
3283
    else
3284
#endif
3285
#ifdef WC_RSA_NONBLOCK
3286
    if (key->nb) {
3287
        ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
3288
    }
3289
    else
3290
#endif
3291
18.6k
    {
3292
18.6k
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
3293
18.6k
    }
3294
3295
18.6k
    RESTORE_VECTOR_REGISTERS();
3296
3297
    /* handle error */
3298
18.6k
    if (ret < 0 && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
3299
    #ifdef WC_RSA_NONBLOCK
3300
        && ret != FP_WOULDBLOCK
3301
    #endif
3302
18.6k
    ) {
3303
1.63k
        if (ret == WC_NO_ERR_TRACE(MP_EXPTMOD_E)) {
3304
            /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
3305
244
            WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
3306
244
        }
3307
3308
1.63k
        key->state = RSA_STATE_NONE;
3309
1.63k
        wc_RsaCleanup(key);
3310
1.63k
    }
3311
18.6k
    return ret;
3312
18.7k
#endif /* !WOLF_CRYPTO_CB_ONLY_RSA */
3313
18.7k
}
3314
3315
int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
3316
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
3317
10.4k
{
3318
    /* Always check for ciphertext of 0 or 1. (Shouldn't for OAEP decrypt.) */
3319
10.4k
    return wc_RsaFunction_ex(in, inLen, out, outLen, type, key, rng, 1);
3320
10.4k
}
3321
3322
#ifndef WOLFSSL_RSA_VERIFY_ONLY
3323
/* Internal Wrappers */
3324
/* Gives the option of choosing padding type
3325
   in : input to be encrypted
3326
   inLen: length of input buffer
3327
   out: encrypted output
3328
   outLen: length of encrypted output buffer
3329
   key   : wolfSSL initialized RSA key struct
3330
   rng   : wolfSSL initialized random number struct
3331
   rsa_type  : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
3332
        RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
3333
   pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
3334
   pad_type  : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
3335
        WC_RSA_NO_PAD or WC_RSA_PSS_PAD
3336
   hash  : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
3337
   mgf   : type of mask generation function to use
3338
   label : optional label
3339
   labelSz : size of optional label buffer
3340
   saltLen : Length of salt used in PSS
3341
   rng : random number generator */
3342
static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
3343
                            word32 outLen, RsaKey* key, int rsa_type,
3344
                            byte pad_value, int pad_type,
3345
                            enum wc_HashType hash, int mgf,
3346
                            byte* label, word32 labelSz, int saltLen,
3347
                            WC_RNG* rng)
3348
10.7k
{
3349
10.7k
    int ret = 0;
3350
10.7k
    int sz;
3351
10.7k
    int state;
3352
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3353
    RsaPadding padding;
3354
#endif
3355
3356
10.7k
    if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
3357
7
        return BAD_FUNC_ARG;
3358
7
    }
3359
3360
10.7k
    sz = wc_RsaEncryptSize(key);
3361
10.7k
    if (sz > (int)outLen) {
3362
17
        return RSA_BUFFER_E;
3363
17
    }
3364
3365
10.6k
    if (sz < RSA_MIN_PAD_SZ || sz > (int)RSA_MAX_SIZE/8) {
3366
4
        return WC_KEY_SIZE_E;
3367
4
    }
3368
3369
10.6k
    if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
3370
26
#ifdef WC_RSA_NO_PADDING
3371
        /* In the case that no padding is used the input length can and should
3372
         * be the same size as the RSA key. */
3373
26
        if (pad_type != WC_RSA_NO_PAD)
3374
5
#endif
3375
5
        return RSA_BUFFER_E;
3376
26
    }
3377
3378
10.6k
#ifndef WOLFSSL_BIND
3379
10.6k
    state = key->state;
3380
#else
3381
    /* Bind9 shares the EVP_PKEY struct across multiple threads so let's just
3382
     * force a restart on each RsaPublicEncryptEx call for it. */
3383
    state = RSA_STATE_NONE;
3384
#ifdef WOLFSSL_ASYNC_CRYPT
3385
#error wolfSSL does not handle building bind support with async crypto
3386
#endif
3387
#endif
3388
10.6k
    switch (state) {
3389
10.6k
    case RSA_STATE_NONE:
3390
10.6k
    case RSA_STATE_ENCRYPT_PAD:
3391
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3392
            defined(HAVE_CAVIUM)
3393
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3394
                                 pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
3395
            /* Async operations that include padding */
3396
            if (rsa_type == RSA_PUBLIC_ENCRYPT &&
3397
                                                pad_value == RSA_BLOCK_TYPE_2) {
3398
                key->state = RSA_STATE_ENCRYPT_RES;
3399
                key->dataLen = key->n.raw.len;
3400
                return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
3401
            }
3402
            else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3403
                                                pad_value == RSA_BLOCK_TYPE_1) {
3404
                key->state = RSA_STATE_ENCRYPT_RES;
3405
                key->dataLen = key->n.raw.len;
3406
                return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
3407
            }
3408
        }
3409
    #elif defined(WOLFSSL_CRYPTOCELL)
3410
        if (rsa_type == RSA_PUBLIC_ENCRYPT &&
3411
                                            pad_value == RSA_BLOCK_TYPE_2) {
3412
3413
            return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key);
3414
        }
3415
        else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3416
                                         pad_value == RSA_BLOCK_TYPE_1) {
3417
            return cc310_RsaSSL_Sign(in, inLen, out, outLen, key,
3418
                                  cc310_hashModeRSA(hash, 0));
3419
        }
3420
    #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
3421
        if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) {
3422
            return se050_rsa_public_encrypt(in, inLen, out, outLen, key,
3423
                                            rsa_type, pad_value, pad_type, hash,
3424
                                            mgf, label, labelSz, sz);
3425
        }
3426
        else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3427
                 pad_value == RSA_BLOCK_TYPE_1 &&
3428
                 pad_type != WC_RSA_PSS_PAD) {
3429
            /* SE050 handles PKCS#1 v1.5 signing directly. PSS signing falls
3430
             * through to software path because the SE050 PSS sign API
3431
             * (Se05x_API_RSASign) is hash-then-sign and does not support
3432
             * signing a pre-computed digest without double-hashing. */
3433
            return se050_rsa_sign(in, inLen, out, outLen, key, rsa_type,
3434
                                  pad_value, pad_type, hash, mgf, label,
3435
                                  labelSz, sz);
3436
        }
3437
    #endif /* RSA CRYPTO HW */
3438
3439
    #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3440
        if (key->devId != INVALID_DEVID) {
3441
            XMEMSET(&padding, 0, sizeof(RsaPadding));
3442
            padding.pad_value = pad_value;
3443
            padding.pad_type = pad_type;
3444
            padding.hash = hash;
3445
            padding.mgf = mgf;
3446
            padding.label = label;
3447
            padding.labelSz = labelSz;
3448
            padding.saltLen = saltLen;
3449
            ret = wc_CryptoCb_RsaPad(in, inLen, out, &outLen, rsa_type, key, rng,
3450
                                     &padding);
3451
3452
            if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3453
                if (ret < 0) {
3454
                    break;
3455
                }
3456
3457
                ret = outLen;
3458
                break;
3459
            }
3460
        }
3461
    #endif
3462
10.6k
        key->state = RSA_STATE_ENCRYPT_PAD;
3463
10.6k
        ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type,
3464
10.6k
                           hash, mgf, label, labelSz, saltLen,
3465
10.6k
                           mp_count_bits(&key->n), key->heap);
3466
10.6k
        if (ret < 0) {
3467
220
            break;
3468
220
        }
3469
3470
10.4k
        key->state = RSA_STATE_ENCRYPT_EXPTMOD;
3471
10.4k
        FALL_THROUGH;
3472
3473
10.4k
    case RSA_STATE_ENCRYPT_EXPTMOD:
3474
3475
10.4k
        key->dataLen = outLen;
3476
10.4k
        ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key,
3477
10.4k
                             rng);
3478
3479
10.4k
        if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3480
9.18k
            key->state = RSA_STATE_ENCRYPT_RES;
3481
9.18k
        }
3482
10.4k
        if (ret < 0) {
3483
1.27k
            break;
3484
1.27k
        }
3485
3486
9.18k
        FALL_THROUGH;
3487
3488
9.18k
    case RSA_STATE_ENCRYPT_RES:
3489
9.18k
        ret = (int)key->dataLen;
3490
9.18k
        break;
3491
3492
0
    default:
3493
0
        ret = BAD_STATE_E;
3494
0
        break;
3495
10.6k
    }
3496
3497
    /* if async pending then return and skip done cleanup below */
3498
10.6k
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
3499
    #ifdef WC_RSA_NONBLOCK
3500
        || ret == FP_WOULDBLOCK
3501
    #endif
3502
10.6k
    ) {
3503
0
        return ret;
3504
0
    }
3505
3506
10.6k
    key->state = RSA_STATE_NONE;
3507
10.6k
    wc_RsaCleanup(key);
3508
3509
10.6k
    return ret;
3510
10.6k
}
3511
3512
#endif
3513
3514
/* Gives the option of choosing padding type
3515
   in : input to be decrypted
3516
   inLen: length of input buffer
3517
   out:  decrypted message
3518
   outLen: length of decrypted message in bytes
3519
   outPtr: optional inline output pointer (if provided doing inline)
3520
   key   : wolfSSL initialized RSA key struct
3521
   rsa_type  : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
3522
        RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
3523
   pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
3524
   pad_type  : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
3525
        WC_RSA_NO_PAD, WC_RSA_PSS_PAD
3526
   hash  : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
3527
   mgf   : type of mask generation function to use
3528
   label : optional label
3529
   labelSz : size of optional label buffer
3530
   saltLen : Length of salt used in PSS
3531
   rng : random number generator */
3532
static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
3533
                            word32 outLen, byte** outPtr, RsaKey* key,
3534
                            int rsa_type, byte pad_value, int pad_type,
3535
                            enum wc_HashType hash, int mgf,
3536
                            byte* label, word32 labelSz, int saltLen,
3537
                            WC_RNG* rng)
3538
8.70k
{
3539
8.70k
    int ret = WC_NO_ERR_TRACE(RSA_WRONG_TYPE_E);
3540
8.70k
    byte* pad = NULL;
3541
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3542
    RsaPadding padding;
3543
#endif
3544
3545
8.70k
    if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
3546
16
        return BAD_FUNC_ARG;
3547
16
    }
3548
3549
8.69k
    switch (key->state) {
3550
8.69k
    case RSA_STATE_NONE:
3551
8.69k
        key->dataLen = inLen;
3552
3553
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3554
            defined(HAVE_CAVIUM)
3555
        /* Async operations that include padding */
3556
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3557
                                                   pad_type != WC_RSA_PSS_PAD) {
3558
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3559
            if (rsa_type == RSA_PRIVATE_DECRYPT &&
3560
                                                pad_value == RSA_BLOCK_TYPE_2) {
3561
                key->state = RSA_STATE_DECRYPT_RES;
3562
                key->data = NULL;
3563
                return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
3564
                                               key);
3565
#endif
3566
            }
3567
            else if (rsa_type == RSA_PUBLIC_DECRYPT &&
3568
                                                pad_value == RSA_BLOCK_TYPE_1) {
3569
                key->state = RSA_STATE_DECRYPT_RES;
3570
                key->data = NULL;
3571
                return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
3572
            }
3573
        }
3574
    #elif defined(WOLFSSL_CRYPTOCELL)
3575
        if (rsa_type == RSA_PRIVATE_DECRYPT &&
3576
                                            pad_value == RSA_BLOCK_TYPE_2) {
3577
            ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key);
3578
            if (outPtr != NULL)
3579
                *outPtr = out; /* for inline */
3580
            return ret;
3581
        }
3582
        else if (rsa_type == RSA_PUBLIC_DECRYPT &&
3583
                                            pad_value == RSA_BLOCK_TYPE_1) {
3584
            return cc310_RsaSSL_Verify(in, inLen, out, key,
3585
                                       cc310_hashModeRSA(hash, 0));
3586
        }
3587
    #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
3588
        if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) {
3589
            ret = se050_rsa_private_decrypt(in, inLen, out, outLen, key,
3590
                                            rsa_type, pad_value, pad_type, hash,
3591
                                            mgf, label, labelSz);
3592
            if (outPtr != NULL) {
3593
                *outPtr = out;
3594
            }
3595
            return ret;
3596
        }
3597
        else if (rsa_type == RSA_PUBLIC_DECRYPT &&
3598
                 pad_value == RSA_BLOCK_TYPE_1 &&
3599
                 pad_type != WC_RSA_PSS_PAD) {
3600
            /* SE050 handles PKCS#1 v1.5 verification directly. PSS
3601
             * verification falls through to software path to match the
3602
             * software PSS signing path (SE050 PSS sign uses hash-then-sign
3603
             * which double-hashes a pre-computed digest). */
3604
            ret = se050_rsa_verify(in, inLen, out, outLen, key, rsa_type,
3605
                                   pad_value, pad_type, hash, mgf, label,
3606
                                   labelSz);
3607
            if (outPtr != NULL) {
3608
                *outPtr = out;
3609
            }
3610
            return ret;
3611
        }
3612
    #endif /* RSA CRYPTO HW */
3613
3614
3615
8.69k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
3616
8.69k
    !defined(WOLFSSL_NO_MALLOC)
3617
        /* verify the tmp ptr is NULL, otherwise indicates bad state */
3618
8.69k
        if (key->data != NULL) {
3619
0
            ret = BAD_STATE_E;
3620
0
            break;
3621
0
        }
3622
3623
        /* if not doing this inline then allocate a buffer for it */
3624
8.69k
        if (outPtr == NULL) {
3625
822
            key->data = (byte*)XMALLOC(inLen, key->heap,
3626
822
                                                      DYNAMIC_TYPE_WOLF_BIGINT);
3627
822
            key->dataIsAlloc = 1;
3628
822
            if (key->data == NULL) {
3629
0
                ret = MEMORY_E;
3630
0
                break;
3631
0
            }
3632
822
            XMEMCPY(key->data, in, inLen);
3633
822
            key->dataLen = inLen;
3634
822
        }
3635
7.87k
        else {
3636
7.87k
            key->dataIsAlloc = 0;
3637
7.87k
            key->data = out;
3638
7.87k
        }
3639
8.69k
#endif
3640
3641
8.69k
        key->state = RSA_STATE_DECRYPT_EXPTMOD;
3642
8.69k
        FALL_THROUGH;
3643
3644
8.69k
    case RSA_STATE_DECRYPT_EXPTMOD:
3645
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3646
    if ((key->devId != INVALID_DEVID)
3647
    #if !defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY) && \
3648
        !defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
3649
    && (rsa_type != RSA_PUBLIC_DECRYPT)
3650
    #endif
3651
    ) {
3652
        /* Everything except verify goes to crypto cb if
3653
         * WOLF_CRYPTO_CB_RSA_PAD defined */
3654
        XMEMSET(&padding, 0, sizeof(RsaPadding));
3655
        padding.pad_value = pad_value;
3656
        padding.pad_type = pad_type;
3657
        padding.hash = hash;
3658
        padding.mgf = mgf;
3659
        padding.label = label;
3660
        padding.labelSz = labelSz;
3661
        padding.saltLen = saltLen;
3662
        ret = wc_CryptoCb_RsaPad(in, inLen, out,
3663
                            &outLen, rsa_type, key, rng, &padding);
3664
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3665
            if (outPtr != NULL) {
3666
                *outPtr = out;
3667
            }
3668
            if (ret == 0) {
3669
                ret = (int)outLen;
3670
            }
3671
            break;
3672
        }
3673
    }
3674
#endif
3675
8.69k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
3676
8.69k
    !defined(WOLFSSL_NO_MALLOC)
3677
8.69k
        ret = wc_RsaFunction_ex(key->data, inLen, key->data, &key->dataLen,
3678
8.69k
                                                   rsa_type, key, rng,
3679
8.69k
                                                   pad_type != WC_RSA_OAEP_PAD);
3680
#else
3681
        ret = wc_RsaFunction_ex(in, inLen, out, &key->dataLen, rsa_type, key,
3682
                                              rng, pad_type != WC_RSA_OAEP_PAD);
3683
#endif
3684
3685
8.69k
        if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3686
8.09k
            key->state = RSA_STATE_DECRYPT_UNPAD;
3687
8.09k
        }
3688
8.69k
        if (ret < 0) {
3689
602
            break;
3690
602
        }
3691
3692
8.09k
        FALL_THROUGH;
3693
3694
8.09k
    case RSA_STATE_DECRYPT_UNPAD:
3695
8.09k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
3696
8.09k
    !defined(WOLFSSL_NO_MALLOC)
3697
8.09k
        ret = wc_RsaUnPad_ex(key->data,
3698
8.09k
            key->dataLen, &pad, pad_value, pad_type, hash, mgf,
3699
8.09k
            label, labelSz, saltLen, mp_count_bits(&key->n), key->heap);
3700
#else
3701
        ret = wc_RsaUnPad_ex(out,
3702
            key->dataLen, &pad, pad_value, pad_type, hash, mgf, label,
3703
            labelSz, saltLen, mp_count_bits(&key->n), key->heap);
3704
#endif
3705
8.09k
        if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) {
3706
6
            ret = RSA_BUFFER_E;
3707
6
        }
3708
8.08k
        else if (ret >= 0 && pad != NULL) {
3709
            /* only copy output if not inline */
3710
7.24k
            if (outPtr == NULL) {
3711
13
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
3712
13
    !defined(WOLFSSL_NO_MALLOC)
3713
13
                if (rsa_type == RSA_PRIVATE_DECRYPT) {
3714
0
                    word32 i = 0;
3715
0
                    word32 j;
3716
0
                    byte last = 0;
3717
0
                    int start = (int)((size_t)pad - (size_t)key->data);
3718
3719
0
                    for (j = 0; j < key->dataLen; j++) {
3720
0
                        signed char incMask;
3721
0
                        signed char maskData;
3722
3723
                        /* When j < start + outLen then out[i] = key->data[j]
3724
                         *                         else out[i] = last
3725
                         */
3726
0
                        maskData = (signed char)ctMaskLT((int)j,
3727
0
                            start + (int)outLen);
3728
0
                        out[i] = (byte)(key->data[j] &   maskData ) |
3729
0
                                 (byte)(last         & (~maskData));
3730
0
                        last = out[i];
3731
3732
                        /* Increment i when j is in range:
3733
                         *   [start..(start + outLen - 1)]. */
3734
0
                        incMask  = (signed char)ctMaskGTE((int)j, start);
3735
0
                        incMask &= (signed char)ctMaskLT((int)j,
3736
0
                            start + (int)outLen - 1);
3737
0
                        i += (word32)((byte)(-incMask));
3738
0
                    }
3739
0
                }
3740
13
                else
3741
13
#endif
3742
13
                {
3743
13
                    XMEMCPY(out, pad, (size_t)ret);
3744
13
                }
3745
13
            }
3746
7.23k
            else {
3747
7.23k
                *outPtr = pad;
3748
7.23k
            }
3749
3750
7.24k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
3751
7.24k
            ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret,
3752
7.24k
                               WC_NO_ERR_TRACE(RSA_BUFFER_E));
3753
7.24k
    #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN
3754
7.24k
            ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret,
3755
7.24k
                               WC_NO_ERR_TRACE(RSA_BUFFER_E));
3756
7.24k
    #endif
3757
#else
3758
            if (outLen < (word32)ret)
3759
                ret = RSA_BUFFER_E;
3760
#endif
3761
7.24k
        }
3762
3763
8.09k
        key->state = RSA_STATE_DECRYPT_RES;
3764
8.09k
        FALL_THROUGH;
3765
3766
8.09k
    case RSA_STATE_DECRYPT_RES:
3767
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3768
            defined(HAVE_CAVIUM)
3769
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3770
                                                   pad_type != WC_RSA_PSS_PAD) {
3771
            ret = key->asyncDev.event.ret;
3772
            if (ret >= 0) {
3773
                /* convert result */
3774
                byte* dataLen = (byte*)&key->dataLen;
3775
                ret = (dataLen[0] << 8) | (dataLen[1]);
3776
3777
                if (outPtr)
3778
                    *outPtr = in;
3779
            }
3780
        }
3781
    #endif
3782
8.09k
        break;
3783
3784
0
    default:
3785
0
        ret = BAD_STATE_E;
3786
0
        break;
3787
8.69k
    }
3788
3789
    /* if async pending then return and skip done cleanup below */
3790
8.69k
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
3791
    #ifdef WC_RSA_NONBLOCK
3792
        || ret == FP_WOULDBLOCK
3793
    #endif
3794
8.69k
    ) {
3795
0
        return ret;
3796
0
    }
3797
3798
8.69k
    key->state = RSA_STATE_NONE;
3799
8.69k
    wc_RsaCleanup(key);
3800
3801
8.69k
    return ret;
3802
8.69k
}
3803
3804
3805
#ifndef WOLFSSL_RSA_VERIFY_ONLY
3806
/* Public RSA Functions */
3807
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
3808
                                                     RsaKey* key, WC_RNG* rng)
3809
0
{
3810
0
    int ret;
3811
0
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3812
0
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
3813
0
        RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3814
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3815
0
    RESTORE_VECTOR_REGISTERS();
3816
0
    return ret;
3817
0
}
3818
3819
3820
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
3821
int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
3822
                    word32 outLen, RsaKey* key, WC_RNG* rng, int type,
3823
                    enum wc_HashType hash, int mgf, byte* label,
3824
                    word32 labelSz)
3825
532
{
3826
532
    int ret;
3827
532
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3828
532
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
3829
532
        RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
3830
532
    RESTORE_VECTOR_REGISTERS();
3831
532
    return ret;
3832
532
}
3833
#endif /* WC_NO_RSA_OAEP */
3834
#endif
3835
3836
3837
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3838
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
3839
0
{
3840
0
    WC_RNG* rng;
3841
0
    int ret;
3842
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3843
0
    if (key == NULL) {
3844
0
        return BAD_FUNC_ARG;
3845
0
    }
3846
0
    rng = key->rng;
3847
#else
3848
    rng = NULL;
3849
#endif
3850
0
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3851
0
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3852
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3853
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3854
0
    RESTORE_VECTOR_REGISTERS();
3855
0
    return ret;
3856
0
}
3857
3858
3859
#ifndef WC_NO_RSA_OAEP
3860
int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
3861
                                  RsaKey* key, int type, enum wc_HashType hash,
3862
                                  int mgf, byte* label, word32 labelSz)
3863
0
{
3864
0
    WC_RNG* rng;
3865
0
    int ret;
3866
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3867
0
    if (key == NULL) {
3868
0
        return BAD_FUNC_ARG;
3869
0
    }
3870
0
    rng = key->rng;
3871
#else
3872
    rng = NULL;
3873
#endif
3874
0
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3875
0
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3876
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
3877
0
        mgf, label, labelSz, 0, rng);
3878
0
    RESTORE_VECTOR_REGISTERS();
3879
0
    return ret;
3880
0
}
3881
#endif /* WC_NO_RSA_OAEP */
3882
3883
3884
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
3885
                                                 word32 outLen, RsaKey* key)
3886
0
{
3887
0
    WC_RNG* rng;
3888
0
    int ret;
3889
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3890
0
    if (key == NULL) {
3891
0
        return BAD_FUNC_ARG;
3892
0
    }
3893
0
    rng = key->rng;
3894
#else
3895
    rng = NULL;
3896
#endif
3897
0
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3898
0
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
3899
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
3900
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3901
0
    RESTORE_VECTOR_REGISTERS();
3902
0
    return ret;
3903
0
}
3904
3905
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
3906
int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
3907
                            word32 outLen, RsaKey* key, int type,
3908
                            enum wc_HashType hash, int mgf, byte* label,
3909
                            word32 labelSz)
3910
0
{
3911
0
    WC_RNG* rng;
3912
0
    int ret;
3913
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3914
0
    if (key == NULL) {
3915
0
        return BAD_FUNC_ARG;
3916
0
    }
3917
0
    rng = key->rng;
3918
#else
3919
    rng = NULL;
3920
#endif
3921
0
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3922
0
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
3923
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
3924
0
        labelSz, 0, rng);
3925
0
    RESTORE_VECTOR_REGISTERS();
3926
0
    return ret;
3927
0
}
3928
#endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
3929
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
3930
3931
#if !defined(WOLFSSL_CRYPTOCELL)
3932
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
3933
7.04k
{
3934
7.04k
    WC_RNG* rng;
3935
7.04k
    int ret;
3936
7.04k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3937
7.04k
    if (key == NULL) {
3938
0
        return BAD_FUNC_ARG;
3939
0
    }
3940
7.04k
    rng = key->rng;
3941
#else
3942
    rng = NULL;
3943
#endif
3944
7.04k
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3945
7.04k
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
3946
7.04k
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
3947
7.04k
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
3948
7.04k
    RESTORE_VECTOR_REGISTERS();
3949
7.04k
    return ret;
3950
7.04k
}
3951
#endif
3952
3953
#ifndef WOLFSSL_RSA_VERIFY_INLINE
3954
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
3955
                                                                 RsaKey* key)
3956
351
{
3957
351
    return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key, WC_RSA_PKCSV15_PAD);
3958
351
}
3959
3960
int  wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
3961
                         RsaKey* key, int pad_type)
3962
351
{
3963
351
    int ret;
3964
351
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3965
351
    ret = wc_RsaSSL_Verify_ex2(in, inLen, out, outLen, key, pad_type,
3966
351
            WC_HASH_TYPE_NONE);
3967
351
    RESTORE_VECTOR_REGISTERS();
3968
351
    return ret;
3969
351
}
3970
3971
int  wc_RsaSSL_Verify_ex2(const byte* in, word32 inLen, byte* out, word32 outLen,
3972
                         RsaKey* key, int pad_type, enum wc_HashType hash)
3973
351
{
3974
351
    WC_RNG* rng;
3975
351
    int ret;
3976
3977
351
    if (key == NULL) {
3978
0
        return BAD_FUNC_ARG;
3979
0
    }
3980
3981
351
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3982
351
    rng = key->rng;
3983
#else
3984
    rng = NULL;
3985
#endif
3986
3987
351
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
3988
351
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
3989
351
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
3990
351
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
3991
351
        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DEFAULT, rng);
3992
#else
3993
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
3994
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
3995
        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DISCOVER, rng);
3996
#endif
3997
351
    RESTORE_VECTOR_REGISTERS();
3998
351
    return ret;
3999
351
}
4000
#endif
4001
4002
#ifdef WC_RSA_PSS
4003
/* Verify the message signed with RSA-PSS.
4004
 * The input buffer is reused for the output buffer.
4005
 * Salt length is equal to hash length.
4006
 *
4007
 * in     Buffer holding encrypted data.
4008
 * inLen  Length of data in buffer.
4009
 * out    Pointer to address containing the PSS data.
4010
 * hash   Hash algorithm.
4011
 * mgf    Mask generation function.
4012
 * key    Public RSA key.
4013
 * returns the length of the PSS data on success and negative indicates failure.
4014
 */
4015
int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
4016
                           enum wc_HashType hash, int mgf, RsaKey* key)
4017
826
{
4018
826
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4019
826
    return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
4020
826
                                                 RSA_PSS_SALT_LEN_DEFAULT, key);
4021
#else
4022
    return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
4023
                                                RSA_PSS_SALT_LEN_DISCOVER, key);
4024
#endif
4025
826
}
4026
4027
/* Verify the message signed with RSA-PSS.
4028
 * The input buffer is reused for the output buffer.
4029
 *
4030
 * in       Buffer holding encrypted data.
4031
 * inLen    Length of data in buffer.
4032
 * out      Pointer to address containing the PSS data.
4033
 * hash     Hash algorithm.
4034
 * mgf      Mask generation function.
4035
 * key      Public RSA key.
4036
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4037
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4038
 *          indicates salt length is determined from the data.
4039
 * returns the length of the PSS data on success and negative indicates failure.
4040
 */
4041
int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
4042
                              enum wc_HashType hash, int mgf, int saltLen,
4043
                              RsaKey* key)
4044
826
{
4045
826
    WC_RNG* rng;
4046
826
    int ret;
4047
826
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4048
826
    if (key == NULL) {
4049
0
        return BAD_FUNC_ARG;
4050
0
    }
4051
826
    rng = key->rng;
4052
#else
4053
    rng = NULL;
4054
#endif
4055
826
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
4056
826
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
4057
826
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
4058
826
        hash, mgf, NULL, 0, saltLen, rng);
4059
826
    RESTORE_VECTOR_REGISTERS();
4060
826
    return ret;
4061
826
}
4062
4063
/* Verify the message signed with RSA-PSS.
4064
 * Salt length is equal to hash length.
4065
 *
4066
 * in     Buffer holding encrypted data.
4067
 * inLen  Length of data in buffer.
4068
 * out    Pointer to address containing the PSS data.
4069
 * hash   Hash algorithm.
4070
 * mgf    Mask generation function.
4071
 * key    Public RSA key.
4072
 * returns the length of the PSS data on success and negative indicates failure.
4073
 */
4074
int wc_RsaPSS_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
4075
                     enum wc_HashType hash, int mgf, RsaKey* key)
4076
454
{
4077
454
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4078
454
    return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
4079
454
                                                 RSA_PSS_SALT_LEN_DEFAULT, key);
4080
#else
4081
    return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
4082
                                                RSA_PSS_SALT_LEN_DISCOVER, key);
4083
#endif
4084
454
}
4085
4086
/* Verify the message signed with RSA-PSS.
4087
 *
4088
 * in       Buffer holding encrypted data.
4089
 * inLen    Length of data in buffer.
4090
 * out      Pointer to address containing the PSS data.
4091
 * hash     Hash algorithm.
4092
 * mgf      Mask generation function.
4093
 * key      Public RSA key.
4094
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4095
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4096
 *          indicates salt length is determined from the data.
4097
 * returns the length of the PSS data on success and negative indicates failure.
4098
 */
4099
int wc_RsaPSS_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
4100
                        enum wc_HashType hash, int mgf, int saltLen,
4101
                        RsaKey* key)
4102
485
{
4103
485
    WC_RNG* rng;
4104
485
    int ret;
4105
485
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4106
485
    if (key == NULL) {
4107
0
        return BAD_FUNC_ARG;
4108
0
    }
4109
485
    rng = key->rng;
4110
#else
4111
    rng = NULL;
4112
#endif
4113
485
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
4114
485
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4115
485
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
4116
485
        hash, mgf, NULL, 0, saltLen, rng);
4117
485
    RESTORE_VECTOR_REGISTERS();
4118
485
    return ret;
4119
485
}
4120
4121
4122
/* Checks the PSS data to ensure that the signature matches.
4123
 * Salt length is equal to hash length.
4124
 *
4125
 * in        Hash of the data that is being verified.
4126
 * inSz      Length of hash.
4127
 * sig       Buffer holding PSS data.
4128
 * sigSz     Size of PSS data.
4129
 * hashType  Hash algorithm.
4130
 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
4131
 * NULL is passed in to in or sig or inSz is not the same as the hash
4132
 * algorithm length and 0 on success.
4133
 */
4134
int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, const byte* sig,
4135
                           word32 sigSz, enum wc_HashType hashType)
4136
168
{
4137
168
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4138
168
    return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DEFAULT, 0);
4139
#else
4140
    return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DISCOVER, 0);
4141
#endif
4142
168
}
4143
4144
/* Checks the PSS data to ensure that the signature matches.
4145
 *
4146
 * in        Hash of the data that is being verified.
4147
 * inSz      Length of hash.
4148
 * sig       Buffer holding PSS data.
4149
 * sigSz     Size of PSS data.
4150
 * hashType  Hash algorithm.
4151
 * saltLen   Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4152
 *           length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4153
 *           indicates salt length is determined from the data.
4154
 * bits      Can be used to calculate salt size in FIPS case
4155
 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
4156
 * NULL is passed in to in or sig or inSz is not the same as the hash
4157
 * algorithm length and 0 on success.
4158
 */
4159
int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, const byte* sig,
4160
                               word32 sigSz, enum wc_HashType hashType,
4161
                               int saltLen, int bits, void* heap)
4162
957
{
4163
957
    int ret = 0;
4164
957
    byte sigCheckBuf[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
4165
957
    byte *sigCheck = sigCheckBuf;
4166
957
    int digSz;
4167
957
    (void)bits;
4168
4169
957
    digSz = wc_HashGetDigestSize(hashType);
4170
4171
957
    if (in == NULL || sig == NULL || digSz < 0 || inSz != (word32)digSz) {
4172
26
        ret = BAD_FUNC_ARG;
4173
26
    }
4174
4175
957
    if (ret == 0) {
4176
931
        if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
4177
930
            saltLen = (int)inSz;
4178
930
            #ifdef WOLFSSL_SHA512
4179
                /* See FIPS 186-4 section 5.5 item (e). */
4180
930
                if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
4181
0
                    saltLen = RSA_PSS_SALT_MAX_SZ;
4182
0
                }
4183
930
            #endif
4184
930
        }
4185
#ifndef WOLFSSL_PSS_LONG_SALT
4186
        else if (saltLen > (int)inSz) {
4187
            ret = PSS_SALTLEN_E;
4188
        }
4189
#endif
4190
1
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4191
1
        else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
4192
0
            ret = PSS_SALTLEN_E;
4193
0
        }
4194
#else
4195
        else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
4196
            saltLen = sigSz - inSz;
4197
            if (saltLen < 0) {
4198
                ret = PSS_SALTLEN_E;
4199
            }
4200
        }
4201
        else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
4202
            ret = PSS_SALTLEN_E;
4203
        }
4204
#endif
4205
931
    }
4206
4207
    /* Sig = Salt | Exp Hash */
4208
957
    if (ret == 0) {
4209
931
        word32 totalSz = 0;
4210
931
        if ((WC_SAFE_SUM_WORD32(inSz, (word32)saltLen, totalSz) == 0) ||
4211
931
            (sigSz != totalSz))
4212
33
        {
4213
33
            ret = PSS_SALTLEN_E;
4214
33
        }
4215
931
    }
4216
4217
957
#ifdef WOLFSSL_PSS_LONG_SALT
4218
    /* if long salt is larger then default maximum buffer then allocate a buffer */
4219
957
    if ((ret == 0) &&
4220
898
            (sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen))) {
4221
0
        sigCheck = (byte*)XMALLOC(
4222
0
                              (size_t)(RSA_PSS_PAD_SZ + inSz + (word32)saltLen),
4223
0
                              heap, DYNAMIC_TYPE_RSA_BUFFER);
4224
0
        if (sigCheck == NULL) {
4225
0
            ret = MEMORY_E;
4226
0
        }
4227
0
    }
4228
#else
4229
    if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen)) {
4230
        ret = BUFFER_E;
4231
    }
4232
#endif
4233
4234
    /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
4235
957
    if (ret == 0) {
4236
898
        XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
4237
898
        XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
4238
898
        XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, (size_t)saltLen);
4239
898
        ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + (word32)saltLen,
4240
898
                      sigCheck, inSz);
4241
898
    }
4242
957
    if (ret == 0) {
4243
897
        if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
4244
109
            WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
4245
109
            ret = BAD_PADDING_E;
4246
109
        }
4247
897
    }
4248
4249
957
#ifdef WOLFSSL_PSS_LONG_SALT
4250
957
    if (sigCheck != NULL && sigCheck != sigCheckBuf) {
4251
0
        XFREE(sigCheck, heap, DYNAMIC_TYPE_RSA_BUFFER);
4252
0
    }
4253
957
#endif
4254
4255
957
    (void)heap; /* unused if memory is disabled */
4256
957
    return ret;
4257
957
}
4258
int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, const byte* sig,
4259
                               word32 sigSz, enum wc_HashType hashType,
4260
                               int saltLen, int bits)
4261
957
{
4262
957
    return wc_RsaPSS_CheckPadding_ex2(in, inSz, sig, sigSz, hashType, saltLen,
4263
957
        bits, NULL);
4264
957
}
4265
4266
4267
/* Verify the message signed with RSA-PSS.
4268
 * The input buffer is reused for the output buffer.
4269
 * Salt length is equal to hash length.
4270
 *
4271
 * in     Buffer holding encrypted data.
4272
 * inLen  Length of data in buffer.
4273
 * out    Pointer to address containing the PSS data.
4274
 * digest Hash of the data that is being verified.
4275
 * digestLen Length of hash.
4276
 * hash   Hash algorithm.
4277
 * mgf    Mask generation function.
4278
 * key    Public RSA key.
4279
 * returns the length of the PSS data on success and negative indicates failure.
4280
 */
4281
int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
4282
                           const byte* digest, word32 digestLen,
4283
                           enum wc_HashType hash, int mgf, RsaKey* key)
4284
0
{
4285
0
    int ret = 0, verify, saltLen, hLen, bits = 0;
4286
4287
0
    hLen = wc_HashGetDigestSize(hash);
4288
0
    if (hLen < 0)
4289
0
        return BAD_FUNC_ARG;
4290
0
    if ((word32)hLen != digestLen)
4291
0
        return BAD_FUNC_ARG;
4292
4293
0
    saltLen = hLen;
4294
0
    #ifdef WOLFSSL_SHA512
4295
0
        if (key == NULL) {
4296
0
            return BAD_FUNC_ARG;
4297
0
        }
4298
        /* See FIPS 186-4 section 5.5 item (e). */
4299
0
        bits = mp_count_bits(&key->n);
4300
0
        if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
4301
0
            saltLen = RSA_PSS_SALT_MAX_SZ;
4302
0
    #endif
4303
4304
0
    verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
4305
0
    if (verify > 0)
4306
0
        ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, (word32)verify,
4307
0
                                        hash, saltLen, bits);
4308
0
    if (ret == 0)
4309
0
        ret = verify;
4310
4311
0
    return ret;
4312
0
}
4313
4314
4315
/* Verify the message signed with RSA-PSS.
4316
 * Salt length is equal to hash length.
4317
 *
4318
 * in     Buffer holding encrypted data.
4319
 * inLen  Length of data in buffer.
4320
 * out    Pointer to address containing the PSS data.
4321
 * outLen Length of the output.
4322
 * digest Hash of the data that is being verified.
4323
 * digestLen Length of hash.
4324
 * hash   Hash algorithm.
4325
 * mgf    Mask generation function.
4326
 * key    Public RSA key.
4327
 * returns the length of the PSS data on success and negative indicates failure.
4328
 */
4329
int wc_RsaPSS_VerifyCheck(const byte* in, word32 inLen, byte* out, word32 outLen,
4330
                          const byte* digest, word32 digestLen,
4331
                          enum wc_HashType hash, int mgf,
4332
                          RsaKey* key)
4333
53
{
4334
53
    int ret = 0, verify, saltLen, hLen, bits = 0;
4335
4336
53
    hLen = wc_HashGetDigestSize(hash);
4337
53
    if (hLen < 0)
4338
2
        return hLen;
4339
51
    if ((word32)hLen != digestLen)
4340
20
        return BAD_FUNC_ARG;
4341
4342
31
    saltLen = hLen;
4343
31
    #ifdef WOLFSSL_SHA512
4344
31
        if (key == NULL) {
4345
0
            return BAD_FUNC_ARG;
4346
0
        }
4347
        /* See FIPS 186-4 section 5.5 item (e). */
4348
31
        bits = mp_count_bits(&key->n);
4349
31
        if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
4350
3
            saltLen = RSA_PSS_SALT_MAX_SZ;
4351
31
    #endif
4352
4353
31
    verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
4354
31
                                 mgf, saltLen, key);
4355
31
    if (verify > 0)
4356
1
        ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, (word32)verify,
4357
1
                                        hash, saltLen, bits);
4358
31
    if (ret == 0)
4359
30
        ret = verify;
4360
4361
31
    return ret;
4362
31
}
4363
4364
#endif
4365
4366
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
4367
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
4368
                                                   RsaKey* key, WC_RNG* rng)
4369
8.84k
{
4370
8.84k
    int ret;
4371
8.84k
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
4372
8.84k
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
4373
8.84k
        RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
4374
8.84k
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
4375
8.84k
    RESTORE_VECTOR_REGISTERS();
4376
8.84k
    return ret;
4377
8.84k
}
4378
4379
#ifdef WC_RSA_PSS
4380
/* Sign the hash of a message using RSA-PSS.
4381
 * Salt length is equal to hash length.
4382
 *
4383
 * in      Buffer holding hash of message.
4384
 * inLen   Length of data in buffer (hash length).
4385
 * out     Buffer to write encrypted signature into.
4386
 * outLen  Size of buffer to write to.
4387
 * hash    Hash algorithm.
4388
 * mgf     Mask generation function.
4389
 * key     Public RSA key.
4390
 * rng     Random number generator.
4391
 * returns the length of the encrypted signature on success, a negative value
4392
 * indicates failure.
4393
 */
4394
int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
4395
                       enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
4396
1.33k
{
4397
1.33k
    return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
4398
1.33k
                                            RSA_PSS_SALT_LEN_DEFAULT, key, rng);
4399
1.33k
}
4400
4401
/* Sign the hash of a message using RSA-PSS.
4402
 *
4403
 * in       Buffer holding hash of message.
4404
 * inLen    Length of data in buffer (hash length).
4405
 * out      Buffer to write encrypted signature into.
4406
 * outLen   Size of buffer to write to.
4407
 * hash     Hash algorithm.
4408
 * mgf      Mask generation function.
4409
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4410
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4411
 *          indicates salt length is determined from the data.
4412
 * key      Public RSA key.
4413
 * rng      Random number generator.
4414
 * returns the length of the encrypted signature on success, a negative value
4415
 * indicates failure.
4416
 */
4417
int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
4418
                      enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
4419
                      WC_RNG* rng)
4420
1.33k
{
4421
1.33k
    int ret;
4422
1.33k
    SAVE_VECTOR_REGISTERS(return _svr_ret;);
4423
1.33k
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
4424
1.33k
        RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
4425
1.33k
        hash, mgf, NULL, 0, saltLen, rng);
4426
1.33k
    RESTORE_VECTOR_REGISTERS();
4427
1.33k
    return ret;
4428
1.33k
}
4429
#endif
4430
#endif
4431
4432
int wc_RsaEncryptSize(const RsaKey* key)
4433
37.9k
{
4434
37.9k
    int ret;
4435
4436
37.9k
    if (key == NULL) {
4437
0
        return BAD_FUNC_ARG;
4438
0
    }
4439
4440
37.9k
    ret = mp_unsigned_bin_size(&key->n);
4441
4442
37.9k
#ifdef WOLF_CRYPTO_CB
4443
37.9k
    if (ret == 0 && key->devId != INVALID_DEVID) {
4444
0
        if (wc_CryptoCb_RsaGetSize(key, &ret) == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4445
0
            ret = 2048/8; /* hardware handles, use 2048-bit as default */
4446
0
        }
4447
0
    }
4448
37.9k
#endif
4449
4450
37.9k
    return ret;
4451
37.9k
}
4452
4453
#ifndef WOLFSSL_RSA_VERIFY_ONLY
4454
/* flatten RsaKey structure into individual elements (e, n) */
4455
int wc_RsaFlattenPublicKey(const RsaKey* key, byte* e, word32* eSz, byte* n,
4456
                                                                   word32* nSz)
4457
0
{
4458
0
    int sz, ret;
4459
4460
0
    if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
4461
0
        return BAD_FUNC_ARG;
4462
0
    }
4463
4464
0
    sz = mp_unsigned_bin_size(&key->e);
4465
0
    if ((word32)sz > *eSz)
4466
0
        return RSA_BUFFER_E;
4467
0
    ret = mp_to_unsigned_bin(&key->e, e);
4468
0
    if (ret != MP_OKAY)
4469
0
        return ret;
4470
0
    *eSz = (word32)sz;
4471
4472
0
    sz = wc_RsaEncryptSize(key);
4473
0
    if ((word32)sz > *nSz)
4474
0
        return RSA_BUFFER_E;
4475
0
    ret = mp_to_unsigned_bin(&key->n, n);
4476
0
    if (ret != MP_OKAY)
4477
0
        return ret;
4478
0
    *nSz = (word32)sz;
4479
4480
0
    return 0;
4481
0
}
4482
#endif
4483
4484
#ifndef WOLFSSL_RSA_VERIFY_ONLY
4485
static int RsaGetValue(const mp_int* in, byte* out, word32* outSz)
4486
0
{
4487
0
    word32 sz;
4488
0
    int ret = 0;
4489
4490
    /* Parameters ensured by calling function. */
4491
4492
0
    sz = (word32)mp_unsigned_bin_size(in);
4493
0
    if (sz > *outSz)
4494
0
        ret = RSA_BUFFER_E;
4495
4496
0
    if (ret == 0)
4497
0
        ret = mp_to_unsigned_bin(in, out);
4498
4499
0
    if (ret == MP_OKAY)
4500
0
        *outSz = sz;
4501
4502
0
    return ret;
4503
0
}
4504
4505
4506
int wc_RsaExportKey(const RsaKey* key,
4507
                    byte* e, word32* eSz, byte* n, word32* nSz,
4508
                    byte* d, word32* dSz, byte* p, word32* pSz,
4509
                    byte* q, word32* qSz)
4510
0
{
4511
0
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
4512
4513
0
    if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz)
4514
0
        ret = 0;
4515
4516
0
    if (ret == 0)
4517
0
        ret = RsaGetValue(&key->e, e, eSz);
4518
0
    if (ret == 0)
4519
0
        ret = RsaGetValue(&key->n, n, nSz);
4520
0
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
4521
0
    if (ret == 0)
4522
0
        ret = RsaGetValue(&key->d, d, dSz);
4523
0
    if (ret == 0)
4524
0
        ret = RsaGetValue(&key->p, p, pSz);
4525
0
    if (ret == 0)
4526
0
        ret = RsaGetValue(&key->q, q, qSz);
4527
#else
4528
    /* no private parts to key */
4529
    if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
4530
            || qSz == NULL) {
4531
        ret = BAD_FUNC_ARG;
4532
    }
4533
    else {
4534
        *dSz = 0;
4535
        *pSz = 0;
4536
        *qSz = 0;
4537
    }
4538
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
4539
4540
0
    return ret;
4541
0
}
4542
#endif
4543
4544
4545
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
4546
4547
/* Check that |p-q| > 2^((size/2)-100) */
4548
static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size, int* valid)
4549
0
{
4550
0
#ifdef WOLFSSL_SMALL_STACK
4551
0
    mp_int *c = NULL, *d = NULL;
4552
#else
4553
    mp_int c[1], d[1];
4554
#endif
4555
0
    int ret;
4556
4557
0
    if (p == NULL || q == NULL)
4558
0
        return BAD_FUNC_ARG;
4559
4560
0
#ifdef WOLFSSL_SMALL_STACK
4561
0
    if (((c = (mp_int *)XMALLOC(sizeof(*c), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
4562
0
        ((d = (mp_int *)XMALLOC(sizeof(*d), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL))
4563
0
        ret = MEMORY_E;
4564
0
    else
4565
0
        ret = 0;
4566
4567
0
    if (ret == 0)
4568
0
#endif
4569
0
        ret = mp_init_multi(c, d, NULL, NULL, NULL, NULL);
4570
4571
    /* c = 2^((size/2)-100) */
4572
0
    if (ret == 0)
4573
0
        ret = mp_2expt(c, (size/2)-100);
4574
4575
    /* d = |p-q| */
4576
0
    if (ret == 0)
4577
0
        ret = mp_sub(p, q, d);
4578
4579
#ifdef WOLFSSL_CHECK_MEM_ZERO
4580
    if (ret == 0)
4581
        mp_memzero_add("Compare PQ d", d);
4582
#endif
4583
4584
0
#if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \
4585
0
                                               defined(WOLFSSL_SP_INT_NEGATIVE))
4586
0
    if (ret == 0)
4587
0
        ret = mp_abs(d, d);
4588
0
#endif
4589
4590
    /* compare */
4591
0
    if (ret == 0)
4592
0
        *valid = (mp_cmp(d, c) == MP_GT);
4593
4594
0
#ifdef WOLFSSL_SMALL_STACK
4595
0
    if (d != NULL) {
4596
0
        mp_forcezero(d);
4597
0
        XFREE(d, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
4598
0
    }
4599
0
    if (c != NULL) {
4600
0
        mp_clear(c);
4601
0
        XFREE(c, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
4602
0
    }
4603
#else
4604
    mp_forcezero(d);
4605
    mp_clear(c);
4606
#ifdef WOLFSSL_CHECK_MEM_ZERO
4607
    mp_memzero_check(d);
4608
#endif
4609
#endif
4610
4611
0
    return ret;
4612
0
}
4613
4614
4615
/* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
4616
 * This number was calculated using a small test tool written with a common
4617
 * large number math library. Other values of nlen may be checked with a subset
4618
 * of lower_bound. */
4619
static const byte lower_bound[] = {
4620
    0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
4621
    0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
4622
    0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
4623
    0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
4624
/* 512 */
4625
    0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
4626
    0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
4627
    0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
4628
    0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
4629
/* 1024 */
4630
    0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
4631
    0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
4632
    0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
4633
    0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
4634
    0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
4635
    0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
4636
    0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
4637
    0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
4638
/* 2048 */
4639
    0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
4640
    0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
4641
    0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
4642
    0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
4643
    0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
4644
    0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
4645
    0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
4646
    0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
4647
/* 3072 */
4648
    0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
4649
    0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
4650
    0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
4651
    0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
4652
    0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
4653
    0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
4654
    0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
4655
    0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
4656
/* 4096 */
4657
};
4658
4659
4660
/* returns 1 on key size ok and 0 if not ok */
4661
static WC_INLINE int RsaSizeCheck(int size)
4662
0
{
4663
0
    if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
4664
0
        return 0;
4665
0
    }
4666
4667
#ifdef HAVE_FIPS
4668
    /* Key size requirements for CAVP */
4669
    switch (size) {
4670
        case 1024:
4671
        case 2048:
4672
        case 3072:
4673
        case 4096:
4674
            return 1;
4675
    }
4676
4677
    return 0;
4678
#else
4679
0
    return 1; /* allow unusual key sizes in non FIPS mode */
4680
0
#endif /* HAVE_FIPS */
4681
0
}
4682
4683
4684
static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
4685
                                    int* isPrime, WC_RNG* rng)
4686
0
{
4687
0
    int ret;
4688
0
#ifdef WOLFSSL_SMALL_STACK
4689
0
    mp_int *tmp1 = NULL, *tmp2 = NULL;
4690
#else
4691
    mp_int tmp1[1], tmp2[2];
4692
#endif
4693
0
    mp_int* prime;
4694
4695
0
    if (p == NULL || e == NULL || isPrime == NULL)
4696
0
        return BAD_FUNC_ARG;
4697
4698
0
    if (!RsaSizeCheck(nlen))
4699
0
        return BAD_FUNC_ARG;
4700
4701
0
    *isPrime = MP_NO;
4702
4703
0
#ifdef WOLFSSL_SMALL_STACK
4704
0
    if (((tmp1 = (mp_int *)XMALLOC(sizeof(*tmp1), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
4705
0
        ((tmp2 = (mp_int *)XMALLOC(sizeof(*tmp2), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL)) {
4706
0
        ret = MEMORY_E;
4707
0
        goto notOkay;
4708
0
    }
4709
0
#endif
4710
4711
0
    ret = mp_init_multi(tmp1, tmp2, NULL, NULL, NULL, NULL);
4712
0
    if (ret != MP_OKAY) goto notOkay;
4713
4714
0
    if (q != NULL) {
4715
0
        int valid = 0;
4716
        /* 5.4 (186-4) 5.5 (186-5) -
4717
         * check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
4718
0
        ret = wc_CompareDiffPQ(p, q, nlen, &valid);
4719
0
        if ((ret != MP_OKAY) || (!valid)) goto notOkay;
4720
0
        prime = q;
4721
0
    }
4722
0
    else
4723
0
        prime = p;
4724
4725
    /* 4.4,5.5 (186-4) 4.4,5.4 (186-5) -
4726
     * Check that prime >= (2^(1/2))(2^((nlen/2)-1))
4727
     *           This is a comparison against lowerBound */
4728
0
    ret = mp_read_unsigned_bin(tmp1, lower_bound, (word32)nlen/16);
4729
0
    if (ret != MP_OKAY) goto notOkay;
4730
0
    ret = mp_cmp(prime, tmp1);
4731
0
    if (ret == MP_LT) goto exit;
4732
4733
    /* 4.5,5.6 (186-4 & 186-5) - Check that GCD(p-1, e) == 1 */
4734
0
    ret = mp_sub_d(prime, 1, tmp1);  /* tmp1 = prime-1 */
4735
0
    if (ret != MP_OKAY) goto notOkay;
4736
#ifdef WOLFSSL_CHECK_MEM_ZERO
4737
    mp_memzero_add("Check Probable Prime tmp1", tmp1);
4738
#endif
4739
0
    ret = mp_gcd(tmp1, e, tmp2);  /* tmp2 = gcd(prime-1, e) */
4740
0
    if (ret != MP_OKAY) goto notOkay;
4741
0
    ret = mp_cmp_d(tmp2, 1);
4742
0
    if (ret != MP_EQ) goto exit; /* e divides p-1 */
4743
4744
    /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
4745
     * mp_prime_is_prime_ex() performs test divisions against the first 256
4746
     * prime numbers. After that it performs 8 rounds of M-R using random
4747
     * bases between 2 and n-2.
4748
     * mp_prime_is_prime() performs the same test divisions and then does
4749
     * M-R with the first 8 primes. Both functions set isPrime as a
4750
     * side-effect. */
4751
0
    if (rng != NULL)
4752
0
        ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
4753
0
    else
4754
0
        ret = mp_prime_is_prime(prime, 8, isPrime);
4755
0
    if (ret != MP_OKAY) goto notOkay;
4756
4757
0
exit:
4758
0
    ret = MP_OKAY;
4759
4760
0
notOkay:
4761
4762
0
#ifdef WOLFSSL_SMALL_STACK
4763
0
    if (tmp1 != NULL) {
4764
0
        mp_forcezero(tmp1);
4765
0
        XFREE(tmp1, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
4766
0
    }
4767
0
    if (tmp2 != NULL) {
4768
0
        mp_clear(tmp2);
4769
0
        XFREE(tmp2, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
4770
0
    }
4771
#else
4772
    mp_forcezero(tmp1);
4773
    mp_clear(tmp2);
4774
#ifdef WOLFSSL_CHECK_MEM_ZERO
4775
    mp_memzero_check(tmp1);
4776
#endif
4777
#endif
4778
4779
0
    return ret;
4780
0
}
4781
4782
4783
int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
4784
                          const byte* qRaw, word32 qRawSz,
4785
                          const byte* eRaw, word32 eRawSz,
4786
                          int nlen, int* isPrime, WC_RNG* rng)
4787
0
{
4788
0
#ifdef WOLFSSL_SMALL_STACK
4789
0
    mp_int *p = NULL, *q = NULL, *e = NULL;
4790
#else
4791
    mp_int p[1], q[1], e[1];
4792
#endif
4793
0
    mp_int* Q = NULL;
4794
0
    int ret;
4795
4796
0
    if (pRaw == NULL || pRawSz == 0 ||
4797
0
        eRaw == NULL || eRawSz == 0 ||
4798
0
        isPrime == NULL) {
4799
4800
0
        return BAD_FUNC_ARG;
4801
0
    }
4802
4803
0
    if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
4804
0
        return BAD_FUNC_ARG;
4805
4806
0
#ifdef WOLFSSL_SMALL_STACK
4807
4808
0
    if (((p = (mp_int *)XMALLOC(sizeof(*p), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
4809
0
        ((q = (mp_int *)XMALLOC(sizeof(*q), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
4810
0
        ((e = (mp_int *)XMALLOC(sizeof(*e), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL))
4811
0
        ret = MEMORY_E;
4812
0
    else
4813
0
        ret = 0;
4814
0
    if (ret == 0)
4815
0
#endif
4816
0
        ret = mp_init_multi(p, q, e, NULL, NULL, NULL);
4817
4818
0
    if (ret == MP_OKAY)
4819
0
        ret = mp_read_unsigned_bin(p, pRaw, pRawSz);
4820
4821
0
    if (ret == MP_OKAY) {
4822
    #ifdef WOLFSSL_CHECK_MEM_ZERO
4823
        mp_memzero_add("wc_CheckProbablePrime_ex p", p);
4824
    #endif
4825
0
        if (qRaw != NULL) {
4826
0
            ret = mp_read_unsigned_bin(q, qRaw, qRawSz);
4827
0
            if (ret == MP_OKAY) {
4828
            #ifdef WOLFSSL_CHECK_MEM_ZERO
4829
                mp_memzero_add("wc_CheckProbablePrime_ex q", q);
4830
            #endif
4831
0
                Q = q;
4832
0
            }
4833
0
        }
4834
0
    }
4835
4836
0
    if (ret == MP_OKAY)
4837
0
        ret = mp_read_unsigned_bin(e, eRaw, eRawSz);
4838
4839
0
    if (ret == MP_OKAY)
4840
0
        SAVE_VECTOR_REGISTERS(ret = _svr_ret;);
4841
4842
0
    if (ret == 0) {
4843
0
        ret = _CheckProbablePrime(p, Q, e, nlen, isPrime, rng);
4844
0
        RESTORE_VECTOR_REGISTERS();
4845
0
    }
4846
4847
0
    ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
4848
4849
0
#ifdef WOLFSSL_SMALL_STACK
4850
0
    if (p != NULL) {
4851
0
        mp_forcezero(p);
4852
0
        XFREE(p, NULL, DYNAMIC_TYPE_RSA_BUFFER);
4853
0
    }
4854
0
    if (q != NULL) {
4855
0
        mp_forcezero(q);
4856
0
        XFREE(q, NULL, DYNAMIC_TYPE_RSA_BUFFER);
4857
0
    }
4858
0
    if (e != NULL) {
4859
0
        mp_clear(e);
4860
0
        XFREE(e, NULL, DYNAMIC_TYPE_RSA_BUFFER);
4861
0
    }
4862
#else
4863
    mp_forcezero(p);
4864
    mp_forcezero(q);
4865
    mp_clear(e);
4866
#ifdef WOLFSSL_CHECK_MEM_ZERO
4867
    mp_memzero_check(p);
4868
    mp_memzero_check(q);
4869
#endif
4870
#endif
4871
4872
0
    return ret;
4873
0
}
4874
4875
4876
int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
4877
                          const byte* qRaw, word32 qRawSz,
4878
                          const byte* eRaw, word32 eRawSz,
4879
                          int nlen, int* isPrime)
4880
0
{
4881
0
    return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
4882
0
                          eRaw, eRawSz, nlen, isPrime, NULL);
4883
0
}
4884
4885
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
4886
        defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
4887
/* Make an RSA key for size bits, with e specified, 65537 is a good e */
4888
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
4889
0
{
4890
0
#ifndef WC_NO_RNG
4891
0
#if !defined(WOLFSSL_CRYPTOCELL) && \
4892
0
    (!defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_NO_RSA)) && \
4893
0
    !defined(WOLF_CRYPTO_CB_ONLY_RSA)
4894
0
#ifdef WOLFSSL_SMALL_STACK
4895
0
    mp_int *p = NULL;
4896
0
    mp_int *q = NULL;
4897
0
    mp_int *tmp1 = NULL;
4898
0
    mp_int *tmp2 = NULL;
4899
0
    mp_int *tmp3 = NULL;
4900
#else
4901
    mp_int p_buf, *p = &p_buf;
4902
    mp_int q_buf, *q = &q_buf;
4903
    mp_int tmp1_buf, *tmp1 = &tmp1_buf;
4904
    mp_int tmp2_buf, *tmp2 = &tmp2_buf;
4905
    mp_int tmp3_buf, *tmp3 = &tmp3_buf;
4906
#endif /* WOLFSSL_SMALL_STACK */
4907
0
    int i, failCount, isPrime = 0;
4908
0
    word32 primeSz;
4909
0
#ifndef WOLFSSL_NO_MALLOC
4910
0
    byte* buf = NULL;
4911
#else
4912
    /* RSA_MAX_SIZE is the size of n in bits. */
4913
    byte buf[RSA_MAX_SIZE/16];
4914
#endif
4915
0
#endif /* !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 */
4916
0
    int err;
4917
4918
0
    if (key == NULL || rng == NULL) {
4919
0
        err = BAD_FUNC_ARG;
4920
0
        goto out;
4921
0
    }
4922
4923
0
    if (!RsaSizeCheck(size)) {
4924
0
        err = BAD_FUNC_ARG;
4925
0
        goto out;
4926
0
    }
4927
4928
0
    if (e < 3 || (e & 1) == 0) {
4929
0
        err = BAD_FUNC_ARG;
4930
0
        goto out;
4931
0
    }
4932
4933
#if defined(WOLFSSL_CRYPTOCELL)
4934
    err = cc310_RSA_GenerateKeyPair(key, size, e);
4935
    goto out;
4936
#elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
4937
    err = se050_rsa_create_key(key, size, e);
4938
    goto out;
4939
#else
4940
    /* software crypto */
4941
4942
0
#ifdef WOLFSSL_SMALL_STACK
4943
0
    p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
4944
0
    q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
4945
0
    tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
4946
0
    tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
4947
0
    tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
4948
4949
0
    if ((p == NULL) ||
4950
0
        (q == NULL) ||
4951
0
        (tmp1 == NULL) ||
4952
0
        (tmp2 == NULL) ||
4953
0
        (tmp3 == NULL)) {
4954
0
      err = MEMORY_E;
4955
0
      goto out;
4956
0
    }
4957
0
#endif
4958
#ifdef WOLFSSL_CHECK_MEM_ZERO
4959
    XMEMSET(p, 0, sizeof(*p));
4960
    XMEMSET(q, 0, sizeof(*q));
4961
    XMEMSET(tmp1, 0, sizeof(*tmp1));
4962
    XMEMSET(tmp2, 0, sizeof(*tmp2));
4963
    XMEMSET(tmp3, 0, sizeof(*tmp3));
4964
#endif
4965
4966
0
#ifdef WOLF_CRYPTO_CB
4967
0
    #ifndef WOLF_CRYPTO_CB_FIND
4968
0
    if (key->devId != INVALID_DEVID)
4969
0
    #endif
4970
0
    {
4971
0
        err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
4972
    #ifdef WOLF_CRYPTO_CB_ONLY_RSA
4973
        if (err == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4974
            err = NO_VALID_DEVID;
4975
            goto out;
4976
        }
4977
    #else
4978
0
        if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4979
0
            goto out;
4980
0
        }
4981
        /* fall-through when unavailable */
4982
0
    #endif
4983
0
    }
4984
    #if !defined(WOLF_CRYPTO_CB_FIND) && defined(WOLF_CRYPTO_CB_ONLY_RSA)
4985
    else {
4986
        err = NO_VALID_DEVID;
4987
    }
4988
    #endif
4989
0
#endif
4990
4991
0
#ifndef WOLF_CRYPTO_CB_ONLY_RSA
4992
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
4993
    defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
4994
    if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
4995
    #ifdef HAVE_CAVIUM
4996
        /* TODO: Not implemented */
4997
    #elif defined(HAVE_INTEL_QA)
4998
        err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
4999
        goto out;
5000
    #elif defined(WOLFSSL_ASYNC_CRYPT_SW)
5001
        if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_RSA_MAKE)) {
5002
            WC_ASYNC_SW* sw = &key->asyncDev.sw;
5003
            sw->rsaMake.rng = rng;
5004
            sw->rsaMake.key = key;
5005
            sw->rsaMake.size = size;
5006
            sw->rsaMake.e = e;
5007
            err = WC_PENDING_E;
5008
            goto out;
5009
        }
5010
    #endif
5011
    }
5012
#endif
5013
5014
0
    err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
5015
5016
0
    if (err == MP_OKAY)
5017
0
        err = mp_set_int(tmp3, (unsigned long)e);
5018
5019
    /* The failCount value comes from NIST FIPS 186-4, section B.3.3,
5020
     * process steps 4.7 and 5.8. */
5021
0
    failCount = 5 * (size / 2);
5022
0
    primeSz = (word32)size / 16; /* size is the size of n in bits.
5023
                            primeSz is in bytes. */
5024
5025
0
#ifndef WOLFSSL_NO_MALLOC
5026
    /* allocate buffer to work with */
5027
0
    if (err == MP_OKAY) {
5028
0
        buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
5029
0
        if (buf == NULL)
5030
0
            err = MEMORY_E;
5031
0
    }
5032
0
#endif
5033
5034
0
    SAVE_VECTOR_REGISTERS(err = _svr_ret;);
5035
5036
    /* make p */
5037
0
    if (err == MP_OKAY) {
5038
    #ifdef WOLFSSL_CHECK_MEM_ZERO
5039
        wc_MemZero_Add("RSA gen buf", buf, primeSz);
5040
        mp_memzero_add("RSA gen p", p);
5041
        mp_memzero_add("RSA gen q", q);
5042
        mp_memzero_add("RSA gen tmp1", tmp1);
5043
        mp_memzero_add("RSA gen tmp2", tmp2);
5044
        mp_memzero_add("RSA gen tmp3", tmp3);
5045
    #endif
5046
0
        isPrime = 0;
5047
0
        i = 0;
5048
0
        for (;;) {
5049
#ifdef SHOW_GEN
5050
            printf(".");
5051
            fflush(stdout);
5052
#endif
5053
            /* generate value */
5054
0
            err = wc_RNG_GenerateBlock(rng, buf, primeSz);
5055
0
            if (err == 0) {
5056
                /* prime lower bound has the MSB set, set it in candidate */
5057
0
                buf[0] |= 0x80;
5058
                /* make candidate odd */
5059
0
                buf[primeSz-1] |= 0x01;
5060
                /* load value */
5061
0
                err = mp_read_unsigned_bin(p, buf, primeSz);
5062
0
            }
5063
5064
0
            if (err == MP_OKAY)
5065
0
                err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
5066
5067
#ifdef HAVE_FIPS
5068
            i++;
5069
#else
5070
            /* Keep the old retry behavior in non-FIPS build. */
5071
0
#endif
5072
5073
0
            if (err != MP_OKAY || isPrime || i >= failCount)
5074
0
                break;
5075
5076
            /* linuxkm: release the kernel for a moment before iterating. */
5077
0
            RESTORE_VECTOR_REGISTERS();
5078
0
            SAVE_VECTOR_REGISTERS(err = _svr_ret; break;);
5079
0
        };
5080
0
    }
5081
5082
0
    if (err == MP_OKAY && !isPrime)
5083
0
        err = PRIME_GEN_E;
5084
5085
    /* make q */
5086
0
    if (err == MP_OKAY) {
5087
0
        isPrime = 0;
5088
0
        i = 0;
5089
0
        do {
5090
#ifdef SHOW_GEN
5091
            printf(".");
5092
            fflush(stdout);
5093
#endif
5094
            /* generate value */
5095
0
            err = wc_RNG_GenerateBlock(rng, buf, primeSz);
5096
0
            if (err == 0) {
5097
                /* prime lower bound has the MSB set, set it in candidate */
5098
0
                buf[0] |= 0x80;
5099
                /* make candidate odd */
5100
0
                buf[primeSz-1] |= 0x01;
5101
                /* load value */
5102
0
                err = mp_read_unsigned_bin(q, buf, primeSz);
5103
0
            }
5104
5105
0
            if (err == MP_OKAY)
5106
0
                err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
5107
5108
0
#ifndef WC_RSA_NO_FERMAT_CHECK
5109
0
            if (err == MP_OKAY && isPrime) {
5110
                /* Fermat's Factorization works when difference between p and q
5111
                 * is less than (conservatively):
5112
                 *     n^(1/4) + 32
5113
                 *  ~= 2^(bit count of n)^(1/4) + 32)
5114
                 *   = 2^((bit count of n)/4 + 32)
5115
                 */
5116
0
                err = mp_sub(p, q, tmp1);
5117
0
                if (err == MP_OKAY && mp_count_bits(tmp1) <= (size / 4) + 32) {
5118
0
                    isPrime = 0;
5119
0
                }
5120
0
            }
5121
0
#endif
5122
5123
#ifdef HAVE_FIPS
5124
            i++;
5125
#else
5126
            /* Keep the old retry behavior in non-FIPS build. */
5127
0
            (void)i;
5128
0
#endif
5129
0
        } while (err == MP_OKAY && !isPrime && i < failCount);
5130
0
    }
5131
5132
0
    if (err == MP_OKAY && !isPrime)
5133
0
        err = PRIME_GEN_E;
5134
5135
0
#ifndef WOLFSSL_NO_MALLOC
5136
0
    if (buf) {
5137
0
        ForceZero(buf, primeSz);
5138
0
        XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
5139
0
    }
5140
#else
5141
    ForceZero(buf, primeSz);
5142
#endif
5143
5144
0
    if (err == MP_OKAY && mp_cmp(p, q) < 0) {
5145
0
        err = mp_copy(p, tmp1);
5146
0
        if (err == MP_OKAY)
5147
0
            err = mp_copy(q, p);
5148
0
        if (err == MP_OKAY)
5149
0
            mp_copy(tmp1, q);
5150
0
    }
5151
5152
    /* Setup RsaKey buffers */
5153
0
    if (err == MP_OKAY)
5154
0
        err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
5155
0
    if (err == MP_OKAY)
5156
0
        err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
5157
5158
    /* Software Key Calculation */
5159
0
    if (err == MP_OKAY)                /* tmp1 = p-1 */
5160
0
        err = mp_sub_d(p, 1, tmp1);
5161
0
    if (err == MP_OKAY)                /* tmp2 = q-1 */
5162
0
        err = mp_sub_d(q, 1, tmp2);
5163
0
#ifdef WC_RSA_BLINDING
5164
0
    if (err == MP_OKAY)                /* tmp3 = order of n */
5165
0
        err = mp_mul(tmp1, tmp2, tmp3);
5166
#else
5167
    if (err == MP_OKAY)                /* tmp3 = lcm(p-1, q-1), last loop */
5168
        err = mp_lcm(tmp1, tmp2, tmp3);
5169
#endif
5170
    /* make key */
5171
0
    if (err == MP_OKAY)                /* key->e = e */
5172
0
        err = mp_set_int(&key->e, (unsigned long)e);
5173
0
#ifdef WC_RSA_BLINDING
5174
    /* Blind the inverse operation with a value that is invertable */
5175
0
    if (err == MP_OKAY) {
5176
0
        do {
5177
0
            err = mp_rand(&key->p, mp_get_digit_count(tmp3), rng);
5178
0
            if (err == MP_OKAY)
5179
0
                err = mp_set_bit(&key->p, 0);
5180
0
            if (err == MP_OKAY)
5181
0
                err = mp_set_bit(&key->p, size - 1);
5182
0
            if (err == MP_OKAY)
5183
0
                err = mp_gcd(&key->p, tmp3, &key->q);
5184
0
        }
5185
0
        while ((err == MP_OKAY) && !mp_isone(&key->q));
5186
0
    }
5187
    /* 8/16-bit word size requires a full multiply when e=0x10001 */
5188
0
    if (err == MP_OKAY)
5189
0
        err = mp_mul(&key->p, &key->e, &key->e);
5190
0
#endif
5191
0
    if (err == MP_OKAY)                /* key->d = 1/e mod lcm(p-1, q-1) */
5192
0
        err = mp_invmod(&key->e, tmp3, &key->d);
5193
0
#ifdef WC_RSA_BLINDING
5194
    /* Take off blinding from d and reset e */
5195
0
    if (err == MP_OKAY)
5196
0
        err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
5197
0
    if (err == MP_OKAY)
5198
0
        err = mp_set_int(&key->e, (unsigned long)e);
5199
0
#endif
5200
0
    if (err == MP_OKAY)                /* key->n = pq */
5201
0
        err = mp_mul(p, q, &key->n);
5202
0
    if (err == MP_OKAY)                /* key->dP = d mod(p-1) */
5203
0
        err = mp_mod(&key->d, tmp1, &key->dP);
5204
0
    if (err == MP_OKAY)                /* key->dQ = d mod(q-1) */
5205
0
        err = mp_mod(&key->d, tmp2, &key->dQ);
5206
#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
5207
    if (err == MP_OKAY)                /* key->u = 1/q mod p */
5208
        err = mp_invmod(q, p, &key->u);
5209
#else
5210
0
    if (err == MP_OKAY)
5211
0
        err = mp_sub_d(p, 2, tmp3);
5212
0
    if (err == MP_OKAY)                /* key->u = 1/q mod p = q^p-2 mod p */
5213
0
        err = mp_exptmod(q, tmp3, p, &key->u);
5214
0
#endif
5215
0
    if (err == MP_OKAY)
5216
0
        err = mp_copy(p, &key->p);
5217
0
    if (err == MP_OKAY)
5218
0
        err = mp_copy(q, &key->q);
5219
5220
#ifdef HAVE_WOLF_BIGINT
5221
    /* make sure raw unsigned bin version is available */
5222
    if (err == MP_OKAY)
5223
         err = wc_mp_to_bigint(&key->n, &key->n.raw);
5224
    if (err == MP_OKAY)
5225
         err = wc_mp_to_bigint(&key->e, &key->e.raw);
5226
    if (err == MP_OKAY)
5227
         err = wc_mp_to_bigint(&key->d, &key->d.raw);
5228
    if (err == MP_OKAY)
5229
         err = wc_mp_to_bigint(&key->p, &key->p.raw);
5230
    if (err == MP_OKAY)
5231
         err = wc_mp_to_bigint(&key->q, &key->q.raw);
5232
    if (err == MP_OKAY)
5233
         err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
5234
    if (err == MP_OKAY)
5235
         err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
5236
    if (err == MP_OKAY)
5237
         err = wc_mp_to_bigint(&key->u, &key->u.raw);
5238
#endif
5239
5240
0
    if (err == MP_OKAY)
5241
0
        key->type = RSA_PRIVATE;
5242
5243
#ifdef WOLFSSL_CHECK_MEM_ZERO
5244
    if (err == MP_OKAY) {
5245
        mp_memzero_add("Make RSA key d", &key->d);
5246
        mp_memzero_add("Make RSA key p", &key->p);
5247
        mp_memzero_add("Make RSA key q", &key->q);
5248
        mp_memzero_add("Make RSA key dP", &key->dP);
5249
        mp_memzero_add("Make RSA key dQ", &key->dQ);
5250
        mp_memzero_add("Make RSA key u", &key->u);
5251
    }
5252
#endif
5253
5254
0
    if (err != WC_NO_ERR_TRACE(WC_ACCEL_INHIBIT_E))
5255
0
        RESTORE_VECTOR_REGISTERS();
5256
5257
    /* Last value p - 1. */
5258
0
    mp_forcezero(tmp1);
5259
    /* Last value q - 1. */
5260
0
    mp_forcezero(tmp2);
5261
    /* Last value p - 2. */
5262
0
    mp_forcezero(tmp3);
5263
0
    mp_forcezero(p);
5264
0
    mp_forcezero(q);
5265
5266
0
#ifdef WOLFSSL_RSA_KEY_CHECK
5267
    /* Perform the pair-wise consistency test on the new key. */
5268
0
    if (err == 0)
5269
0
        err = _ifc_pairwise_consistency_test(key, rng);
5270
0
#endif
5271
5272
0
    if (err != 0) {
5273
0
        wc_FreeRsaKey(key);
5274
0
        goto out;
5275
0
    }
5276
5277
#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
5278
    if (wc_InitRsaHw(key) != 0) {
5279
        return BAD_STATE_E;
5280
    }
5281
#endif
5282
5283
0
    err = 0;
5284
0
#endif /* WOLF_CRYPTO_CB_ONLY_RSA */
5285
0
#endif /* WOLFSSL_CRYPTOCELL / SW only */
5286
0
  out:
5287
5288
0
#if !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SE050)
5289
0
#ifdef WOLFSSL_SMALL_STACK
5290
0
    if (key != NULL) {
5291
0
        XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
5292
0
        XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
5293
0
        XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
5294
0
        XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
5295
0
        XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
5296
0
    }
5297
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
5298
    mp_memzero_check(p);
5299
    mp_memzero_check(q);
5300
    mp_memzero_check(tmp1);
5301
    mp_memzero_check(tmp2);
5302
    mp_memzero_check(tmp3);
5303
#endif /* WOLFSSL_SMALL_STACK */
5304
0
#endif /* !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 */
5305
5306
0
    return err;
5307
5308
#else
5309
    return NOT_COMPILED_IN;
5310
#endif
5311
0
}
5312
#endif /* !FIPS || FIPS_VER >= 2 */
5313
#endif /* WOLFSSL_KEY_GEN */
5314
5315
#ifndef WC_NO_RNG
5316
int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
5317
716
{
5318
716
    if (key == NULL || rng == NULL)
5319
0
        return BAD_FUNC_ARG;
5320
5321
716
    key->rng = rng;
5322
5323
716
    return 0;
5324
716
}
5325
#endif /* !WC_NO_RNG */
5326
5327
#ifdef WC_RSA_NONBLOCK
5328
int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
5329
{
5330
    if (key == NULL)
5331
        return BAD_FUNC_ARG;
5332
5333
    if (nb) {
5334
        XMEMSET(nb, 0, sizeof(RsaNb));
5335
    }
5336
5337
    /* Allow nb == NULL to clear non-block mode */
5338
    key->nb = nb;
5339
5340
    return 0;
5341
}
5342
#ifdef WC_RSA_NONBLOCK_TIME
5343
int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
5344
{
5345
    if (key == NULL || key->nb == NULL) {
5346
        return BAD_FUNC_ARG;
5347
    }
5348
5349
    /* calculate maximum number of instructions to block */
5350
    key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
5351
5352
    return 0;
5353
}
5354
#endif /* WC_RSA_NONBLOCK_TIME */
5355
#endif /* WC_RSA_NONBLOCK */
5356
5357
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
5358
5359
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
5360
/*
5361
 * Calculate  y = d mod(x-1)
5362
 */
5363
static int CalcDX(mp_int* y, mp_int* x, mp_int* d)
5364
0
{
5365
0
    int err;
5366
#ifndef WOLFSSL_SMALL_STACK
5367
    mp_int  m[1];
5368
#else
5369
0
    mp_int* m = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5370
0
    if (m == NULL)
5371
0
        return MEMORY_E;
5372
0
#endif
5373
5374
0
    err = mp_init(m);
5375
0
    if (err == MP_OKAY) {
5376
0
        err = mp_sub_d(x, 1, m);
5377
0
        if (err == MP_OKAY)
5378
0
            err = mp_mod(d, m, y);
5379
0
        mp_forcezero(m);
5380
0
    }
5381
5382
0
    WC_FREE_VAR_EX(m, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5383
5384
0
    return err;
5385
0
}
5386
#endif
5387
5388
int wc_RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz,
5389
        const byte* e, word32 eSz, const byte* d, word32 dSz,
5390
        const byte* u, word32 uSz, const byte* p, word32 pSz,
5391
        const byte* q, word32 qSz, const byte* dP, word32 dPSz,
5392
        const byte* dQ, word32 dQSz, RsaKey* key)
5393
0
{
5394
0
    int err = MP_OKAY;
5395
5396
0
    if (n == NULL || nSz == 0 || e == NULL || eSz == 0
5397
0
            || d == NULL || dSz == 0 || p == NULL || pSz == 0
5398
0
            || q == NULL || qSz == 0 || key == NULL) {
5399
0
        err = BAD_FUNC_ARG;
5400
0
    }
5401
5402
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
5403
0
    if (err == MP_OKAY) {
5404
0
        if ((u == NULL || uSz == 0)
5405
0
                || (dP != NULL && dPSz == 0)
5406
0
                || (dQ != NULL && dQSz == 0)) {
5407
0
            err = BAD_FUNC_ARG;
5408
0
        }
5409
0
    }
5410
#else
5411
    (void)u;
5412
    (void)uSz;
5413
    (void)dP;
5414
    (void)dPSz;
5415
    (void)dQ;
5416
    (void)dQSz;
5417
#endif
5418
5419
0
    if (err == MP_OKAY)
5420
0
        err = mp_read_unsigned_bin(&key->n, n, nSz);
5421
0
    if (err == MP_OKAY)
5422
0
        err = mp_read_unsigned_bin(&key->e, e, eSz);
5423
0
    if (err == MP_OKAY)
5424
0
        err = mp_read_unsigned_bin(&key->d, d, dSz);
5425
0
    if (err == MP_OKAY)
5426
0
        err = mp_read_unsigned_bin(&key->p, p, pSz);
5427
0
    if (err == MP_OKAY)
5428
0
        err = mp_read_unsigned_bin(&key->q, q, qSz);
5429
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
5430
0
    if (err == MP_OKAY)
5431
0
        err = mp_read_unsigned_bin(&key->u, u, uSz);
5432
0
    if (err == MP_OKAY) {
5433
0
        if (dP != NULL)
5434
0
            err = mp_read_unsigned_bin(&key->dP, dP, dPSz);
5435
0
        else
5436
0
            err = CalcDX(&key->dP, &key->p, &key->d);
5437
0
    }
5438
0
    if (err == MP_OKAY) {
5439
0
        if (dQ != NULL)
5440
0
            err = mp_read_unsigned_bin(&key->dQ, dQ, dQSz);
5441
0
        else
5442
0
            err = CalcDX(&key->dQ, &key->q, &key->d);
5443
0
    }
5444
0
#endif
5445
5446
0
    if (err == MP_OKAY) {
5447
0
        key->type = RSA_PRIVATE;
5448
0
    }
5449
0
    else if (key != NULL) {
5450
0
        mp_clear(&key->n);
5451
0
        mp_clear(&key->e);
5452
0
        mp_forcezero(&key->d);
5453
0
        mp_forcezero(&key->p);
5454
0
        mp_forcezero(&key->q);
5455
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
5456
0
        mp_forcezero(&key->u);
5457
0
        mp_forcezero(&key->dP);
5458
0
        mp_forcezero(&key->dQ);
5459
0
#endif
5460
0
    }
5461
5462
0
    return err;
5463
0
}
5464
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
5465
5466
#endif /* NO_RSA */