Coverage Report

Created: 2025-07-01 06:54

/work/mbedtls-2.28.8/library/rsa.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  The RSA public-key cryptosystem
3
 *
4
 *  Copyright The Mbed TLS Contributors
5
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6
 */
7
8
/*
9
 *  The following sources were referenced in the design of this implementation
10
 *  of the RSA algorithm:
11
 *
12
 *  [1] A method for obtaining digital signatures and public-key cryptosystems
13
 *      R Rivest, A Shamir, and L Adleman
14
 *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
15
 *
16
 *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
17
 *      Menezes, van Oorschot and Vanstone
18
 *
19
 *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
20
 *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
21
 *      Stefan Mangard
22
 *      https://arxiv.org/abs/1702.08719v2
23
 *
24
 */
25
26
#include "common.h"
27
28
#if defined(MBEDTLS_RSA_C)
29
30
#include "mbedtls/rsa.h"
31
#include "mbedtls/rsa_internal.h"
32
#include "mbedtls/oid.h"
33
#include "mbedtls/platform_util.h"
34
#include "mbedtls/error.h"
35
#include "constant_time_internal.h"
36
#include "mbedtls/constant_time.h"
37
#include "bignum_internal.h"
38
39
#include <string.h>
40
41
#if defined(MBEDTLS_PKCS1_V21)
42
#include "mbedtls/md.h"
43
#endif
44
45
#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
46
#include <stdlib.h>
47
#endif
48
49
#include "mbedtls/platform.h"
50
51
#if !defined(MBEDTLS_RSA_ALT)
52
53
/* Parameter validation macros */
54
#define RSA_VALIDATE_RET(cond)                                       \
55
0
    MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_RSA_BAD_INPUT_DATA)
56
#define RSA_VALIDATE(cond)                                           \
57
0
    MBEDTLS_INTERNAL_VALIDATE(cond)
58
59
int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
60
                       const mbedtls_mpi *N,
61
                       const mbedtls_mpi *P, const mbedtls_mpi *Q,
62
                       const mbedtls_mpi *D, const mbedtls_mpi *E)
63
0
{
64
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
65
0
    RSA_VALIDATE_RET(ctx != NULL);
66
67
0
    if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
68
0
        (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
69
0
        (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
70
0
        (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
71
0
        (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
72
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
73
0
    }
74
75
0
    if (N != NULL) {
76
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
77
0
    }
78
79
0
    return 0;
80
0
}
81
82
int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
83
                           unsigned char const *N, size_t N_len,
84
                           unsigned char const *P, size_t P_len,
85
                           unsigned char const *Q, size_t Q_len,
86
                           unsigned char const *D, size_t D_len,
87
                           unsigned char const *E, size_t E_len)
88
0
{
89
0
    int ret = 0;
90
0
    RSA_VALIDATE_RET(ctx != NULL);
91
92
0
    if (N != NULL) {
93
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
94
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
95
0
    }
96
97
0
    if (P != NULL) {
98
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
99
0
    }
100
101
0
    if (Q != NULL) {
102
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
103
0
    }
104
105
0
    if (D != NULL) {
106
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
107
0
    }
108
109
0
    if (E != NULL) {
110
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
111
0
    }
112
113
0
cleanup:
114
115
0
    if (ret != 0) {
116
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
117
0
    }
118
119
0
    return 0;
120
0
}
121
122
/*
123
 * Checks whether the context fields are set in such a way
124
 * that the RSA primitives will be able to execute without error.
125
 * It does *not* make guarantees for consistency of the parameters.
126
 */
127
static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
128
                             int blinding_needed)
129
0
{
130
0
#if !defined(MBEDTLS_RSA_NO_CRT)
131
    /* blinding_needed is only used for NO_CRT to decide whether
132
     * P,Q need to be present or not. */
133
0
    ((void) blinding_needed);
134
0
#endif
135
136
0
    if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
137
0
        ctx->len > MBEDTLS_MPI_MAX_SIZE) {
138
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
139
0
    }
140
141
    /*
142
     * 1. Modular exponentiation needs positive, odd moduli.
143
     */
144
145
    /* Modular exponentiation wrt. N is always used for
146
     * RSA public key operations. */
147
0
    if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
148
0
        mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
149
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
150
0
    }
151
152
0
#if !defined(MBEDTLS_RSA_NO_CRT)
153
    /* Modular exponentiation for P and Q is only
154
     * used for private key operations and if CRT
155
     * is used. */
156
0
    if (is_priv &&
157
0
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
158
0
         mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
159
0
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
160
0
         mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
161
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
162
0
    }
163
0
#endif /* !MBEDTLS_RSA_NO_CRT */
164
165
    /*
166
     * 2. Exponents must be positive
167
     */
168
169
    /* Always need E for public key operations */
170
0
    if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
171
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
172
0
    }
173
174
#if defined(MBEDTLS_RSA_NO_CRT)
175
    /* For private key operations, use D or DP & DQ
176
     * as (unblinded) exponents. */
177
    if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
178
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
179
    }
180
#else
181
0
    if (is_priv &&
182
0
        (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
183
0
         mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
184
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
185
0
    }
186
0
#endif /* MBEDTLS_RSA_NO_CRT */
187
188
    /* Blinding shouldn't make exponents negative either,
189
     * so check that P, Q >= 1 if that hasn't yet been
190
     * done as part of 1. */
191
#if defined(MBEDTLS_RSA_NO_CRT)
192
    if (is_priv && blinding_needed &&
193
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
194
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
195
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
196
    }
197
#endif
198
199
    /* It wouldn't lead to an error if it wasn't satisfied,
200
     * but check for QP >= 1 nonetheless. */
201
0
#if !defined(MBEDTLS_RSA_NO_CRT)
202
0
    if (is_priv &&
203
0
        mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
204
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
205
0
    }
206
0
#endif
207
208
0
    return 0;
209
0
}
210
211
int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
212
0
{
213
0
    int ret = 0;
214
0
    int have_N, have_P, have_Q, have_D, have_E;
215
0
#if !defined(MBEDTLS_RSA_NO_CRT)
216
0
    int have_DP, have_DQ, have_QP;
217
0
#endif
218
0
    int n_missing, pq_missing, d_missing, is_pub, is_priv;
219
220
0
    RSA_VALIDATE_RET(ctx != NULL);
221
222
0
    have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
223
0
    have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
224
0
    have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
225
0
    have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
226
0
    have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
227
228
0
#if !defined(MBEDTLS_RSA_NO_CRT)
229
0
    have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
230
0
    have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
231
0
    have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
232
0
#endif
233
234
    /*
235
     * Check whether provided parameters are enough
236
     * to deduce all others. The following incomplete
237
     * parameter sets for private keys are supported:
238
     *
239
     * (1) P, Q missing.
240
     * (2) D and potentially N missing.
241
     *
242
     */
243
244
0
    n_missing  =              have_P &&  have_Q &&  have_D && have_E;
245
0
    pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
246
0
    d_missing  =              have_P &&  have_Q && !have_D && have_E;
247
0
    is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
248
249
    /* These three alternatives are mutually exclusive */
250
0
    is_priv = n_missing || pq_missing || d_missing;
251
252
0
    if (!is_priv && !is_pub) {
253
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
254
0
    }
255
256
    /*
257
     * Step 1: Deduce N if P, Q are provided.
258
     */
259
260
0
    if (!have_N && have_P && have_Q) {
261
0
        if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
262
0
                                       &ctx->Q)) != 0) {
263
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
264
0
        }
265
266
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
267
0
    }
268
269
    /*
270
     * Step 2: Deduce and verify all remaining core parameters.
271
     */
272
273
0
    if (pq_missing) {
274
0
        ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
275
0
                                        &ctx->P, &ctx->Q);
276
0
        if (ret != 0) {
277
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
278
0
        }
279
280
0
    } else if (d_missing) {
281
0
        if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
282
0
                                                       &ctx->Q,
283
0
                                                       &ctx->E,
284
0
                                                       &ctx->D)) != 0) {
285
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
286
0
        }
287
0
    }
288
289
    /*
290
     * Step 3: Deduce all additional parameters specific
291
     *         to our current RSA implementation.
292
     */
293
294
0
#if !defined(MBEDTLS_RSA_NO_CRT)
295
0
    if (is_priv && !(have_DP && have_DQ && have_QP)) {
296
0
        ret = mbedtls_rsa_deduce_crt(&ctx->P,  &ctx->Q,  &ctx->D,
297
0
                                     &ctx->DP, &ctx->DQ, &ctx->QP);
298
0
        if (ret != 0) {
299
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
300
0
        }
301
0
    }
302
0
#endif /* MBEDTLS_RSA_NO_CRT */
303
304
    /*
305
     * Step 3: Basic sanity checks
306
     */
307
308
0
    return rsa_check_context(ctx, is_priv, 1);
309
0
}
310
311
int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
312
                           unsigned char *N, size_t N_len,
313
                           unsigned char *P, size_t P_len,
314
                           unsigned char *Q, size_t Q_len,
315
                           unsigned char *D, size_t D_len,
316
                           unsigned char *E, size_t E_len)
317
0
{
318
0
    int ret = 0;
319
0
    int is_priv;
320
0
    RSA_VALIDATE_RET(ctx != NULL);
321
322
    /* Check if key is private or public */
323
0
    is_priv =
324
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
325
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
326
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
327
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
328
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
329
330
0
    if (!is_priv) {
331
        /* If we're trying to export private parameters for a public key,
332
         * something must be wrong. */
333
0
        if (P != NULL || Q != NULL || D != NULL) {
334
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
335
0
        }
336
337
0
    }
338
339
0
    if (N != NULL) {
340
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
341
0
    }
342
343
0
    if (P != NULL) {
344
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
345
0
    }
346
347
0
    if (Q != NULL) {
348
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
349
0
    }
350
351
0
    if (D != NULL) {
352
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
353
0
    }
354
355
0
    if (E != NULL) {
356
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
357
0
    }
358
359
0
cleanup:
360
361
0
    return ret;
362
0
}
363
364
int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
365
                       mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
366
                       mbedtls_mpi *D, mbedtls_mpi *E)
