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