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