367
0
{
368
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
369
0
    int is_priv;
370
0
    RSA_VALIDATE_RET(ctx != NULL);
371
372
    /* Check if key is private or public */
373
0
    is_priv =
374
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
375
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
376
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
377
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
378
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
379
380
0
    if (!is_priv) {
381
        /* If we're trying to export private parameters for a public key,
382
         * something must be wrong. */
383
0
        if (P != NULL || Q != NULL || D != NULL) {
384
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
385
0
        }
386
387
0
    }
388
389
    /* Export all requested core parameters. */
390
391
0
    if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
392
0
        (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
393
0
        (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
394
0
        (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
395
0
        (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
396
0
        return ret;
397
0
    }
398
399
0
    return 0;
400
0
}
401
402
/*
403
 * Export CRT parameters
404
 * This must also be implemented if CRT is not used, for being able to
405
 * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
406
 * can be used in this case.
407
 */
408
int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
409
                           mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
410
0
{
411
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
412
0
    int is_priv;
413
0
    RSA_VALIDATE_RET(ctx != NULL);
414
415
    /* Check if key is private or public */
416
0
    is_priv =
417
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
418
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
419
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
420
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
421
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
422
423
0
    if (!is_priv) {
424
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
425
0
    }
426
427
0
#if !defined(MBEDTLS_RSA_NO_CRT)
428
    /* Export all requested blinding parameters. */
429
0
    if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
430
0
        (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
431
0
        (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
432
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
433
0
    }
434
#else
435
    if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
436
                                      DP, DQ, QP)) != 0) {
437
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
438
    }
439
#endif
440
441
0
    return 0;
442
0
}
443
444
/*
445
 * Initialize an RSA context
446
 */
447
void mbedtls_rsa_init(mbedtls_rsa_context *ctx,
448
                      int padding,
449
                      int hash_id)
450
0
{
451
0
    RSA_VALIDATE(ctx != NULL);
452
0
    RSA_VALIDATE(padding == MBEDTLS_RSA_PKCS_V15 ||
453
0
                 padding == MBEDTLS_RSA_PKCS_V21);
454
455
0
    memset(ctx, 0, sizeof(mbedtls_rsa_context));
456
457
0
    mbedtls_rsa_set_padding(ctx, padding, hash_id);
458
459
#if defined(MBEDTLS_THREADING_C)
460
    /* Set ctx->ver to nonzero to indicate that the mutex has been
461
     * initialized and will need to be freed. */
462
    ctx->ver = 1;
463
    mbedtls_mutex_init(&ctx->mutex);
464
#endif
465
0
}
466
467
/*
468
 * Set padding for an existing RSA context
469
 */
470
void mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
471
                             int hash_id)
472
0
{
473
0
    RSA_VALIDATE(ctx != NULL);
474
0
    RSA_VALIDATE(padding == MBEDTLS_RSA_PKCS_V15 ||
475
0
                 padding == MBEDTLS_RSA_PKCS_V21);
476
477
0
    ctx->padding = padding;
478
0
    ctx->hash_id = hash_id;
479
0
}
480
481
/*
482
 * Get length in bytes of RSA modulus
483
 */
484
485
size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
486
0
{
487
0
    return ctx->len;
488
0
}
489
490
491
#if defined(MBEDTLS_GENPRIME)
492
493
/*
494
 * Generate an RSA keypair
495
 *
496
 * This generation method follows the RSA key pair generation procedure of
497
 * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
498
 */
499
int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
500
                        int (*f_rng)(void *, unsigned char *, size_t),
501
                        void *p_rng,
502
                        unsigned int nbits, int exponent)
503
0
{
504
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
505
0
    mbedtls_mpi H, G, L;
506
0
    int prime_quality = 0;
507
0
    RSA_VALIDATE_RET(ctx != NULL);
508
0
    RSA_VALIDATE_RET(f_rng != NULL);
509
510
    /*
511
     * If the modulus is 1024 bit long or shorter, then the security strength of
512
     * the RSA algorithm is less than or equal to 80 bits and therefore an error
513
     * rate of 2^-80 is sufficient.
514
     */
515
0
    if (nbits > 1024) {
516
0
        prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
517
0
    }
518
519
0
    mbedtls_mpi_init(&H);
520
0
    mbedtls_mpi_init(&G);
521
0
    mbedtls_mpi_init(&L);
522
523
0
    if (nbits < 128 || exponent < 3 || nbits % 2 != 0) {
524
0
        ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
525
0
        goto cleanup;
526
0
    }
527
528
    /*
529
     * find primes P and Q with Q < P so that:
530
     * 1.  |P-Q| > 2^( nbits / 2 - 100 )
531
     * 2.  GCD( E, (P-1)*(Q-1) ) == 1
532
     * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
533
     */
534
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
535
536
0
    do {
537
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
538
0
                                              prime_quality, f_rng, p_rng));
539
540
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
541
0
                                              prime_quality, f_rng, p_rng));
542
543
        /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
544
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
545
0
        if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
546
0
            continue;
547
0
        }
548
549
        /* not required by any standards, but some users rely on the fact that P > Q */
550
0
        if (H.s < 0) {
551
0
            mbedtls_mpi_swap(&ctx->P, &ctx->Q);
552
0
        }
553
554
        /* Temporarily replace P,Q by P-1, Q-1 */
555
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
556
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
557
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
558
559
        /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
560
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
561
0
        if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
562
0
            continue;
563
0
        }
564
565
        /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
566
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
567
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
568
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
569
570
0
        if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {      // (FIPS 186-4 §B.3.1 criterion 3(a))
571
0
            continue;
572
0
        }
573
574
0
        break;
575
0
    } while (1);
576
577
    /* Restore P,Q */
578
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P,  &ctx->P, 1));
579
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q,  &ctx->Q, 1));
580
581
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
582
583
0
    ctx->len = mbedtls_mpi_size(&ctx->N);
584
585
0
#if !defined(MBEDTLS_RSA_NO_CRT)
586
    /*
587
     * DP = D mod (P - 1)
588
     * DQ = D mod (Q - 1)
589
     * QP = Q^-1 mod P
590
     */
591
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
592
0
                                           &ctx->DP, &ctx->DQ, &ctx->QP));
593
0
#endif /* MBEDTLS_RSA_NO_CRT */
594
595
    /* Double-check */
596
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
597
598
0
cleanup:
599
600
0
    mbedtls_mpi_free(&H);
601
0
    mbedtls_mpi_free(&G);
602
0
    mbedtls_mpi_free(&L);
603
604
0
    if (ret != 0) {
605
0
        mbedtls_rsa_free(ctx);
606
607
0
        if ((-ret & ~0x7f) == 0) {
608
0
            ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
609
0
        }
610
0
        return ret;
611
0
    }
612
613
0
    return 0;
614
0
}
615
616
#endif /* MBEDTLS_GENPRIME */
617
618
/*
619
 * Check a public RSA key
620
 */
621
int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
622
0
{
623
0
    RSA_VALIDATE_RET(ctx != NULL);
624
625
0
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
626
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
627
0
    }
628
629
0
    if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
630
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
631
0
    }
632
633
0
    if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
634
0
        mbedtls_mpi_bitlen(&ctx->E)     < 2  ||
635
0
        mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
636
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
637
0
    }
638
639
0
    return 0;
640
0
}
641
642
/*
643
 * Check for the consistency of all fields in an RSA private key context
644
 */
645
int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
646
0
{
647
0
    RSA_VALIDATE_RET(ctx != NULL);
648
649
0
    if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
650
0
        rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
651
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
652
0
    }
653
654
0
    if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
655
0
                                    &ctx->D, &ctx->E, NULL, NULL) != 0) {
656
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
657
0
    }
658
659
0
#if !defined(MBEDTLS_RSA_NO_CRT)
660
0
    else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
661
0
                                      &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
662
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
663
0
    }
664
0
#endif
665
666
0
    return 0;
667
0
}
668
669
/*
670
 * Check if contexts holding a public and private key match
671
 */
672
int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
673
                               const mbedtls_rsa_context *prv)
674
0
{
675
0
    RSA_VALIDATE_RET(pub != NULL);
676
0
    RSA_VALIDATE_RET(prv != NULL);
677
678
0
    if (mbedtls_rsa_check_pubkey(pub)  != 0 ||
679
0
        mbedtls_rsa_check_privkey(prv) != 0) {
680
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
681
0
    }
682
683
0
    if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
684
0
        mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
685
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
686
0
    }
687
688
0
    return 0;
689
0
}
690
691
/*
692
 * Do an RSA public key operation
693
 */
694
int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
695
                       const unsigned char *input,
696
                       unsigned char *output)
697
0
{
698
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
699
0
    size_t olen;
700
0
    mbedtls_mpi T;
701
0
    RSA_VALIDATE_RET(ctx != NULL);
702
0
    RSA_VALIDATE_RET(input != NULL);
703
0
    RSA_VALIDATE_RET(output != NULL);
704
705
0
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
706
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
707
0
    }
708
709
0
    mbedtls_mpi_init(&T);
710
711
#if defined(MBEDTLS_THREADING_C)
712
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
713
        return ret;
714
    }
715
#endif
716
717
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
718
719
0
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
720
0
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
721
0
        goto cleanup;
722
0
    }
723
724
0
    olen = ctx->len;
725
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
726
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
727
728
0
cleanup:
729
#if defined(MBEDTLS_THREADING_C)
730
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
731
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
732
    }
733
#endif
734
735
0
    mbedtls_mpi_free(&T);
736
737
0
    if (ret != 0) {
738
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
739
0
    }
740
741
0
    return 0;
742
0
}
743
744
/*
745
 * Generate or update blinding values, see section 10 of:
746
 *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
747
 *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
748
 *  Berlin Heidelberg, 1996. p. 104-113.
749
 */
750
static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
751
                                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
752
0
{
753
0
    int ret, count = 0;
754
0
    mbedtls_mpi R;
755
756
0
    mbedtls_mpi_init(&R);
757
758
0
    if (ctx->Vf.p != NULL) {
759
        /* We already have blinding values, just update them by squaring */
760
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
761
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
762
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
763
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
764
765
0
        goto cleanup;
766
0
    }
767
768
    /* Unblinding value: Vf = random number, invertible mod N */
769
0
    do {
770
0
        if (count++ > 10) {
771
0
            ret = MBEDTLS_ERR_RSA_RNG_FAILED;
772
0
            goto cleanup;
773
0
        }
774
775
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
776
777
        /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
778
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
779
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
780
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
781
782
        /* At this point, Vi is invertible mod N if and only if both Vf and R
783
         * are invertible mod N. If one of them isn't, we don't need to know
784
         * which one, we just loop and choose new values for both of them.
785
         * (Each iteration succeeds with overwhelming probability.) */
786
0
        ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
787
0
        if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
788
0
            goto cleanup;
789
0
        }
790
791
0
    } while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
792
793
    /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
