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