794
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
795
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
796
797
    /* Blinding value: Vi = Vf^(-e) mod N
798
     * (Vi already contains Vf^-1 at this point) */
799
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
800
801
802
0
cleanup:
803
0
    mbedtls_mpi_free(&R);
804
805
0
    return ret;
806
0
}
807
808
/*
809
 * Unblind
810
 * T = T * Vf mod N
811
 */
812
static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
813
0
{
814
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
815
0
    const size_t nlimbs = N->n;
816
0
    const size_t tlimbs = 2 * (nlimbs + 1);
817
818
0
    mbedtls_mpi_uint mm = mbedtls_mpi_montmul_init(N->p);
819
820
0
    mbedtls_mpi RR, M_T;
821
822
0
    mbedtls_mpi_init(&RR);
823
0
    mbedtls_mpi_init(&M_T);
824
825
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_get_mont_r2_unsafe(&RR, N));
826
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
827
828
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
829
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
830
831
    /* T = T * Vf mod N
832
     * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
833
     * Usually both operands are multiplied by R mod N beforehand, yielding a
834
     * result that's also * R mod N (aka "in the Montgomery domain"). Here we
835
     * only multiply one operand by R mod N, so the result is directly what we
836
     * want - no need to call `mpi_montred()` on it. */
837
0
    mbedtls_mpi_montmul(T, &RR, N, mm, &M_T);
838
0
    mbedtls_mpi_montmul(T, Vf, N, mm, &M_T);
839
840
0
cleanup:
841
842
0
    mbedtls_mpi_free(&RR);
843
0
    mbedtls_mpi_free(&M_T);
844
845
0
    return ret;
846
0
}
847
848
/*
849
 * Exponent blinding supposed to prevent side-channel attacks using multiple
850
 * traces of measurements to recover the RSA key. The more collisions are there,
851
 * the more bits of the key can be recovered. See [3].
852
 *
853
 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
854
 * observations on average.
855
 *
856
 * For example with 28 byte blinding to achieve 2 collisions the adversary has
857
 * to make 2^112 observations on average.
858
 *
859
 * (With the currently (as of 2017 April) known best algorithms breaking 2048
860
 * bit RSA requires approximately as much time as trying out 2^112 random keys.
861
 * Thus in this sense with 28 byte blinding the security is not reduced by
862
 * side-channel attacks like the one in [3])
863
 *
864
 * This countermeasure does not help if the key recovery is possible with a
865
 * single trace.
866
 */
867
#define RSA_EXPONENT_BLINDING 28
868
869
/*
870
 * Do an RSA private key operation
871
 */
872
int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
873
                        int (*f_rng)(void *, unsigned char *, size_t),
874
                        void *p_rng,
875
                        const unsigned char *input,
876
                        unsigned char *output)
877
0
{
878
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
879
0
    size_t olen;
880
881
    /* Temporary holding the result */
882
0
    mbedtls_mpi T;
883
884
    /* Temporaries holding P-1, Q-1 and the
885
     * exponent blinding factor, respectively. */
886
0
    mbedtls_mpi P1, Q1, R;
887
888
0
#if !defined(MBEDTLS_RSA_NO_CRT)
889
    /* Temporaries holding the results mod p resp. mod q. */
890
0
    mbedtls_mpi TP, TQ;
891
892
    /* Temporaries holding the blinded exponents for
893
     * the mod p resp. mod q computation (if used). */
894
0
    mbedtls_mpi DP_blind, DQ_blind;
895
896
    /* Pointers to actual exponents to be used - either the unblinded
897
     * or the blinded ones, depending on the presence of a PRNG. */
898
0
    mbedtls_mpi *DP = &ctx->DP;
899
0
    mbedtls_mpi *DQ = &ctx->DQ;
900
#else
901
    /* Temporary holding the blinded exponent (if used). */
902
    mbedtls_mpi D_blind;
903
904
    /* Pointer to actual exponent to be used - either the unblinded
905
     * or the blinded one, depending on the presence of a PRNG. */
906
    mbedtls_mpi *D = &ctx->D;
907
#endif /* MBEDTLS_RSA_NO_CRT */
908
909
    /* Temporaries holding the initial input and the double
910
     * checked result; should be the same in the end. */
911
0
    mbedtls_mpi input_blinded, check_result_blinded;
912
913
0
    RSA_VALIDATE_RET(ctx != NULL);
914
0
    RSA_VALIDATE_RET(input  != NULL);
915
0
    RSA_VALIDATE_RET(output != NULL);
916
917
0
    if (rsa_check_context(ctx, 1 /* private key checks */,
918
0
                          f_rng != NULL /* blinding y/n       */) != 0) {
919
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
920
0
    }
921
922
#if defined(MBEDTLS_THREADING_C)
923
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
924
        return ret;
925
    }
926
#endif
927
928
    /* MPI Initialization */
929
0
    mbedtls_mpi_init(&T);
930
931
0
    mbedtls_mpi_init(&P1);
932
0
    mbedtls_mpi_init(&Q1);
933
0
    mbedtls_mpi_init(&R);
934
935
0
    if (f_rng != NULL) {
936
#if defined(MBEDTLS_RSA_NO_CRT)
937
        mbedtls_mpi_init(&D_blind);
938
#else
939
0
        mbedtls_mpi_init(&DP_blind);
940
0
        mbedtls_mpi_init(&DQ_blind);
941
0
#endif
942
0
    }
943
944
0
#if !defined(MBEDTLS_RSA_NO_CRT)
945
0
    mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
946
0
#endif
947
948
0
    mbedtls_mpi_init(&input_blinded);
949
0
    mbedtls_mpi_init(&check_result_blinded);
950
951
    /* End of MPI initialization */
952
953
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
954
0
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
955
0
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
956
0
        goto cleanup;
957
0
    }
958
959
0
    if (f_rng != NULL) {
960
        /*
961
         * Blinding
962
         * T = T * Vi mod N
963
         */
964
0
        MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
965
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
966
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
967
968
        /*
969
         * Exponent blinding
970
         */
971
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
972
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
973
974
#if defined(MBEDTLS_RSA_NO_CRT)
975
        /*
976
         * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
977
         */
978
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
979
                                                f_rng, p_rng));
980
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
981
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
982
        MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
983
984
        D = &D_blind;
985
#else
986
        /*
987
         * DP_blind = ( P - 1 ) * R + DP
988
         */
989
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
990
0
                                                f_rng, p_rng));
991
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
992
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
993
0
                                            &ctx->DP));
994
995
0
        DP = &DP_blind;
996
997
        /*
998
         * DQ_blind = ( Q - 1 ) * R + DQ
999
         */
1000
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1001
0
                                                f_rng, p_rng));
1002
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
1003
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
1004
0
                                            &ctx->DQ));
1005
1006
0
        DQ = &DQ_blind;
1007
0
#endif /* MBEDTLS_RSA_NO_CRT */
1008
0
    }
1009
1010
    /* Make a copy of the input (after blinding if there was any) */
1011
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
1012
1013
#if defined(MBEDTLS_RSA_NO_CRT)
1014
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, D, &ctx->N, &ctx->RN));
1015
#else
1016
    /*
1017
     * Faster decryption using the CRT
1018
     *
1019
     * TP = input ^ dP mod P
1020
     * TQ = input ^ dQ mod Q
1021
     */
1022
1023
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, DP, &ctx->P, &ctx->RP));
1024
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, DQ, &ctx->Q, &ctx->RQ));
1025
1026
    /*
1027
     * T = (TP - TQ) * (Q^-1 mod P) mod P
1028
     */
1029
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
1030
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
1031
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
1032
1033
    /*
1034
     * T = TQ + T * Q
1035
     */
1036
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1037
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1038
0
#endif /* MBEDTLS_RSA_NO_CRT */
1039
1040
    /* Verify the result to prevent glitching attacks. */
1041
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
1042
0
                                        &ctx->N, &ctx->RN));
1043
0
    if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
1044
0
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1045
0
        goto cleanup;
1046
0
    }
1047
1048
0
    if (f_rng != NULL) {
1049
        /*
1050
         * Unblind
1051
         * T = T * Vf mod N
1052
         */
1053
0
        MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
1054
0
    }
1055
1056
0
    olen = ctx->len;
1057
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1058
1059
0
cleanup:
1060
#if defined(MBEDTLS_THREADING_C)
1061
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1062
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1063
    }
1064
#endif
1065
1066
0
    mbedtls_mpi_free(&P1);
1067
0
    mbedtls_mpi_free(&Q1);
1068
0
    mbedtls_mpi_free(&R);
1069
1070
0
    if (f_rng != NULL) {
1071
#if defined(MBEDTLS_RSA_NO_CRT)
1072
        mbedtls_mpi_free(&D_blind);
1073
#else
1074
0
        mbedtls_mpi_free(&DP_blind);
1075
0
        mbedtls_mpi_free(&DQ_blind);
1076
0
#endif
1077
0
    }
1078
1079
0
    mbedtls_mpi_free(&T);
1080
1081
0
#if !defined(MBEDTLS_RSA_NO_CRT)
1082
0
    mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1083
0
#endif
1084
1085
0
    mbedtls_mpi_free(&check_result_blinded);
1086
0
    mbedtls_mpi_free(&input_blinded);
1087
1088
0
    if (ret != 0 && ret >= -0x007f) {
1089
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1090
0
    }
1091
1092
0
    return ret;
1093
0
}
1094
1095
#if defined(MBEDTLS_PKCS1_V21)
1096
/**
1097
 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1098
 *
1099
 * \param dst       buffer to mask
1100
 * \param dlen      length of destination buffer
1101
 * \param src       source of the mask generation
1102
 * \param slen      length of the source buffer
1103
 * \param md_ctx    message digest context to use
1104
 */
1105
static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1106
                    size_t slen, mbedtls_md_context_t *md_ctx)
1107
0
{
1108
0
    unsigned char mask[MBEDTLS_MD_MAX_SIZE];
1109
0
    unsigned char counter[4];
1110
0
    unsigned char *p;
1111
0
    unsigned int hlen;
1112
0
    size_t i, use_len;
1113
0
    int ret = 0;
1114
1115
0
    memset(mask, 0, MBEDTLS_MD_MAX_SIZE);
1116
0
    memset(counter, 0, 4);
1117
1118
0
    hlen = mbedtls_md_get_size(md_ctx->md_info);
1119
1120
    /* Generate and apply dbMask */
1121
0
    p = dst;
1122
1123
0
    while (dlen > 0) {
1124
0
        use_len = hlen;
1125
0
        if (dlen < hlen) {
1126
0
            use_len = dlen;
1127
0
        }
1128
1129
0
        if ((ret = mbedtls_md_starts(md_ctx)) != 0) {
1130
0
            goto exit;
1131
0
        }
1132
0
        if ((ret = mbedtls_md_update(md_ctx, src, slen)) != 0) {
1133
0
            goto exit;
1134
0
        }
1135
0
        if ((ret = mbedtls_md_update(md_ctx, counter, 4)) != 0) {
1136
0
            goto exit;
1137
0
        }
1138
0
        if ((ret = mbedtls_md_finish(md_ctx, mask)) != 0) {
1139
0
            goto exit;
1140
0
        }
1141
1142
0
        for (i = 0; i < use_len; ++i) {
1143
0
            *p++ ^= mask[i];
1144
0
        }
1145
1146
0
        counter[3]++;
1147
1148
0
        dlen -= use_len;
1149
0
    }
1150
1151
0
exit:
1152
0
    mbedtls_platform_zeroize(mask, sizeof(mask));
1153
1154
0
    return ret;
1155
0
}
1156
#endif /* MBEDTLS_PKCS1_V21 */
1157
1158
#if defined(MBEDTLS_PKCS1_V21)
1159
/*
1160
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1161
 */
1162
int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1163
                                   int (*f_rng)(void *, unsigned char *, size_t),
1164
                                   void *p_rng,
1165
                                   int mode,
1166
                                   const unsigned char *label, size_t label_len,
1167
                                   size_t ilen,
1168
                                   const unsigned char *input,
1169
                                   unsigned char *output)
1170
0
{
1171
0
    size_t olen;
1172
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1173
0
    unsigned char *p = output;
1174
0
    unsigned int hlen;
1175
0
    const mbedtls_md_info_t *md_info;
1176
0
    mbedtls_md_context_t md_ctx;
1177
1178
0
    RSA_VALIDATE_RET(ctx != NULL);
1179
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1180
0
                     mode == MBEDTLS_RSA_PUBLIC);
1181
0
    RSA_VALIDATE_RET(output != NULL);
1182
0
    RSA_VALIDATE_RET(ilen == 0 || input != NULL);
1183
0
    RSA_VALIDATE_RET(label_len == 0 || label != NULL);
1184
1185
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1186
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1187
0
    }
1188
1189
0
    if (f_rng == NULL) {
1190
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1191
0
    }
1192
1193
0
    md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id);
1194
0
    if (md_info == NULL) {
1195
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1196
0
    }
1197
1198
0
    olen = ctx->len;
1199
0
    hlen = mbedtls_md_get_size(md_info);
1200
1201
    /* first comparison checks for overflow */
1202
0
    if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1203
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1204
0
    }
1205
1206
0
    memset(output, 0, olen);
1207
1208
0
    *p++ = 0;
1209
1210
    /* Generate a random octet string seed */
1211
0
    if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1212
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1213
0
    }
1214
1215
0
    p += hlen;
1216
1217
    /* Construct DB */
1218
0
    if ((ret = mbedtls_md(md_info, label, label_len, p)) != 0) {
1219
0
        return ret;
1220
0
    }
1221
0
    p += hlen;
1222
0
    p += olen - 2 * hlen - 2 - ilen;
1223
0
    *p++ = 1;
1224
0
    if (ilen != 0) {
1225
0
        memcpy(p, input, ilen);
1226
0
    }
1227
1228
0
    mbedtls_md_init(&md_ctx);
1229
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1230
0
        goto exit;
1231
0
    }
1232
1233
    /* maskedDB: Apply dbMask to DB */
1234
0
    if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1235
0
                        &md_ctx)) != 0) {
1236
0
        goto exit;
1237
0
    }
1238
1239
    /* maskedSeed: Apply seedMask to seed */
1240
0
    if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1241
0
                        &md_ctx)) != 0) {
1242
0
        goto exit;
1243
0
    }
1244
1245
0
exit:
1246
0
    mbedtls_md_free(&md_ctx);
1247
1248
0
    if (ret != 0) {
1249
0
        return ret;
1250
0
    }
1251
1252
0
    return (mode == MBEDTLS_RSA_PUBLIC)
1253
0
            ? mbedtls_rsa_public(ctx, output, output)
1254
0
            : mbedtls_rsa_private(ctx, f_rng, p_rng, output, output);
1255
0
}
1256
#endif /* MBEDTLS_PKCS1_V21 */
1257
1258
#if defined(MBEDTLS_PKCS1_V15)
1259
/*
1260
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1261
 */
1262
int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1263
                                        int (*f_rng)(void *, unsigned char *, size_t),
1264
                                        void *p_rng,
1265
                                        int mode, size_t ilen,
1266
                                        const unsigned char *input,
1267
                                        unsigned char *output)
1268
0
{
1269
0
    size_t nb_pad, olen;
1270
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1271
0
    unsigned char *p = output;
1272
1273
0
    RSA_VALIDATE_RET(ctx != NULL);
1274
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1275
0
                     mode == MBEDTLS_RSA_PUBLIC);
1276
0
    RSA_VALIDATE_RET(output != NULL);
1277
0
    RSA_VALIDATE_RET(ilen == 0 || input != NULL);
1278
1279
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1280
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1281
0
    }
1282
1283
0
    olen = ctx->len;
1284
1285
    /* first comparison checks for overflow */
1286
0
    if (ilen + 11 < ilen || olen < ilen + 11) {
1287
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1288
0
    }
1289
1290
0
    nb_pad = olen - 3 - ilen;
1291
1292
0
    *p++ = 0;
1293
0
    if (mode == MBEDTLS_RSA_PUBLIC) {
1294
0
        if (f_rng == NULL) {
1295
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1296
0
        }
1297
1298
0
        *p++ = MBEDTLS_RSA_CRYPT;
1299
1300
0
        while (nb_pad-- > 0) {
1301
0
            int rng_dl = 100;
1302
1303
0
            do {
1304
0
                ret = f_rng(p_rng, p, 1);
1305
0
            } while (*p == 0 && --rng_dl && ret == 0);
1306
1307
            /* Check if RNG failed to generate data */
1308
0
            if (rng_dl == 0 || ret != 0) {
1309
0
                return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1310
0
            }
1311
1312
0
            p++;
1313
0
        }
1314
0
    } else {
1315
0
        *p++ = MBEDTLS_RSA_SIGN;
1316
1317
0
        while (nb_pad-- > 0) {
1318
0
            *p++ = 0xFF;
1319
0
        }
1320
0
    }
1321
1322
0
    *p++ = 0;
1323
0
    if (ilen != 0) {
1324
0
        memcpy(p, input, ilen);
1325
0
    }
1326
1327
0
    return (mode == MBEDTLS_RSA_PUBLIC)
1328
0
            ? mbedtls_rsa_public(ctx, output, output)
1329
0
            : mbedtls_rsa_private(ctx, f_rng, p_rng, output, output);
1330
0
}
1331
#endif /* MBEDTLS_PKCS1_V15 */
1332
1333
/*
1334
 * Add the message padding, then do an RSA operation
1335
 */
1336
int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1337
                              int (*f_rng)(void *, unsigned char *, size_t),
1338
                              void *p_rng,
1339
                              int mode, size_t ilen,
1340
                              const unsigned char *input,
1341
                              unsigned char *output)
1342
0
{
1343
0
    RSA_VALIDATE_RET(ctx != NULL);
1344
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1345
0
                     mode == MBEDTLS_RSA_PUBLIC);
1346
0
    RSA_VALIDATE_RET(output != NULL);
1347
0
    RSA_VALIDATE_RET(ilen == 0 || input != NULL);
1348
1349
0
    switch (ctx->padding) {
1350
0
#if defined(MBEDTLS_PKCS1_V15)
1351
0
        case MBEDTLS_RSA_PKCS_V15:
1352
0
            return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng, mode, ilen,
1353
0
                                                       input, output);
1354
0
#endif
1355
1356
0
#if defined(MBEDTLS_PKCS1_V21)
1357
0
        case MBEDTLS_RSA_PKCS_V21:
1358
0
            return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, mode, NULL, 0,
1359
0
                                                  ilen, input, output);
1360
0
#endif
1361
1362
0
        default:
1363
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
1364
0
    }
1365
0
}
1366
1367
#if defined(MBEDTLS_PKCS1_V21)
1368
/*
1369
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1370
 */
1371
int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1372
                                   int (*f_rng)(void *, unsigned char *, size_t),
1373
                                   void *p_rng,
1374
                                   int mode,
1375
                                   const unsigned char *label, size_t label_len,
1376
                                   size_t *olen,
1377
                                   const unsigned char *input,
1378
                                   unsigned char *output,
1379
                                   size_t output_max_len)
1380
0
{
1381
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1382
0
    size_t ilen, i, pad_len;
1383
0
    unsigned char *p, pad_done;
1384
0
    int bad;
1385
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1386
0
    unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
1387
0
    unsigned int hlen;
1388
0
    const mbedtls_md_info_t *md_info;
1389
0
    mbedtls_md_context_t md_ctx;
1390
1391
0
    RSA_VALIDATE_RET(ctx != NULL);
1392
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1393
0
                     mode == MBEDTLS_RSA_PUBLIC);
1394
0
    RSA_VALIDATE_RET(output_max_len == 0 || output != NULL);
1395
0
    RSA_VALIDATE_RET(label_len == 0 || label != NULL);
1396
0
    RSA_VALIDATE_RET(input != NULL);
1397
0
    RSA_VALIDATE_RET(olen != NULL);
1398
1399
    /*
1400
     * Parameters sanity checks
1401
     */
1402
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1403
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1404
0
    }
1405
1406
0
    ilen = ctx->len;
1407
1408
0
    if (ilen < 16 || ilen > sizeof(buf)) {
1409
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1410
0
    }
1411
1412
0
    md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id);
1413
0
    if (md_info == NULL) {
1414
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1415
0
    }
1416
1417
0
    hlen = mbedtls_md_get_size(md_info);
1418
1419
    // checking for integer underflow
1420
0
    if (2 * hlen + 2 > ilen) {
1421
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1422
0
    }
1423
1424
    /*
1425
     * RSA operation
1426
     */
1427
0
    ret = (mode == MBEDTLS_RSA_PUBLIC)
1428
0
          ? mbedtls_rsa_public(ctx, input, buf)
1429
0
          : mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1430
1431
0
    if (ret != 0) {
1432
0
        goto cleanup;
1433
0
    }
1434
1435
    /*
1436
     * Unmask data and generate lHash
1437
     */
1438
0
    mbedtls_md_init(&md_ctx);
1439
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1440
0
        mbedtls_md_free(&md_ctx);
1441
0
        goto cleanup;
1442
0
    }
1443
1444
    /* seed: Apply seedMask to maskedSeed */
1445
0
    if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1446
0
                        &md_ctx)) != 0 ||
1447
        /* DB: Apply dbMask to maskedDB */
1448
0
        (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1449
0
                        &md_ctx)) != 0) {
1450
0
        mbedtls_md_free(&md_ctx);
1451
0
        goto cleanup;
1452
0
    }
1453
1454
0
    mbedtls_md_free(&md_ctx);
1455
1456
    /* Generate lHash */
1457
0
    if ((ret = mbedtls_md(md_info, label, label_len, lhash)) != 0) {
1458
0
        goto cleanup;
1459
0
    }
1460
1461
    /*
1462
     * Check contents, in "constant-time"
1463
     */
1464
0
    p = buf;
1465
0
    bad = 0;
1466
1467
0
    bad |= *p++; /* First byte must be 0 */
1468
1469
0
    p += hlen; /* Skip seed */
1470
1471
    /* Check lHash */
1472
0
    bad |= mbedtls_ct_memcmp(lhash, p, hlen);
1473
0
    p += hlen;
1474
1475
    /* Get zero-padding len, but always read till end of buffer
1476
     * (minus one, for the 01 byte) */
1477
0
    pad_len = 0;
1478
0
    pad_done = 0;
1479
0
    for (i = 0; i < ilen - 2 * hlen - 2; i++) {
1480
0
        pad_done |= p[i];
1481
0
        pad_len += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
1482
0
    }
1483
1484
0
    p += pad_len;
1485
0
    bad |= *p++ ^ 0x01;
1486
1487
    /*
1488
     * The only information "leaked" is whether the padding was correct or not
1489
     * (eg, no data is copied if it was not correct). This meets the
1490
     * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
1491
     * the different error conditions.
1492
     */
1493
0
    if (bad != 0) {
1494
0
        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
1495
0
        goto cleanup;
1496
0
    }
1497
1498
0
    if (ilen - (p - buf) > output_max_len) {
1499
0
        ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1500
0
        goto cleanup;
1501
0
    }
1502
1503
0
    *olen = ilen - (p - buf);
1504
0
    if (*olen != 0) {
1505
0
        memcpy(output, p, *olen);
1506
0
    }
1507
0
    ret = 0;
1508
1509
0
cleanup:
1510
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
1511
0
    mbedtls_platform_zeroize(lhash, sizeof(lhash));
1512
1513
0
    return ret;
1514
0
}
1515
#endif /* MBEDTLS_PKCS1_V21 */
1516
1517
#if defined(MBEDTLS_PKCS1_V15)
1518
/*
1519
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
1520
 */
1521
int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
1522
                                        int (*f_rng)(void *, unsigned char *, size_t),
1523
                                        void *p_rng,
1524
                                        int mode,
1525
                                        size_t *olen,
1526
                                        const unsigned char *input,
1527
                                        unsigned char *output,
1528
                                        size_t output_max_len)
1529
0
{
1530
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1531
0
    size_t ilen;
1532
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1533
1534
0
    RSA_VALIDATE_RET(ctx != NULL);
1535
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1536
0
                     mode == MBEDTLS_RSA_PUBLIC);
1537
0
    RSA_VALIDATE_RET(output_max_len == 0 || output != NULL);
1538
0
    RSA_VALIDATE_RET(input != NULL);
1539
0
    RSA_VALIDATE_RET(olen != NULL);
1540
1541
0
    ilen = ctx->len;
1542
1543
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1544
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1545
0
    }
1546
1547
0
    if (ilen < 16 || ilen > sizeof(buf)) {
1548
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1549
0
    }
1550
1551
0
    ret = (mode == MBEDTLS_RSA_PUBLIC)
1552
0
          ? mbedtls_rsa_public(ctx, input, buf)
1553
0
          : mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1554
1555
0
    if (ret != 0) {
1556
0
        goto cleanup;
1557
0
    }
1558
1559
0
    ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(mode, buf, ilen,
1560
0
                                               output, output_max_len, olen);
1561
1562
0
cleanup:
1563
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
1564
1565
0
    return ret;
1566
0
}
1567
#endif /* MBEDTLS_PKCS1_V15 */
1568
1569
/*
1570
 * Do an RSA operation, then remove the message padding
1571
 */
1572
int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
1573
                              int (*f_rng)(void *, unsigned char *, size_t),
1574
                              void *p_rng,
1575
                              int mode, size_t *olen,
1576
                              const unsigned char *input,
1577
                              unsigned char *output,
1578
                              size_t output_max_len)
1579
0
{
1580
0
    RSA_VALIDATE_RET(ctx != NULL);
1581
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1582
0
                     mode == MBEDTLS_RSA_PUBLIC);
1583
0
    RSA_VALIDATE_RET(output_max_len == 0 || output != NULL);
1584
0
    RSA_VALIDATE_RET(input != NULL);
1585
0
    RSA_VALIDATE_RET(olen != NULL);
1586
1587
0
    switch (ctx->padding) {
1588
0
#if defined(MBEDTLS_PKCS1_V15)
1589
0
        case MBEDTLS_RSA_PKCS_V15:
1590
0
            return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, mode, olen,
1591
0
                                                       input, output, output_max_len);
1592
0
#endif
1593
1594
0
#if defined(MBEDTLS_PKCS1_V21)
1595
0
        case MBEDTLS_RSA_PKCS_V21:
1596
0
            return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, mode, NULL, 0,
1597
0
                                                  olen, input, output,
1598
0
                                                  output_max_len);
1599
0
#endif
1600
1601
0
        default:
1602
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
1603
0
    }
1604
0
}
1605
1606
#if defined(MBEDTLS_PKCS1_V21)
1607
static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1608
                               int (*f_rng)(void *, unsigned char *, size_t),
1609
                               void *p_rng,
1610
                               int mode,
1611
                               mbedtls_md_type_t md_alg,
1612
                               unsigned int hashlen,
1613
                               const unsigned char *hash,
1614
                               int saltlen,
1615
                               unsigned char *sig)
1616
0
{
1617
0
    size_t olen;
1618
0
    unsigned char *p = sig;
1619
0
    unsigned char *salt = NULL;
1620
0
    size_t slen, min_slen, hlen, offset = 0;
1621
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1622
0
    size_t msb;
1623
0
    const mbedtls_md_info_t *md_info;
1624
0
    mbedtls_md_context_t md_ctx;
1625
0
    RSA_VALIDATE_RET(ctx != NULL);
1626
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1627
0
                     mode == MBEDTLS_RSA_PUBLIC);
1628
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
1629
0
                      hashlen == 0) ||
1630
0
                     hash != NULL);
1631
0
    RSA_VALIDATE_RET(sig != NULL);
1632
1633
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1634
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1635
0
    }
1636
1637
0
    if (f_rng == NULL) {
1638
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1639
0
    }
1640
1641
0
    olen = ctx->len;
1642
1643
0
    if (md_alg != MBEDTLS_MD_NONE) {
1644
        /* Gather length of hash to sign */
1645
0
        md_info = mbedtls_md_info_from_type(md_alg);
1646
0
        if (md_info == NULL) {
1647
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1648
0
        }
1649
1650
0
        hashlen = mbedtls_md_get_size(md_info);
1651
0
    }
1652
1653
0
    md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) ctx->hash_id);
1654
0
    if (md_info == NULL) {
1655
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1656
0
    }
1657
1658
0
    hlen = mbedtls_md_get_size(md_info);
1659
1660
0
    if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
1661
        /* Calculate the largest possible salt length, up to the hash size.
1662
         * Normally this is the hash length, which is the maximum salt length
1663
         * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
1664
         * enough room, use the maximum salt length that fits. The constraint is
1665
         * that the hash length plus the salt length plus 2 bytes must be at most
1666
         * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
1667
         * (PKCS#1 v2.2) §9.1.1 step 3. */
1668
0
        min_slen = hlen - 2;
1669
0
        if (olen < hlen + min_slen + 2) {
1670
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1671
0
        } else if (olen >= hlen + hlen + 2) {
1672
0
            slen = hlen;
1673
0
        } else {
1674
0
            slen = olen - hlen - 2;
1675
0
        }
1676
0
    } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
1677
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1678
0
    } else {
1679
0
        slen = (size_t) saltlen;
1680
0
    }
1681
1682
0
    memset(sig, 0, olen);
1683
1684
    /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
1685
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1686
0
    p += olen - hlen - slen - 2;
1687
0
    *p++ = 0x01;
1688
1689
    /* Generate salt of length slen in place in the encoded message */
1690
0
    salt = p;
1691
0
    if ((ret = f_rng(p_rng, salt, slen)) != 0) {
1692
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1693
0
    }
1694
1695
0
    p += slen;
1696
1697
0
    mbedtls_md_init(&md_ctx);
1698
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1699
0
        goto exit;
1700
0
    }
1701
1702
    /* Generate H = Hash( M' ) */
1703
0
    if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1704
0
        goto exit;
1705
0
    }
1706
0
    if ((ret = mbedtls_md_update(&md_ctx, p, 8)) != 0) {
1707
0
        goto exit;
1708
0
    }
1709
0
    if ((ret = mbedtls_md_update(&md_ctx, hash, hashlen)) != 0) {
1710
0
        goto exit;
1711
0
    }
1712
0
    if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1713
0
        goto exit;
1714
0
    }
1715
0
    if ((ret = mbedtls_md_finish(&md_ctx, p)) != 0) {
1716
0
        goto exit;
1717
0
    }
1718
1719
    /* Compensate for boundary condition when applying mask */
1720
0
    if (msb % 8 == 0) {
1721
0
        offset = 1;
1722
0
    }
1723
1724
    /* maskedDB: Apply dbMask to DB */
1725
0
    if ((ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen,
1726
0
                        &md_ctx)) != 0) {
1727
0
        goto exit;
1728
0
    }
1729
1730
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1731
0
    sig[0] &= 0xFF >> (olen * 8 - msb);
1732
1733
0
    p += hlen;
1734
0
    *p++ = 0xBC;
1735
1736
0
exit:
1737
0
    mbedtls_md_free(&md_ctx);
1738
1739
0
    if (ret != 0) {
1740
0
        return ret;
1741
0
    }
1742
1743
0
    return (mode == MBEDTLS_RSA_PUBLIC)
1744
0
            ? mbedtls_rsa_public(ctx, sig, sig)
1745
0
            : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
1746
0
}
1747
1748
/*
1749
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
1750
 * the option to pass in the salt length.
1751
 */
1752
int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
1753
                                    int (*f_rng)(void *, unsigned char *, size_t),
1754
                                    void *p_rng,
1755
                                    mbedtls_md_type_t md_alg,
1756
                                    unsigned int hashlen,
1757
                                    const unsigned char *hash,
1758
                                    int saltlen,
1759
                                    unsigned char *sig)
1760
0
{
1761
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, md_alg,
1762
0
                               hashlen, hash, saltlen, sig);
1763
0
}
1764
1765
1766
/*
1767
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
1768
 */
1769
int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1770
                                int (*f_rng)(void *, unsigned char *, size_t),
1771
                                void *p_rng,
1772
                                int mode,
1773
                                mbedtls_md_type_t md_alg,
1774
                                unsigned int hashlen,
1775
                                const unsigned char *hash,
1776
                                unsigned char *sig)
1777
0
{
1778
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, mode, md_alg,
1779
0
                               hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
1780
0
}
1781
#endif /* MBEDTLS_PKCS1_V21 */
1782
1783
#if defined(MBEDTLS_PKCS1_V15)
1784
/*
1785
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
1786
 */
1787
1788
/* Construct a PKCS v1.5 encoding of a hashed message
1789
 *
1790
 * This is used both for signature generation and verification.
1791
 *
1792
 * Parameters:
1793
 * - md_alg:  Identifies the hash algorithm used to generate the given hash;
1794
 *            MBEDTLS_MD_NONE if raw data is signed.
1795
 * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.
1796
 * - hash:    Buffer containing the hashed message or the raw data.
1797
 * - dst_len: Length of the encoded message.
1798
 * - dst:     Buffer to hold the encoded message.
1799
 *
1800
 * Assumptions:
1801
 * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.
1802
 * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.
1803
 * - dst points to a buffer of size at least dst_len.
1804
 *
1805
 */
1806
static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
1807
                                       unsigned int hashlen,
1808
                                       const unsigned char *hash,
1809
                                       size_t dst_len,
1810
                                       unsigned char *dst)
1811
0
{
1812
0
    size_t oid_size  = 0;
1813
0
    size_t nb_pad    = dst_len;
1814
0
    unsigned char *p = dst;
1815
0
    const char *oid  = NULL;
1816
1817
    /* Are we signing hashed or raw data? */
1818
0
    if (md_alg != MBEDTLS_MD_NONE) {
1819
0
        const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1820
0
        if (md_info == NULL) {
1821
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1822
0
        }
1823
1824
0
        if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
1825
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1826
0
        }
1827
1828
0
        hashlen = mbedtls_md_get_size(md_info);
1829
1830
        /* Double-check that 8 + hashlen + oid_size can be used as a
1831
         * 1-byte ASN.1 length encoding and that there's no overflow. */
1832
0
        if (8 + hashlen + oid_size  >= 0x80         ||
1833
0
            10 + hashlen            <  hashlen      ||
1834
0
            10 + hashlen + oid_size <  10 + hashlen) {
1835
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1836
0
        }
1837
1838
        /*
1839
         * Static bounds check:
1840
         * - Need 10 bytes for five tag-length pairs.
1841
         *   (Insist on 1-byte length encodings to protect against variants of
1842
         *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
1843
         * - Need hashlen bytes for hash
1844
         * - Need oid_size bytes for hash alg OID.
1845
         */
1846
0
        if (nb_pad < 10 + hashlen + oid_size) {
1847
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1848
0
        }
1849
0
        nb_pad -= 10 + hashlen + oid_size;
1850
0
    } else {
1851
0
        if (nb_pad < hashlen) {
1852
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1853
0
        }
1854
1855
0
        nb_pad -= hashlen;
1856
0
    }
1857
1858
    /* Need space for signature header and padding delimiter (3 bytes),
1859
     * and 8 bytes for the minimal padding */
1860
0
    if (nb_pad < 3 + 8) {
1861
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1862
0
    }
1863
0
    nb_pad -= 3;
1864
1865
    /* Now nb_pad is the amount of memory to be filled
1866
     * with padding, and at least 8 bytes long. */
1867
1868
    /* Write signature header and padding */
1869
0
    *p++ = 0;
1870
0
    *p++ = MBEDTLS_RSA_SIGN;
1871
0
    memset(p, 0xFF, nb_pad);
1872
0
    p += nb_pad;
1873
0
    *p++ = 0;
1874
1875
    /* Are we signing raw data? */
1876
0
    if (md_alg == MBEDTLS_MD_NONE) {
1877
0
        memcpy(p, hash, hashlen);
1878
0
        return 0;
1879
0
    }
1880
1881
    /* Signing hashed data, add corresponding ASN.1 structure
1882
     *
1883
     * DigestInfo ::= SEQUENCE {
1884
     *   digestAlgorithm DigestAlgorithmIdentifier,
1885
     *   digest Digest }
1886
     * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1887
     * Digest ::= OCTET STRING
1888
     *
1889
     * Schematic:
1890
     * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
1891
     *                                 TAG-NULL + LEN [ NULL ] ]
1892
     *                 TAG-OCTET + LEN [ HASH ] ]
1893
     */
1894
0
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1895
0
    *p++ = (unsigned char) (0x08 + oid_size + hashlen);
1896
0
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1897
0
    *p++ = (unsigned char) (0x04 + oid_size);
1898
0
    *p++ = MBEDTLS_ASN1_OID;
1899
0
    *p++ = (unsigned char) oid_size;
1900
0
    memcpy(p, oid, oid_size);
1901
0
    p += oid_size;
1902
0
    *p++ = MBEDTLS_ASN1_NULL;
1903
0
    *p++ = 0x00;
1904
0
    *p++ = MBEDTLS_ASN1_OCTET_STRING;
1905
0
    *p++ = (unsigned char) hashlen;
1906
0
    memcpy(p, hash, hashlen);
1907
0
    p += hashlen;
1908
1909
    /* Just a sanity-check, should be automatic
1910
     * after the initial bounds check. */
1911
0
    if (p != dst + dst_len) {
1912
0
        mbedtls_platform_zeroize(dst, dst_len);
1913
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1914
0
    }
1915
1916
0
    return 0;
1917
0
}
1918
1919
/*
1920
 * Do an RSA operation to sign the message digest
1921
 */
1922
int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
1923
                                      int (*f_rng)(void *, unsigned char *, size_t),
1924
                                      void *p_rng,
1925
                                      int mode,
1926
                                      mbedtls_md_type_t md_alg,
1927
                                      unsigned int hashlen,
1928
                                      const unsigned char *hash,
1929
                                      unsigned char *sig)
1930
0
{
1931
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1932
0
    unsigned char *sig_try = NULL, *verif = NULL;
1933
1934
0
    RSA_VALIDATE_RET(ctx != NULL);
1935
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
1936
0
                     mode == MBEDTLS_RSA_PUBLIC);
1937
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
1938
0
                      hashlen == 0) ||
1939
0
                     hash != NULL);
1940
0
    RSA_VALIDATE_RET(sig != NULL);
1941
1942
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1943
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1944
0
    }
1945
1946
    /*
1947
     * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
1948
     */
1949
1950
0
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
1951
0
                                           ctx->len, sig)) != 0) {
1952
0
        return ret;
1953
0
    }
1954
1955
    /*
1956
     * Call respective RSA primitive
1957
     */
1958
1959
0
    if (mode == MBEDTLS_RSA_PUBLIC) {
1960
        /* Skip verification on a public key operation */
1961
0
        return mbedtls_rsa_public(ctx, sig, sig);
1962
0
    }
1963
1964
    /* Private key operation
1965
     *
1966
     * In order to prevent Lenstra's attack, make the signature in a
1967
     * temporary buffer and check it before returning it.
1968
     */
1969
1970
0
    sig_try = mbedtls_calloc(1, ctx->len);
1971
0
    if (sig_try == NULL) {
1972
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1973
0
    }
1974
1975
0
    verif = mbedtls_calloc(1, ctx->len);
1976
0
    if (verif == NULL) {
1977
0
        mbedtls_free(sig_try);
1978
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1979
0
    }
1980
1981
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
1982
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
1983
1984
0
    if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
1985
0
        ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
1986
0
        goto cleanup;
1987
0
    }
1988
1989
0
    memcpy(sig, sig_try, ctx->len);
1990
1991
0
cleanup:
1992
0
    mbedtls_platform_zeroize(sig_try, ctx->len);
1993
0
    mbedtls_platform_zeroize(verif, ctx->len);
1994
0
    mbedtls_free(sig_try);
1995
0
    mbedtls_free(verif);
1996
1997
0
    if (ret != 0) {
1998
0
        memset(sig, '!', ctx->len);
1999
0
    }
2000
0
    return ret;
2001
0
}
2002
#endif /* MBEDTLS_PKCS1_V15 */
2003
2004
/*
2005
 * Do an RSA operation to sign the message digest
2006
 */
2007
int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
2008
                           int (*f_rng)(void *, unsigned char *, size_t),
2009
                           void *p_rng,
2010
                           int mode,
2011
                           mbedtls_md_type_t md_alg,
2012
                           unsigned int hashlen,
2013
                           const unsigned char *hash,
2014
                           unsigned char *sig)
2015
0
{
2016
0
    RSA_VALIDATE_RET(ctx != NULL);
2017
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
2018
0
                     mode == MBEDTLS_RSA_PUBLIC);
2019
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
2020
0
                      hashlen == 0) ||
2021
0
                     hash != NULL);
2022
0
    RSA_VALIDATE_RET(sig != NULL);
2023
2024
0
    switch (ctx->padding) {
2025
0
#if defined(MBEDTLS_PKCS1_V15)
2026
0
        case MBEDTLS_RSA_PKCS_V15:
2027
0
            return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng, mode, md_alg,
2028
0
                                                     hashlen, hash, sig);
2029
0
#endif
2030
2031
0
#if defined(MBEDTLS_PKCS1_V21)
2032
0
        case MBEDTLS_RSA_PKCS_V21:
2033
0
            return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, mode, md_alg,
2034
0
                                               hashlen, hash, sig);
2035
0
#endif
2036
2037
0
        default:
2038
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2039
0
    }
2040
0
}
2041
2042
#if defined(MBEDTLS_PKCS1_V21)
2043
/*
2044
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2045
 */
2046
int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2047
                                      int (*f_rng)(void *, unsigned char *, size_t),
2048
                                      void *p_rng,
2049
                                      int mode,
2050
                                      mbedtls_md_type_t md_alg,
2051
                                      unsigned int hashlen,
2052
                                      const unsigned char *hash,
2053
                                      mbedtls_md_type_t mgf1_hash_id,
2054
                                      int expected_salt_len,
2055
                                      const unsigned char *sig)
2056
0
{
2057
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2058
0
    size_t siglen;
2059
0
    unsigned char *p;
2060
0
    unsigned char *hash_start;
2061
0
    unsigned char result[MBEDTLS_MD_MAX_SIZE];
2062
0
    unsigned char zeros[8];
2063
0
    unsigned int hlen;
2064
0
    size_t observed_salt_len, msb;
2065
0
    const mbedtls_md_info_t *md_info;
2066
0
    mbedtls_md_context_t md_ctx;
2067
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
2068
2069
0
    RSA_VALIDATE_RET(ctx != NULL);
2070
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
2071
0
                     mode == MBEDTLS_RSA_PUBLIC);
2072
0
    RSA_VALIDATE_RET(sig != NULL);
2073
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
2074
0
                      hashlen == 0) ||
2075
0
                     hash != NULL);
2076
2077
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21) {
2078
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2079
0
    }
2080
2081
0
    siglen = ctx->len;
2082
2083
0
    if (siglen < 16 || siglen > sizeof(buf)) {
2084
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2085
0
    }
2086
2087
0
    ret = (mode == MBEDTLS_RSA_PUBLIC)
2088
0
          ? mbedtls_rsa_public(ctx, sig, buf)
2089
0
          : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, buf);
2090
2091
0
    if (ret != 0) {
2092
0
        return ret;
2093
0
    }
2094
2095
0
    p = buf;
2096
2097
0
    if (buf[siglen - 1] != 0xBC) {
2098
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2099
0
    }
2100
2101
0
    if (md_alg != MBEDTLS_MD_NONE) {
2102
        /* Gather length of hash to sign */
2103
0
        md_info = mbedtls_md_info_from_type(md_alg);
2104
0
        if (md_info == NULL) {
2105
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2106
0
        }
2107
2108
0
        hashlen = mbedtls_md_get_size(md_info);
2109
0
    }
2110
2111
0
    md_info = mbedtls_md_info_from_type(mgf1_hash_id);
2112
0
    if (md_info == NULL) {
2113
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2114
0
    }
2115
2116
0
    hlen = mbedtls_md_get_size(md_info);
2117
2118
0
    memset(zeros, 0, 8);
2119
2120
    /*
2121
     * Note: EMSA-PSS verification is over the length of N - 1 bits
2122
     */
2123
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2124
2125
0
    if (buf[0] >> (8 - siglen * 8 + msb)) {
2126
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2127
0
    }
2128
2129
    /* Compensate for boundary condition when applying mask */
2130
0
    if (msb % 8 == 0) {
2131
0
        p++;
2132
0
        siglen -= 1;
2133
0
    }
2134
2135
0
    if (siglen < hlen + 2) {
2136
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2137
0
    }
2138
0
    hash_start = p + siglen - hlen - 1;
2139
2140
0
    mbedtls_md_init(&md_ctx);
2141
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
2142
0
        goto exit;
2143
0
    }
2144
2145
0
    ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, &md_ctx);
2146
0
    if (ret != 0) {
2147
0
        goto exit;
2148
0
    }
2149
2150
0
    buf[0] &= 0xFF >> (siglen * 8 - msb);
2151
2152
0
    while (p < hash_start - 1 && *p == 0) {
2153
0
        p++;
2154
0
    }
2155
2156
0
    if (*p++ != 0x01) {
2157
0
        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
2158
0
        goto exit;
2159
0
    }
2160
2161
0
    observed_salt_len = hash_start - p;
2162
2163
0
    if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2164
0
        observed_salt_len != (size_t) expected_salt_len) {
2165
0
        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
2166
0
        goto exit;
2167
0
    }
2168
2169
    /*
2170
     * Generate H = Hash( M' )
2171
     */
2172
0
    ret = mbedtls_md_starts(&md_ctx);
2173
0
    if (ret != 0) {
2174
0
        goto exit;
2175
0
    }
2176
0
    ret = mbedtls_md_update(&md_ctx, zeros, 8);
2177
0
    if (ret != 0) {
2178
0
        goto exit;
2179
0
    }
2180
0
    ret = mbedtls_md_update(&md_ctx, hash, hashlen);
2181
0
    if (ret != 0) {
2182
0
        goto exit;
2183
0
    }
2184
0
    ret = mbedtls_md_update(&md_ctx, p, observed_salt_len);
2185
0
    if (ret != 0) {
2186
0
        goto exit;
2187
0
    }
2188
0
    ret = mbedtls_md_finish(&md_ctx, result);
2189
0
    if (ret != 0) {
2190
0
        goto exit;
2191
0
    }
2192
2193
0
    if (memcmp(hash_start, result, hlen) != 0) {
2194
0
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2195
0
        goto exit;
2196
0
    }
2197
2198
0
exit:
2199
0
    mbedtls_md_free(&md_ctx);
2200
2201
0
    return ret;
2202
0
}
2203
2204
/*
2205
 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2206
 */
2207
int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2208
                                  int (*f_rng)(void *, unsigned char *, size_t),
2209
                                  void *p_rng,
2210
                                  int mode,
2211
                                  mbedtls_md_type_t md_alg,
2212
                                  unsigned int hashlen,
2213
                                  const unsigned char *hash,
2214
                                  const unsigned char *sig)
2215
0
{
2216
0
    mbedtls_md_type_t mgf1_hash_id;
2217
0
    RSA_VALIDATE_RET(ctx != NULL);
2218
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
2219
0
                     mode == MBEDTLS_RSA_PUBLIC);
2220
0
    RSA_VALIDATE_RET(sig != NULL);
2221
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
2222
0
                      hashlen == 0) ||
2223
0
                     hash != NULL);
2224
2225
0
    mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2226
0
                             ? (mbedtls_md_type_t) ctx->hash_id
2227
0
                             : md_alg;
2228
2229
0
    return mbedtls_rsa_rsassa_pss_verify_ext(ctx, f_rng, p_rng, mode,
2230
0
                                             md_alg, hashlen, hash,
2231
0
                                             mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,
2232
0
                                             sig);
2233
2234
0
}
2235
#endif /* MBEDTLS_PKCS1_V21 */
2236
2237
#if defined(MBEDTLS_PKCS1_V15)
2238
/*
2239
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2240
 */
2241
int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
2242
                                        int (*f_rng)(void *, unsigned char *, size_t),
2243
                                        void *p_rng,
2244
                                        int mode,
2245
                                        mbedtls_md_type_t md_alg,
2246
                                        unsigned int hashlen,
2247
                                        const unsigned char *hash,
2248
                                        const unsigned char *sig)
2249
0
{
2250
0
    int ret = 0;
2251
0
    size_t sig_len;
2252
0
    unsigned char *encoded = NULL, *encoded_expected = NULL;
2253
2254
0
    RSA_VALIDATE_RET(ctx != NULL);
2255
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
2256
0
                     mode == MBEDTLS_RSA_PUBLIC);
2257
0
    RSA_VALIDATE_RET(sig != NULL);
2258
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
2259
0
                      hashlen == 0) ||
2260
0
                     hash != NULL);
2261
2262
0
    sig_len = ctx->len;
2263
2264
0
    if (mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2265
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2266
0
    }
2267
2268
    /*
2269
     * Prepare expected PKCS1 v1.5 encoding of hash.
2270
     */
2271
2272
0
    if ((encoded          = mbedtls_calloc(1, sig_len)) == NULL ||
2273
0
        (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2274
0
        ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2275
0
        goto cleanup;
2276
0
    }
2277
2278
0
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2279
0
                                           encoded_expected)) != 0) {
2280
0
        goto cleanup;
2281
0
    }
2282
2283
    /*
2284
     * Apply RSA primitive to get what should be PKCS1 encoded hash.
2285
     */
2286
2287
0
    ret = (mode == MBEDTLS_RSA_PUBLIC)
2288
0
          ? mbedtls_rsa_public(ctx, sig, encoded)
2289
0
          : mbedtls_rsa_private(ctx, f_rng, p_rng, sig, encoded);
2290
0
    if (ret != 0) {
2291
0
        goto cleanup;
2292
0
    }
2293
2294
    /*
2295
     * Compare
2296
     */
2297
2298
0
    if ((ret = mbedtls_ct_memcmp(encoded, encoded_expected,
2299
0
                                 sig_len)) != 0) {
2300
0
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2301
0
        goto cleanup;
2302
0
    }
2303
2304
0
cleanup:
2305
2306
0
    if (encoded != NULL) {
2307
0
        mbedtls_platform_zeroize(encoded, sig_len);
2308
0
        mbedtls_free(encoded);
2309
0
    }
2310
2311
0
    if (encoded_expected != NULL) {
2312
0
        mbedtls_platform_zeroize(encoded_expected, sig_len);
2313
0
        mbedtls_free(encoded_expected);
2314
0
    }
2315
2316
0
    return ret;
2317
0
}
2318
#endif /* MBEDTLS_PKCS1_V15 */
2319
2320
/*
2321
 * Do an RSA operation and check the message digest
2322
 */
2323
int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2324
                             int (*f_rng)(void *, unsigned char *, size_t),
2325
                             void *p_rng,
2326
                             int mode,
2327
                             mbedtls_md_type_t md_alg,
2328
                             unsigned int hashlen,
2329
                             const unsigned char *hash,
2330
                             const unsigned char *sig)
2331
0
{
2332
0
    RSA_VALIDATE_RET(ctx != NULL);
2333
0
    RSA_VALIDATE_RET(mode == MBEDTLS_RSA_PRIVATE ||
2334
0
                     mode == MBEDTLS_RSA_PUBLIC);
2335
0
    RSA_VALIDATE_RET(sig != NULL);
2336
0
    RSA_VALIDATE_RET((md_alg  == MBEDTLS_MD_NONE &&
2337
0
                      hashlen == 0) ||
2338
0
                     hash != NULL);
2339
2340
0
    switch (ctx->padding) {
2341
0
#if defined(MBEDTLS_PKCS1_V15)
2342
0
        case MBEDTLS_RSA_PKCS_V15:
2343
0
            return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, f_rng, p_rng, mode, md_alg,
2344
0
                                                       hashlen, hash, sig);
2345
0
#endif
2346
2347
0
#if defined(MBEDTLS_PKCS1_V21)
2348
0
        case MBEDTLS_RSA_PKCS_V21:
2349
0
            return mbedtls_rsa_rsassa_pss_verify(ctx, f_rng, p_rng, mode, md_alg,
2350
0
                                                 hashlen, hash, sig);
2351
0
#endif
2352
2353
0
        default:
2354
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2355
0
    }
2356
0
}
2357
2358
/*
2359
 * Copy the components of an RSA key
2360
 */
2361
int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2362
0
{
2363
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2364
0
    RSA_VALIDATE_RET(dst != NULL);
2365
0
    RSA_VALIDATE_RET(src != NULL);
2366
2367
0
    dst->len = src->len;
2368
2369
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2370
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2371
2372
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2373
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2374
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2375
2376
0
#if !defined(MBEDTLS_RSA_NO_CRT)
2377
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2378
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2379
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2380
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2381
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2382
0
#endif
2383
2384
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2385
2386
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2387
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2388
2389
0
    dst->padding = src->padding;
2390
0
    dst->hash_id = src->hash_id;
2391
2392
0
cleanup:
2393
0
    if (ret != 0) {
2394
0
        mbedtls_rsa_free(dst);
2395
0
    }
2396
2397
0
    return ret;
2398
0
}
2399
2400
/*
2401
 * Free the components of an RSA key
2402
 */
2403
void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2404
0
{
2405
0
    if (ctx == NULL) {
2406
0
        return;
2407
0
    }
2408
2409
0
    mbedtls_mpi_free(&ctx->Vi);
2410
0
    mbedtls_mpi_free(&ctx->Vf);
2411
0
    mbedtls_mpi_free(&ctx->RN);
2412
0
    mbedtls_mpi_free(&ctx->D);
2413
0
    mbedtls_mpi_free(&ctx->Q);
2414
0
    mbedtls_mpi_free(&ctx->P);
2415
0
    mbedtls_mpi_free(&ctx->E);
2416
0
    mbedtls_mpi_free(&ctx->N);
2417
2418
0
#if !defined(MBEDTLS_RSA_NO_CRT)
2419
0
    mbedtls_mpi_free(&ctx->RQ);
2420
0
    mbedtls_mpi_free(&ctx->RP);
2421
0
    mbedtls_mpi_free(&ctx->QP);
2422
0
    mbedtls_mpi_free(&ctx->DQ);
2423
0
    mbedtls_mpi_free(&ctx->DP);
2424
0
#endif /* MBEDTLS_RSA_NO_CRT */
2425
2426
#if defined(MBEDTLS_THREADING_C)
2427
    /* Free the mutex, but only if it hasn't been freed already. */
2428
    if (ctx->ver != 0) {
2429
        mbedtls_mutex_free(&ctx->mutex);
2430
        ctx->ver = 0;
2431
    }
2432
#endif
2433
0
}
2434
2435
#endif /* !MBEDTLS_RSA_ALT */
2436
2437
#if defined(MBEDTLS_SELF_TEST)
2438
2439
#include "mbedtls/sha1.h"
2440
2441
/*
2442
 * Example RSA-1024 keypair, for test purposes
2443
 */
2444
#define KEY_LEN 128
2445
2446
#define RSA_N   "9292758453063D803DD603D5E777D788" \
2447
                "8ED1D5BF35786190FA2F23EBC0848AEA" \
2448
                "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2449
                "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2450
                "93A89813FBF3C4F8066D2D800F7C38A8" \
2451
                "1AE31942917403FF4946B0A83D3D3E05" \
2452
                "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2453
                "5E94BB77B07507233A0BC7BAC8F90F79"
2454
2455
#define RSA_E   "10001"
2456
2457
#define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
2458
                "66CA472BC44D253102F8B4A9D3BFA750" \
2459
                "91386C0077937FE33FA3252D28855837" \
2460
                "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2461
                "DF79C5CE07EE72C7F123142198164234" \
2462
                "CABB724CF78B8173B9F880FC86322407" \
2463
                "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2464
                "071513A1E85B5DFA031F21ECAE91A34D"
2465
2466
#define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2467
                "2C01CAD19EA484A87EA4377637E75500" \
2468
                "FCB2005C5C7DD6EC4AC023CDA285D796" \
2469
                "C3D9E75E1EFC42488BB4F1D13AC30A57"
2470
2471
#define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
2472
                "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2473
                "910E4168387E3C30AA1E00C339A79508" \
2474
                "8452DD96A9A5EA5D9DCA68DA636032AF"
2475
2476
0
#define PT_LEN  24
2477
0
#define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2478
0
                "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2479
2480
#if defined(MBEDTLS_PKCS1_V15)
2481
static int myrand(void *rng_state, unsigned char *output, size_t len)
2482
0
{
2483
0
#if !defined(__OpenBSD__) && !defined(__NetBSD__)
2484
0
    size_t i;
2485
2486
0
    if (rng_state != NULL) {
2487
0
        rng_state  = NULL;
2488
0
    }
2489
2490
0
    for (i = 0; i < len; ++i) {
2491
0
        output[i] = rand();
2492
0
    }
2493
#else
2494
    if (rng_state != NULL) {
2495
        rng_state = NULL;
2496
    }
2497
2498
    arc4random_buf(output, len);
2499
#endif /* !OpenBSD && !NetBSD */
2500
2501
0
    return 0;
2502
0
}
2503
#endif /* MBEDTLS_PKCS1_V15 */
2504
2505
/*
2506
 * Checkup routine
2507
 */
2508
int mbedtls_rsa_self_test(int verbose)
2509
0
{
2510
0
    int ret = 0;
2511
0
#if defined(MBEDTLS_PKCS1_V15)
2512
0
    size_t len;
2513
0
    mbedtls_rsa_context rsa;
2514
0
    unsigned char rsa_plaintext[PT_LEN];
2515
0
    unsigned char rsa_decrypted[PT_LEN];
2516
0
    unsigned char rsa_ciphertext[KEY_LEN];
2517
0
#if defined(MBEDTLS_SHA1_C)
2518
0
    unsigned char sha1sum[20];
2519
0
#endif
2520
2521
0
    mbedtls_mpi K;
2522
2523
0
    mbedtls_mpi_init(&K);
2524
0
    mbedtls_rsa_init(&rsa, MBEDTLS_RSA_PKCS_V15, 0);
2525
2526
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2527
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2528
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2529
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2530
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2531
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2532
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2533
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2534
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2535
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2536
2537
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2538
2539
0
    if (verbose != 0) {
2540
0
        mbedtls_printf("  RSA key validation: ");
2541
0
    }
2542
2543
0
    if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2544
0
        mbedtls_rsa_check_privkey(&rsa) != 0) {
2545
0
        if (verbose != 0) {
2546
0
            mbedtls_printf("failed\n");
2547
0
        }
2548
2549
0
        ret = 1;
2550
0
        goto cleanup;
2551
0
    }
2552
2553
0
    if (verbose != 0) {
2554
0
        mbedtls_printf("passed\n  PKCS#1 encryption : ");
2555
0
    }
2556
2557
0
    memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2558
2559
0
    if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC,
2560
0
                                  PT_LEN, rsa_plaintext,
2561
0
                                  rsa_ciphertext) != 0) {
2562
0
        if (verbose != 0) {
2563
0
            mbedtls_printf("failed\n");
2564
0
        }
2565
2566
0
        ret = 1;
2567
0
        goto cleanup;
2568
0
    }
2569
2570
0
    if (verbose != 0) {
2571
0
        mbedtls_printf("passed\n  PKCS#1 decryption : ");
2572
0
    }
2573
2574
0
    if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE,
2575
0
                                  &len, rsa_ciphertext, rsa_decrypted,
2576
0
                                  sizeof(rsa_decrypted)) != 0) {
2577
0
        if (verbose != 0) {
2578
0
            mbedtls_printf("failed\n");
2579
0
        }
2580
2581
0
        ret = 1;
2582
0
        goto cleanup;
2583
0
    }
2584
2585
0
    if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
2586
0
        if (verbose != 0) {
2587
0
            mbedtls_printf("failed\n");
2588
0
        }
2589
2590
0
        ret = 1;
2591
0
        goto cleanup;
2592
0
    }
2593
2594
0
    if (verbose != 0) {
2595
0
        mbedtls_printf("passed\n");
2596
0
    }
2597
2598
0
#if defined(MBEDTLS_SHA1_C)
2599
0
    if (verbose != 0) {
2600
0
        mbedtls_printf("  PKCS#1 data sign  : ");
2601
0
    }
2602
2603
0
    if (mbedtls_sha1_ret(rsa_plaintext, PT_LEN, sha1sum) != 0) {
2604
0
        if (verbose != 0) {
2605
0
            mbedtls_printf("failed\n");
2606
0
        }
2607
2608
0
        return 1;
2609
0
    }
2610
2611
0
    if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
2612
0
                               MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
2613
0
                               sha1sum, rsa_ciphertext) != 0) {
2614
0
        if (verbose != 0) {
2615
0
            mbedtls_printf("failed\n");
2616
0
        }
2617
2618
0
        ret = 1;
2619
0
        goto cleanup;
2620
0
    }
2621
2622
0
    if (verbose != 0) {
2623
0
        mbedtls_printf("passed\n  PKCS#1 sig. verify: ");
2624
0
    }
2625
2626
0
    if (mbedtls_rsa_pkcs1_verify(&rsa, NULL, NULL,
2627
0
                                 MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
2628
0
                                 sha1sum, rsa_ciphertext) != 0) {
2629
0
        if (verbose != 0) {
2630
0
            mbedtls_printf("failed\n");
2631
0
        }
2632
2633
0
        ret = 1;
2634
0
        goto cleanup;
2635
0
    }
2636
2637
0
    if (verbose != 0) {
2638
0
        mbedtls_printf("passed\n");
2639
0
    }
2640
0
#endif /* MBEDTLS_SHA1_C */
2641
2642
0
    if (verbose != 0) {
2643
0
        mbedtls_printf("\n");
2644
0
    }
2645
2646
0
cleanup:
2647
0
    mbedtls_mpi_free(&K);
2648
0
    mbedtls_rsa_free(&rsa);
2649
#else /* MBEDTLS_PKCS1_V15 */
2650
    ((void) verbose);
2651
#endif /* MBEDTLS_PKCS1_V15 */
2652
0
    return ret;
2653
0
}
2654
2655
#endif /* MBEDTLS_SELF_TEST */
2656
2657
#endif /* MBEDTLS_RSA_C */