rsa.c
Go to the documentation of this file.
1 /**
2  * @file rsa.c
3  * @brief RSA public-key cryptography standard
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2019 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneCrypto Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @section Description
28  *
29  * RSA is an algorithm for public-key cryptography which is suitable for signing
30  * as well as encryption. Refer to the following RFCs for complete details:
31  * - RFC 2313: PKCS #1: RSA Encryption Version 1.5
32  * - RFC 3447: PKCS #1: RSA Cryptography Specifications Version 2.1
33  * - RFC 8017: PKCS #1: RSA Cryptography Specifications Version 2.2
34  *
35  * @author Oryx Embedded SARL (www.oryx-embedded.com)
36  * @version 1.9.6
37  **/
38 
39 //Switch to the appropriate trace level
40 #define TRACE_LEVEL CRYPTO_TRACE_LEVEL
41 
42 //Dependencies
43 #include "core/crypto.h"
44 #include "mac/hmac.h"
45 #include "pkc/rsa.h"
46 #include "mpi/mpi.h"
47 #include "encoding/asn1.h"
48 #include "encoding/oid.h"
49 #include "debug.h"
50 
51 //Check crypto library configuration
52 #if (RSA_SUPPORT == ENABLED)
53 
54 //PKCS #1 OID (1.2.840.113549.1.1)
55 const uint8_t PKCS1_OID[8] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01};
56 //RSA encryption OID (1.2.840.113549.1.1.1)
57 const uint8_t RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01};
58 
59 //MD2 with RSA encryption OID (1.2.840.113549.1.1.2)
60 const uint8_t MD2_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02};
61 //MD5 with RSA encryption OID (1.2.840.113549.1.1.4)
62 const uint8_t MD5_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04};
63 //SHA-1 with RSA encryption OID (1.2.840.113549.1.1.5)
64 const uint8_t SHA1_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05};
65 //SHA-224 with RSA encryption OID (1.2.840.113549.1.1.14)
66 const uint8_t SHA224_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0E};
67 //SHA-256 with RSA encryption OID (1.2.840.113549.1.1.11)
68 const uint8_t SHA256_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B};
69 //SHA-384 with RSA encryption OID (1.2.840.113549.1.1.12)
70 const uint8_t SHA384_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C};
71 //SHA-512 with RSA encryption OID (1.2.840.113549.1.1.13)
72 const uint8_t SHA512_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D};
73 //SHA-512/224 with RSA encryption OID (1.2.840.113549.1.1.15)
74 const uint8_t SHA512_224_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0F};
75 //SHA-512/256 with RSA encryption OID (1.2.840.113549.1.1.16)
76 const uint8_t SHA512_256_WITH_RSA_ENCRYPTION_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x10};
77 
78 //RSASSA-PKCS1-v1_5 signature with SHA-3-224 OID (2.16.840.1.101.3.4.3.13)
79 const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_224_OID[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x0D};
80 //RSASSA-PKCS1-v1_5 signature with SHA-3-256 OID (2.16.840.1.101.3.4.3.14)
81 const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_256_OID[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x0E};
82 //RSASSA-PKCS1-v1_5 signature with SHA-3-384 OID (2.16.840.1.101.3.4.3.15)
83 const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_384_OID[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x0F};
84 //RSASSA-PKCS1-v1_5 signature with SHA-3-512 OID (2.16.840.1.101.3.4.3.16)
85 const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_512_OID[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x10};
86 
87 //RSASSA-PSS OID (1.2.840.113549.1.1.10)
88 const uint8_t RSASSA_PSS_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0A};
89 
90 //MGF1 OID (1.2.840.113549.1.1.8)
91 const uint8_t MGF1_OID[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x08};
92 
93 //Padding string
94 static const uint8_t padding[] =
95 {
96  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
97 };
98 
99 
100 /**
101  * @brief Initialize an RSA public key
102  * @param[in] key Pointer to the RSA public key to initialize
103  **/
104 
106 {
107  //Initialize multiple precision integers
108  mpiInit(&key->n);
109  mpiInit(&key->e);
110 }
111 
112 
113 /**
114  * @brief Release an RSA public key
115  * @param[in] key Pointer to the RSA public key to free
116  **/
117 
119 {
120  //Free multiple precision integers
121  mpiFree(&key->n);
122  mpiFree(&key->e);
123 }
124 
125 
126 /**
127  * @brief Initialize an RSA private key
128  * @param[in] key Pointer to the RSA private key to initialize
129  **/
130 
132 {
133  //Initialize multiple precision integers
134  mpiInit(&key->n);
135  mpiInit(&key->e);
136  mpiInit(&key->d);
137  mpiInit(&key->p);
138  mpiInit(&key->q);
139  mpiInit(&key->dp);
140  mpiInit(&key->dq);
141  mpiInit(&key->qinv);
142 }
143 
144 
145 /**
146  * @brief Release an RSA private key
147  * @param[in] key Pointer to the RSA private key to free
148  **/
149 
151 {
152  //Free multiple precision integers
153  mpiFree(&key->n);
154  mpiFree(&key->e);
155  mpiFree(&key->d);
156  mpiFree(&key->p);
157  mpiFree(&key->q);
158  mpiFree(&key->dp);
159  mpiFree(&key->dq);
160  mpiFree(&key->qinv);
161 }
162 
163 
164 /**
165  * @brief RSAES-PKCS1-v1_5 encryption operation
166  * @param[in] prngAlgo PRNG algorithm
167  * @param[in] prngContext Pointer to the PRNG context
168  * @param[in] key Recipient's RSA public key
169  * @param[in] message Message to be encrypted
170  * @param[in] messageLen Length of the message to be encrypted
171  * @param[out] ciphertext Ciphertext resulting from the encryption operation
172  * @param[out] ciphertextLen Length of the resulting ciphertext
173  * @return Error code
174  **/
175 
176 error_t rsaesPkcs1v15Encrypt(const PrngAlgo *prngAlgo, void *prngContext,
177  const RsaPublicKey *key, const uint8_t *message, size_t messageLen,
178  uint8_t *ciphertext, size_t *ciphertextLen)
179 {
180  error_t error;
181  uint_t k;
182  uint8_t *em;
183  Mpi m;
184  Mpi c;
185 
186  //Check parameters
187  if(prngAlgo == NULL || prngContext == NULL)
189  if(key == NULL || message == NULL)
191  if(ciphertext == NULL || ciphertextLen == NULL)
193 
194  //Debug message
195  TRACE_DEBUG("RSAES-PKCS1-v1_5 encryption...\r\n");
196  TRACE_DEBUG(" Modulus:\r\n");
197  TRACE_DEBUG_MPI(" ", &key->n);
198  TRACE_DEBUG(" Public exponent:\r\n");
199  TRACE_DEBUG_MPI(" ", &key->e);
200  TRACE_DEBUG(" Message:\r\n");
201  TRACE_DEBUG_ARRAY(" ", message, messageLen);
202 
203  //Initialize multiple-precision integers
204  mpiInit(&m);
205  mpiInit(&c);
206 
207  //Get the length in octets of the modulus n
208  k = mpiGetByteLength(&key->n);
209 
210  //Point to the buffer where the encoded message EM will be formatted
211  em = ciphertext;
212 
213  //EME-PKCS1-v1_5 encoding
214  error = emePkcs1v15Encode(prngAlgo, prngContext, message, messageLen, em, k);
215  //Any error to report?
216  if(error)
217  return error;
218 
219  //Debug message
220  TRACE_DEBUG(" Encoded message:\r\n");
221  TRACE_DEBUG_ARRAY(" ", em, k);
222 
223  //Start of exception handling block
224  do
225  {
226  //Convert the encoded message EM to an integer message representative m
227  error = mpiReadRaw(&m, em, k);
228  //Conversion failed?
229  if(error)
230  break;
231 
232  //Apply the RSAEP encryption primitive
233  error = rsaep(key, &m, &c);
234  //Any error to report?
235  if(error)
236  break;
237 
238  //Convert the ciphertext representative c to a ciphertext of length k octets
239  error = mpiWriteRaw(&c, ciphertext, k);
240  //Conversion failed?
241  if(error)
242  break;
243 
244  //Length of the resulting ciphertext
245  *ciphertextLen = k;
246 
247  //Debug message
248  TRACE_DEBUG(" Ciphertext:\r\n");
249  TRACE_DEBUG_ARRAY(" ", ciphertext, *ciphertextLen);
250 
251  //End of exception handling block
252  } while(0);
253 
254  //Free previously allocated memory
255  mpiFree(&m);
256  mpiFree(&c);
257 
258  //Return status code
259  return error;
260 }
261 
262 
263 /**
264  * @brief RSAES-PKCS1-v1_5 decryption operation
265  * @param[in] key Recipient's RSA private key
266  * @param[in] ciphertext Ciphertext to be decrypted
267  * @param[in] ciphertextLen Length of the ciphertext to be decrypted
268  * @param[out] message Output buffer where to store the decrypted message
269  * @param[in] messageSize Size of the output buffer
270  * @param[out] messageLen Length of the decrypted message
271  * @return Error code
272  **/
273 
275  const uint8_t *ciphertext, size_t ciphertextLen, uint8_t *message,
276  size_t messageSize, size_t *messageLen)
277 {
278  error_t error;
279  uint_t k;
280  size_t i;
281  size_t j;
282  size_t n;
283  uint8_t b;
284  uint32_t a;
285  uint32_t badPadding;
286  uint32_t badLength;
287  uint8_t *em;
288  Mpi c;
289  Mpi m;
290 
291  //Check parameters
292  if(key == NULL || ciphertext == NULL)
294  if(message == NULL || messageSize == 0 || messageLen == NULL)
296 
297  //Debug message
298  TRACE_DEBUG("RSAES-PKCS1-v1_5 decryption...\r\n");
299  TRACE_DEBUG(" Modulus:\r\n");
300  TRACE_DEBUG_MPI(" ", &key->n);
301  TRACE_DEBUG(" Public exponent:\r\n");
302  TRACE_DEBUG_MPI(" ", &key->e);
303  TRACE_DEBUG(" Private exponent:\r\n");
304  TRACE_DEBUG_MPI(" ", &key->d);
305  TRACE_DEBUG(" Prime 1:\r\n");
306  TRACE_DEBUG_MPI(" ", &key->p);
307  TRACE_DEBUG(" Prime 2:\r\n");
308  TRACE_DEBUG_MPI(" ", &key->q);
309  TRACE_DEBUG(" Prime exponent 1:\r\n");
310  TRACE_DEBUG_MPI(" ", &key->dp);
311  TRACE_DEBUG(" Prime exponent 2:\r\n");
312  TRACE_DEBUG_MPI(" ", &key->dq);
313  TRACE_DEBUG(" Coefficient:\r\n");
314  TRACE_DEBUG_MPI(" ", &key->qinv);
315  TRACE_DEBUG(" Ciphertext:\r\n");
316  TRACE_DEBUG_ARRAY(" ", ciphertext, ciphertextLen);
317 
318  //Initialize multiple-precision integers
319  mpiInit(&c);
320  mpiInit(&m);
321 
322  //Get the length in octets of the modulus n
323  k = mpiGetByteLength(&key->n);
324 
325  //Check the length of the ciphertext
326  if(ciphertextLen != k || ciphertextLen < 11)
327  return ERROR_INVALID_LENGTH;
328 
329  //Allocate a buffer to store the encoded message EM
330  em = cryptoAllocMem(k);
331  //Failed to allocate memory?
332  if(em == NULL)
333  return ERROR_OUT_OF_MEMORY;
334 
335  //Start of exception handling block
336  do
337  {
338  //Convert the ciphertext to an integer ciphertext representative c
339  error = mpiReadRaw(&c, ciphertext, ciphertextLen);
340  //Conversion failed?
341  if(error)
342  break;
343 
344  //Apply the RSADP decryption primitive
345  error = rsadp(key, &c, &m);
346  //Any error to report?
347  if(error)
348  break;
349 
350  //Convert the message representative m to an encoded message EM of
351  //length k octets
352  error = mpiWriteRaw(&m, em, k);
353  //Conversion failed?
354  if(error)
355  break;
356 
357  //Debug message
358  TRACE_DEBUG(" Encoded message:\r\n");
359  TRACE_DEBUG_ARRAY(" ", em, k);
360 
361  //EME-PKCS1-v1_5 decoding
362  badPadding = emePkcs1v15Decode(em, k, &n);
363 
364  //Check whether the output buffer is large enough to hold the decrypted
365  //message
366  badLength = CRYPTO_TEST_LT_32(messageSize, n);
367 
368  //Copy the decrypted message, byte per byte
369  for(i = 0; i < messageSize; i++)
370  {
371  //Read the whole encoded message EM
372  for(b = 0, j = 0; j < k; j++)
373  {
374  //Constant time implementation
375  a = CRYPTO_TEST_EQ_32(j, k - n + i);
376  b = CRYPTO_SELECT_8(b, em[j], a);
377  }
378 
379  //Save the value of the current byte
380  message[i] = b;
381  }
382 
383  //Return the length of the decrypted message
384  *messageLen = CRYPTO_SELECT_32(n, messageSize, badLength);
385 
386  //Check whether the decryption operation is successful
387  error = (error_t) CRYPTO_SELECT_32(error, ERROR_BUFFER_OVERFLOW, badLength);
388  error = (error_t) CRYPTO_SELECT_32(error, ERROR_DECRYPTION_FAILED, badPadding);
389 
390  //Debug message
391  TRACE_DEBUG(" Message:\r\n");
392  TRACE_DEBUG_ARRAY(" ", message, *messageLen);
393 
394  //End of exception handling block
395  } while(0);
396 
397  //Release the encoded message
398  cryptoFreeMem(em);
399 
400  //Release multiple precision integers
401  mpiFree(&c);
402  mpiFree(&m);
403 
404  //Return status code
405  return error;
406 }
407 
408 
409 /**
410  * @brief RSAES-OAEP encryption operation
411  * @param[in] prngAlgo PRNG algorithm
412  * @param[in] prngContext Pointer to the PRNG context
413  * @param[in] key Recipient's RSA public key
414  * @param[in] hash Underlying hash function
415  * @param[in] label Optional label to be associated with the message
416  * @param[in] message Message to be encrypted
417  * @param[in] messageLen Length of the message to be encrypted
418  * @param[out] ciphertext Ciphertext resulting from the encryption operation
419  * @param[out] ciphertextLen Length of the resulting ciphertext
420  * @return Error code
421  **/
422 
423 error_t rsaesOaepEncrypt(const PrngAlgo *prngAlgo, void *prngContext,
424  const RsaPublicKey *key, const HashAlgo *hash, const char_t *label,
425  const uint8_t *message, size_t messageLen, uint8_t *ciphertext,
426  size_t *ciphertextLen)
427 {
428  error_t error;
429  uint_t k;
430  uint8_t *em;
431  Mpi m;
432  Mpi c;
433 
434  //Check parameters
435  if(prngAlgo == NULL || prngContext == NULL)
437  if(key == NULL || message == NULL)
439  if(ciphertext == NULL || ciphertextLen == NULL)
441 
442  //Debug message
443  TRACE_DEBUG("RSAES-OAEP encryption...\r\n");
444  TRACE_DEBUG(" Modulus:\r\n");
445  TRACE_DEBUG_MPI(" ", &key->n);
446  TRACE_DEBUG(" Public exponent:\r\n");
447  TRACE_DEBUG_MPI(" ", &key->e);
448  TRACE_DEBUG(" Message:\r\n");
449  TRACE_DEBUG_ARRAY(" ", message, messageLen);
450 
451  //Initialize multiple-precision integers
452  mpiInit(&m);
453  mpiInit(&c);
454 
455  //Get the length in octets of the modulus n
456  k = mpiGetByteLength(&key->n);
457 
458  //Make sure the modulus is valid
459  if(k == 0)
461 
462  //Point to the buffer where the encoded message EM will be formatted
463  em = ciphertext;
464 
465  //EME-OAEP encoding
466  error = emeOaepEncode(prngAlgo, prngContext, hash, label, message,
467  messageLen, em, k);
468  //Any error to report?
469  if(error)
470  return error;
471 
472  //Debug message
473  TRACE_DEBUG(" Encoded message:\r\n");
474  TRACE_DEBUG_ARRAY(" ", em, k);
475 
476  //Start of exception handling block
477  do
478  {
479  //Convert the encoded message EM to an integer message representative m
480  error = mpiReadRaw(&m, em, k);
481  //Conversion failed?
482  if(error)
483  break;
484 
485  //Apply the RSAEP encryption primitive
486  error = rsaep(key, &m, &c);
487  //Any error to report?
488  if(error)
489  break;
490 
491  //Convert the ciphertext representative c to a ciphertext of length k octets
492  error = mpiWriteRaw(&c, ciphertext, k);
493  //Conversion failed?
494  if(error)
495  break;
496 
497  //Length of the resulting ciphertext
498  *ciphertextLen = k;
499 
500  //Debug message
501  TRACE_DEBUG(" Ciphertext:\r\n");
502  TRACE_DEBUG_ARRAY(" ", ciphertext, *ciphertextLen);
503 
504  //End of exception handling block
505  } while(0);
506 
507  //Free previously allocated memory
508  mpiFree(&m);
509  mpiFree(&c);
510 
511  //Return status code
512  return error;
513 }
514 
515 
516 /**
517  * @brief RSAES-OAEP decryption operation
518  * @param[in] key Recipient's RSA private key
519  * @param[in] hash Underlying hash function
520  * @param[in] label Optional label to be associated with the message
521  * @param[in] ciphertext Ciphertext to be decrypted
522  * @param[in] ciphertextLen Length of the ciphertext to be decrypted
523  * @param[out] message Output buffer where to store the decrypted message
524  * @param[in] messageSize Size of the output buffer
525  * @param[out] messageLen Length of the decrypted message
526  * @return Error code
527  **/
528 
530  const char_t *label, const uint8_t *ciphertext, size_t ciphertextLen,
531  uint8_t *message, size_t messageSize, size_t *messageLen)
532 {
533  error_t error;
534  uint_t k;
535  size_t i;
536  size_t j;
537  size_t n;
538  uint8_t b;
539  uint32_t a;
540  uint32_t badPadding;
541  uint32_t badLength;
542  uint8_t *em;
543  Mpi c;
544  Mpi m;
545 
546  //Check parameters
547  if(key == NULL || ciphertext == NULL)
549  if(message == NULL || messageSize == 0 || messageLen == NULL)
551 
552  //Debug message
553  TRACE_DEBUG("RSAES-OAEP decryption...\r\n");
554  TRACE_DEBUG(" Modulus:\r\n");
555  TRACE_DEBUG_MPI(" ", &key->n);
556  TRACE_DEBUG(" Public exponent:\r\n");
557  TRACE_DEBUG_MPI(" ", &key->e);
558  TRACE_DEBUG(" Private exponent:\r\n");
559  TRACE_DEBUG_MPI(" ", &key->d);
560  TRACE_DEBUG(" Prime 1:\r\n");
561  TRACE_DEBUG_MPI(" ", &key->p);
562  TRACE_DEBUG(" Prime 2:\r\n");
563  TRACE_DEBUG_MPI(" ", &key->q);
564  TRACE_DEBUG(" Prime exponent 1:\r\n");
565  TRACE_DEBUG_MPI(" ", &key->dp);
566  TRACE_DEBUG(" Prime exponent 2:\r\n");
567  TRACE_DEBUG_MPI(" ", &key->dq);
568  TRACE_DEBUG(" Coefficient:\r\n");
569  TRACE_DEBUG_MPI(" ", &key->qinv);
570  TRACE_DEBUG(" Ciphertext:\r\n");
571  TRACE_DEBUG_ARRAY(" ", ciphertext, ciphertextLen);
572 
573  //Initialize multiple-precision integers
574  mpiInit(&c);
575  mpiInit(&m);
576 
577  //Get the length in octets of the modulus n
578  k = mpiGetByteLength(&key->n);
579 
580  //Check the length of the modulus
581  if(k < (2 * hash->digestSize + 2))
583 
584  //Check the length of the ciphertext
585  if(ciphertextLen != k)
586  return ERROR_INVALID_LENGTH;
587 
588  //Allocate a buffer to store the encoded message EM
589  em = cryptoAllocMem(k);
590  //Failed to allocate memory?
591  if(em == NULL)
592  return ERROR_OUT_OF_MEMORY;
593 
594  //Start of exception handling block
595  do
596  {
597  //Convert the ciphertext to an integer ciphertext representative c
598  error = mpiReadRaw(&c, ciphertext, ciphertextLen);
599  //Conversion failed?
600  if(error)
601  break;
602 
603  //Apply the RSADP decryption primitive
604  error = rsadp(key, &c, &m);
605  //Any error to report?
606  if(error)
607  break;
608 
609  //Convert the message representative m to an encoded message EM of
610  //length k octets
611  error = mpiWriteRaw(&m, em, k);
612  //Conversion failed?
613  if(error)
614  break;
615 
616  //Debug message
617  TRACE_DEBUG(" Encoded message:\r\n");
618  TRACE_DEBUG_ARRAY(" ", em, k);
619 
620  //EME-OAEP decoding
621  badPadding = emeOaepDecode(hash, label, em, k, &n);
622 
623  //Check whether the output buffer is large enough to hold the decrypted
624  //message
625  badLength = CRYPTO_TEST_LT_32(messageSize, n);
626 
627  //Copy the decrypted message, byte per byte
628  for(i = 0; i < messageSize; i++)
629  {
630  //Read the whole encoded message EM
631  for(b = 0, j = 0; j < k; j++)
632  {
633  //Constant time implementation
634  a = CRYPTO_TEST_EQ_32(j, k - n + i);
635  b = CRYPTO_SELECT_8(b, em[j], a);
636  }
637 
638  //Save the value of the current byte
639  message[i] = b;
640  }
641 
642  //Return the length of the decrypted message
643  *messageLen = CRYPTO_SELECT_32(n, messageSize, badLength);
644 
645  //Check whether the decryption operation is successful
646  error = (error_t) CRYPTO_SELECT_32(error, ERROR_BUFFER_OVERFLOW, badLength);
647  error = (error_t) CRYPTO_SELECT_32(error, ERROR_DECRYPTION_FAILED, badPadding);
648 
649  //Debug message
650  TRACE_DEBUG(" Message:\r\n");
651  TRACE_DEBUG_ARRAY(" ", message, *messageLen);
652 
653  //End of exception handling block
654  } while(0);
655 
656  //Release the encoded message
657  cryptoFreeMem(em);
658 
659  //Release multiple precision integers
660  mpiFree(&c);
661  mpiFree(&m);
662 
663  //Return status code
664  return error;
665 }
666 
667 
668 /**
669  * @brief RSASSA-PKCS1-v1_5 signature generation operation
670  * @param[in] key Signer's RSA private key
671  * @param[in] hash Hash function used to digest the message
672  * @param[in] digest Digest of the message to be signed
673  * @param[out] signature Resulting signature
674  * @param[out] signatureLen Length of the resulting signature
675  * @return Error code
676  **/
677 
679  const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
680 {
681  error_t error;
682  uint_t k;
683  uint8_t *em;
684  Mpi m;
685  Mpi s;
686  Mpi t;
687 
688  //Check parameters
689  if(key == NULL || hash == NULL || digest == NULL)
691  if(signature == NULL || signatureLen == NULL)
693 
694  //Debug message
695  TRACE_DEBUG("RSASSA-PKCS1-v1_5 signature generation...\r\n");
696  TRACE_DEBUG(" Modulus:\r\n");
697  TRACE_DEBUG_MPI(" ", &key->n);
698  TRACE_DEBUG(" Public exponent:\r\n");
699  TRACE_DEBUG_MPI(" ", &key->e);
700  TRACE_DEBUG(" Private exponent:\r\n");
701  TRACE_DEBUG_MPI(" ", &key->d);
702  TRACE_DEBUG(" Prime 1:\r\n");
703  TRACE_DEBUG_MPI(" ", &key->p);
704  TRACE_DEBUG(" Prime 2:\r\n");
705  TRACE_DEBUG_MPI(" ", &key->q);
706  TRACE_DEBUG(" Prime exponent 1:\r\n");
707  TRACE_DEBUG_MPI(" ", &key->dp);
708  TRACE_DEBUG(" Prime exponent 2:\r\n");
709  TRACE_DEBUG_MPI(" ", &key->dq);
710  TRACE_DEBUG(" Coefficient:\r\n");
711  TRACE_DEBUG_MPI(" ", &key->qinv);
712  TRACE_DEBUG(" Message digest:\r\n");
713  TRACE_DEBUG_ARRAY(" ", digest, hash->digestSize);
714 
715  //Initialize multiple-precision integers
716  mpiInit(&m);
717  mpiInit(&s);
718  mpiInit(&t);
719 
720  //Get the length in octets of the modulus n
721  k = mpiGetByteLength(&key->n);
722  //Point to the buffer where the encoded message EM will be formatted
723  em = signature;
724 
725  //Apply the EMSA-PKCS1-v1.5 encoding operation
726  error = emsaPkcs1v15Encode(hash, digest, em, k);
727  //Any error to report?
728  if(error)
729  return error;
730 
731  //Debug message
732  TRACE_DEBUG(" Encoded message:\r\n");
733  TRACE_DEBUG_ARRAY(" ", em, k);
734 
735  //Start of exception handling block
736  do
737  {
738  //Convert the encoded message EM to an integer message representative m
739  error = mpiReadRaw(&m, em, k);
740  //Conversion failed?
741  if(error)
742  break;
743 
744  //Apply the RSASP1 signature primitive
745  error = rsasp1(key, &m, &s);
746  //Any error to report?
747  if(error)
748  break;
749 
750  //When unprotected, RSA–CRT is vulnerable to the Bellcore attack
751  if(key->n.size && key->e.size && key->p.size && key->q.size &&
752  key->dp.size && key->dq.size && key->qinv.size)
753  {
754  RsaPublicKey publicKey;
755 
756  //Retrieve modulus and public exponent
757  publicKey.n = key->n;
758  publicKey.e = key->e;
759 
760  //Apply the RSAVP1 verification primitive
761  error = rsavp1(&publicKey, &s, &t);
762  //Any error to report?
763  if(error)
764  break;
765 
766  //Verify the RSA signature in order to protect against RSA-CRT key leak
767  if(mpiComp(&t, &m) != 0)
768  {
769  //A signature fault has been detected
770  error = ERROR_FAILURE;
771  break;
772  }
773  }
774 
775  //Convert the signature representative s to a signature of length k octets
776  error = mpiWriteRaw(&s, signature, k);
777  //Conversion failed?
778  if(error)
779  break;
780 
781  //Length of the resulting signature
782  *signatureLen = k;
783 
784  //Debug message
785  TRACE_DEBUG(" Signature:\r\n");
786  TRACE_DEBUG_ARRAY(" ", signature, *signatureLen);
787 
788  //End of exception handling block
789  } while(0);
790 
791  //Free previously allocated memory
792  mpiFree(&m);
793  mpiFree(&s);
794  mpiFree(&t);
795 
796  //Return status code
797  return error;
798 }
799 
800 
801 /**
802  * @brief RSASSA-PKCS1-v1_5 signature verification operation
803  * @param[in] key Signer's RSA public key
804  * @param[in] hash Hash function used to digest the message
805  * @param[in] digest Digest of the message whose signature is to be verified
806  * @param[in] signature Signature to be verified
807  * @param[in] signatureLen Length of the signature to be verified
808  * @return Error code
809  **/
810 
812  const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
813 {
814  error_t error;
815  uint_t k;
816  uint8_t *em;
817  Mpi s;
818  Mpi m;
819 
820  //Check parameters
821  if(key == NULL || hash == NULL || digest == NULL || signature == NULL)
823 
824  //Debug message
825  TRACE_DEBUG("RSASSA-PKCS1-v1_5 signature verification...\r\n");
826  TRACE_DEBUG(" Modulus:\r\n");
827  TRACE_DEBUG_MPI(" ", &key->n);
828  TRACE_DEBUG(" Public exponent:\r\n");
829  TRACE_DEBUG_MPI(" ", &key->e);
830  TRACE_DEBUG(" Message digest:\r\n");
831  TRACE_DEBUG_ARRAY(" ", digest, hash->digestSize);
832  TRACE_DEBUG(" Signature:\r\n");
833  TRACE_DEBUG_ARRAY(" ", signature, signatureLen);
834 
835  //Initialize multiple-precision integers
836  mpiInit(&s);
837  mpiInit(&m);
838 
839  //Get the length in octets of the modulus n
840  k = mpiGetByteLength(&key->n);
841 
842  //Make sure the modulus is valid
843  if(k == 0)
845 
846  //Check the length of the signature
847  if(signatureLen != k)
849 
850  //Allocate a memory buffer to hold the encoded message
851  em = cryptoAllocMem(k);
852  //Failed to allocate memory?
853  if(em == NULL)
854  return ERROR_OUT_OF_MEMORY;
855 
856  //Start of exception handling block
857  do
858  {
859  //Convert the signature to an integer signature representative s
860  error = mpiReadRaw(&s, signature, signatureLen);
861  //Conversion failed?
862  if(error)
863  break;
864 
865  //Apply the RSAVP1 verification primitive
866  error = rsavp1(key, &s, &m);
867  //Any error to report?
868  if(error)
869  break;
870 
871  //Convert the message representative m to an encoded message EM of
872  //length k octets
873  error = mpiWriteRaw(&m, em, k);
874  //Conversion failed?
875  if(error)
876  break;
877 
878  //Debug message
879  TRACE_DEBUG(" Encoded message:\r\n");
880  TRACE_DEBUG_ARRAY(" ", em, k);
881 
882  //Verify the encoded message EM
883  error = emsaPkcs1v15Verify(hash, digest, em, k);
884  //Any error to report?
885  if(error)
886  {
887  //The signature is not valid
888  error = ERROR_INVALID_SIGNATURE;
889  break;
890  }
891 
892  //End of exception handling block
893  } while(0);
894 
895  //Release the encoded message
896  cryptoFreeMem(em);
897 
898  //Release multiple precision integers
899  mpiFree(&s);
900  mpiFree(&m);
901 
902  //Return status code
903  return error;
904 }
905 
906 
907 /**
908  * @brief RSASSA-PSS signature generation operation
909  * @param[in] prngAlgo PRNG algorithm
910  * @param[in] prngContext Pointer to the PRNG context
911  * @param[in] key Signer's RSA private key
912  * @param[in] hash Hash function used to digest the message
913  * @param[in] saltLen Length of the salt, in bytes
914  * @param[in] digest Digest of the message to be signed
915  * @param[out] signature Resulting signature
916  * @param[out] signatureLen Length of the resulting signature
917  * @return Error code
918  **/
919 
920 error_t rsassaPssSign(const PrngAlgo *prngAlgo, void *prngContext,
921  const RsaPrivateKey *key, const HashAlgo *hash, size_t saltLen,
922  const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
923 {
924  error_t error;
925  uint_t k;
926  uint_t modBits;
927  uint8_t *em;
928  Mpi m;
929  Mpi s;
930 
931  //Check parameters
932  if(prngAlgo == NULL || prngContext == NULL)
934  if(key == NULL || hash == NULL || digest == NULL)
936  if(signature == NULL || signatureLen == NULL)
938 
939  //Debug message
940  TRACE_DEBUG("RSASSA-PSS signature generation...\r\n");
941  TRACE_DEBUG(" Modulus:\r\n");
942  TRACE_DEBUG_MPI(" ", &key->n);
943  TRACE_DEBUG(" Public exponent:\r\n");
944  TRACE_DEBUG_MPI(" ", &key->e);
945  TRACE_DEBUG(" Private exponent:\r\n");
946  TRACE_DEBUG_MPI(" ", &key->d);
947  TRACE_DEBUG(" Prime 1:\r\n");
948  TRACE_DEBUG_MPI(" ", &key->p);
949  TRACE_DEBUG(" Prime 2:\r\n");
950  TRACE_DEBUG_MPI(" ", &key->q);
951  TRACE_DEBUG(" Prime exponent 1:\r\n");
952  TRACE_DEBUG_MPI(" ", &key->dp);
953  TRACE_DEBUG(" Prime exponent 2:\r\n");
954  TRACE_DEBUG_MPI(" ", &key->dq);
955  TRACE_DEBUG(" Coefficient:\r\n");
956  TRACE_DEBUG_MPI(" ", &key->qinv);
957  TRACE_DEBUG(" Message digest:\r\n");
958  TRACE_DEBUG_ARRAY(" ", digest, hash->digestSize);
959 
960  //Initialize multiple-precision integers
961  mpiInit(&m);
962  mpiInit(&s);
963 
964  //modBits is the length in bits of the modulus n
965  modBits = mpiGetBitLength(&key->n);
966 
967  //Make sure the modulus is valid
968  if(modBits == 0)
970 
971  //Calculate the length in octets of the modulus n
972  k = (modBits + 7) / 8;
973 
974  //Point to the buffer where the encoded message EM will be formatted
975  em = signature;
976 
977  //Apply the EMSA-PSS encoding operation to the message M to produce an
978  //encoded message EM of length ceil((modBits - 1) / 8) octets
979  error = emsaPssEncode(prngAlgo, prngContext, hash, saltLen, digest,
980  em, modBits - 1);
981  //Any error to report?
982  if(error)
983  return error;
984 
985  //Debug message
986  TRACE_DEBUG(" Encoded message:\r\n");
987  TRACE_DEBUG_ARRAY(" ", em, (modBits + 6) / 8);
988 
989  //Start of exception handling block
990  do
991  {
992  //Convert the encoded message EM to an integer message representative m
993  error = mpiReadRaw(&m, em, (modBits + 6) / 8);
994  //Conversion failed?
995  if(error)
996  break;
997 
998  //Apply the RSASP1 signature primitive
999  error = rsasp1(key, &m, &s);
1000  //Any error to report?
1001  if(error)
1002  break;
1003 
1004  //Convert the signature representative s to a signature of length k octets
1005  error = mpiWriteRaw(&s, signature, k);
1006  //Conversion failed?
1007  if(error)
1008  break;
1009 
1010  //Length of the resulting signature
1011  *signatureLen = k;
1012 
1013  //Debug message
1014  TRACE_DEBUG(" Signature:\r\n");
1015  TRACE_DEBUG_ARRAY(" ", signature, *signatureLen);
1016 
1017  //End of exception handling block
1018  } while(0);
1019 
1020  //Free previously allocated memory
1021  mpiFree(&m);
1022  mpiFree(&s);
1023 
1024  //Return status code
1025  return error;
1026 }
1027 
1028 
1029 /**
1030  * @brief RSASSA-PSS signature verification operation
1031  * @param[in] key Signer's RSA public key
1032  * @param[in] hash Hash function used to digest the message
1033  * @param[in] saltLen Length of the salt, in bytes
1034  * @param[in] digest Digest of the message whose signature is to be verified
1035  * @param[in] signature Signature to be verified
1036  * @param[in] signatureLen Length of the signature to be verified
1037  * @return Error code
1038  **/
1039 
1041  size_t saltLen, const uint8_t *digest, const uint8_t *signature,
1042  size_t signatureLen)
1043 {
1044  error_t error;
1045  uint_t k;
1046  uint_t modBits;
1047  uint8_t *em;
1048  Mpi s;
1049  Mpi m;
1050 
1051  //Check parameters
1052  if(key == NULL || hash == NULL || digest == NULL || signature == NULL)
1053  return ERROR_INVALID_PARAMETER;
1054 
1055  //Debug message
1056  TRACE_DEBUG("RSASSA-PSS signature verification...\r\n");
1057  TRACE_DEBUG(" Modulus:\r\n");
1058  TRACE_DEBUG_MPI(" ", &key->n);
1059  TRACE_DEBUG(" Public exponent:\r\n");
1060  TRACE_DEBUG_MPI(" ", &key->e);
1061  TRACE_DEBUG(" Message digest:\r\n");
1062  TRACE_DEBUG_ARRAY(" ", digest, hash->digestSize);
1063  TRACE_DEBUG(" Signature:\r\n");
1064  TRACE_DEBUG_ARRAY(" ", signature, signatureLen);
1065 
1066  //Initialize multiple-precision integers
1067  mpiInit(&s);
1068  mpiInit(&m);
1069 
1070  //modBits is the length in bits of the modulus n
1071  modBits = mpiGetBitLength(&key->n);
1072 
1073  //Make sure the modulus is valid
1074  if(modBits == 0)
1075  return ERROR_INVALID_PARAMETER;
1076 
1077  //Calculate the length in octets of the modulus n
1078  k = (modBits + 7) / 8;
1079 
1080  //Check the length of the signature
1081  if(signatureLen != k)
1082  return ERROR_INVALID_SIGNATURE;
1083 
1084  //Allocate a memory buffer to hold the encoded message
1085  em = cryptoAllocMem(k);
1086  //Failed to allocate memory?
1087  if(em == NULL)
1088  return ERROR_OUT_OF_MEMORY;
1089 
1090  //Start of exception handling block
1091  do
1092  {
1093  //Convert the signature to an integer signature representative s
1094  error = mpiReadRaw(&s, signature, signatureLen);
1095  //Conversion failed?
1096  if(error)
1097  break;
1098 
1099  //Apply the RSAVP1 verification primitive
1100  error = rsavp1(key, &s, &m);
1101  //Any error to report?
1102  if(error)
1103  break;
1104 
1105  //Convert the message representative m to an encoded message EM of
1106  //length emLen = ceil((modBits - 1) / 8) octets
1107  error = mpiWriteRaw(&m, em, (modBits + 6) / 8);
1108  //Conversion failed?
1109  if(error)
1110  break;
1111 
1112  //Debug message
1113  TRACE_DEBUG(" Encoded message:\r\n");
1114  TRACE_DEBUG_ARRAY(" ", em, (modBits + 6) / 8);
1115 
1116  //Apply the EMSA-PSS verification operation to the message M and the
1117  //encoded message EM to determine whether they are consistent
1118  error = emsaPssVerify(hash, saltLen, digest, em, modBits - 1);
1119  //Any error to report?
1120  if(error)
1121  {
1122  //The signature is not valid
1123  error = ERROR_INVALID_SIGNATURE;
1124  break;
1125  }
1126 
1127  //End of exception handling block
1128  } while(0);
1129 
1130  //Release the encoded message
1131  cryptoFreeMem(em);
1132 
1133  //Release multiple precision integers
1134  mpiFree(&s);
1135  mpiFree(&m);
1136 
1137  //Return status code
1138  return error;
1139 }
1140 
1141 
1142 /**
1143  * @brief RSA encryption primitive
1144  *
1145  * The RSA encryption primitive produces a ciphertext representative from
1146  * a message representative under the control of a public key
1147  *
1148  * @param[in] key RSA public key
1149  * @param[in] m Message representative
1150  * @param[out] c Ciphertext representative
1151  * @return Error code
1152  **/
1153 
1154 error_t rsaep(const RsaPublicKey *key, const Mpi *m, Mpi *c)
1155 {
1156  //Ensure the RSA public key is valid
1157  if(!key->n.size || !key->e.size)
1158  return ERROR_INVALID_PARAMETER;
1159 
1160  //The message representative m shall be between 0 and n - 1
1161  if(mpiCompInt(m, 0) < 0 || mpiComp(m, &key->n) >= 0)
1162  return ERROR_OUT_OF_RANGE;
1163 
1164  //Perform modular exponentiation (c = m ^ e mod n)
1165  return mpiExpMod(c, m, &key->e, &key->n);
1166 }
1167 
1168 
1169 /**
1170  * @brief RSA decryption primitive
1171  *
1172  * The RSA decryption primitive recovers the message representative from
1173  * the ciphertext representative under the control of a private key
1174  *
1175  * @param[in] key RSA private key
1176  * @param[in] c Ciphertext representative
1177  * @param[out] m Message representative
1178  * @return Error code
1179  **/
1180 
1181 __weak error_t rsadp(const RsaPrivateKey *key, const Mpi *c, Mpi *m)
1182 {
1183  error_t error;
1184  Mpi m1;
1185  Mpi m2;
1186  Mpi h;
1187 
1188  //The ciphertext representative c shall be between 0 and n - 1
1189  if(mpiCompInt(c, 0) < 0 || mpiComp(c, &key->n) >= 0)
1190  return ERROR_OUT_OF_RANGE;
1191 
1192  //Initialize multiple-precision integers
1193  mpiInit(&m1);
1194  mpiInit(&m2);
1195  mpiInit(&h);
1196 
1197  //Use the Chinese remainder algorithm?
1198  if(key->n.size && key->p.size && key->q.size &&
1199  key->dp.size && key->dq.size && key->qinv.size)
1200  {
1201  //Compute m1 = c ^ dP mod p
1202  MPI_CHECK(mpiExpMod(&m1, c, &key->dp, &key->p));
1203  //Compute m2 = c ^ dQ mod q
1204  MPI_CHECK(mpiExpMod(&m2, c, &key->dq, &key->q));
1205  //Let h = (m1 - m2) * qInv mod p
1206  MPI_CHECK(mpiSub(&h, &m1, &m2));
1207  MPI_CHECK(mpiMulMod(&h, &h, &key->qinv, &key->p));
1208  //Let m = m2 + q * h
1209  MPI_CHECK(mpiMul(m, &key->q, &h));
1210  MPI_CHECK(mpiAdd(m, m, &m2));
1211  }
1212  //Use modular exponentiation?
1213  else if(key->n.size && key->d.size)
1214  {
1215  //Let m = c ^ d mod n
1216  error = mpiExpMod(m, c, &key->d, &key->n);
1217  }
1218  //Invalid parameters?
1219  else
1220  {
1221  //Report an error
1222  error = ERROR_INVALID_PARAMETER;
1223  }
1224 
1225 end:
1226  //Free previously allocated memory
1227  mpiFree(&m1);
1228  mpiFree(&m2);
1229  mpiFree(&h);
1230 
1231  //Return status code
1232  return error;
1233 }
1234 
1235 
1236 /**
1237  * @brief RSA signature primitive
1238  *
1239  * The RSA signature primitive produces a signature representative from
1240  * a message representative under the control of a private key
1241  *
1242  * @param[in] key RSA private key
1243  * @param[in] m Message representative
1244  * @param[out] s Signature representative
1245  * @return Error code
1246  **/
1247 
1248 error_t rsasp1(const RsaPrivateKey *key, const Mpi *m, Mpi *s)
1249 {
1250  //RSASP1 primitive is the same as RSADP except for the names of its input
1251  //and output arguments. They are distinguished as they are intended for
1252  //different purposes
1253  return rsadp(key, m, s);
1254 }
1255 
1256 
1257 /**
1258  * @brief RSA verification primitive
1259  *
1260  * The RSA verification primitive recovers the message representative from
1261  * the signature representative under the control of a public key
1262  *
1263  * @param[in] key RSA public key
1264  * @param[in] s Signature representative
1265  * @param[out] m Message representative
1266  * @return Error code
1267  **/
1268 
1269 error_t rsavp1(const RsaPublicKey *key, const Mpi *s, Mpi *m)
1270 {
1271  //RSAVP1 primitive is the same as RSAEP except for the names of its input
1272  //and output arguments. They are distinguished as they are intended for
1273  //different purposes
1274  return rsaep(key, s, m);
1275 }
1276 
1277 
1278 /**
1279  * @brief EME-PKCS1-v1_5 encoding operation
1280  * @param[in] prngAlgo PRNG algorithm
1281  * @param[in] prngContext Pointer to the PRNG context
1282  * @param[in] message Message to be encrypted
1283  * @param[in] messageLen Length of the message to be encrypted
1284  * @param[out] em Encoded message
1285  * @param[in] k Length of the encoded message
1286  * @return Error code
1287  **/
1288 
1289 error_t emePkcs1v15Encode(const PrngAlgo *prngAlgo, void *prngContext,
1290  const uint8_t *message, size_t messageLen, uint8_t *em, size_t k)
1291 {
1292  error_t error;
1293  size_t i;
1294  size_t j;
1295  size_t n;
1296  uint8_t *p;
1297 
1298  //Check the length of the message
1299  if((messageLen + 11) > k)
1300  return ERROR_INVALID_LENGTH;
1301 
1302  //The leading 0x00 octet ensures that the encoded message, converted to
1303  //an integer, is less than the modulus
1304  em[0] = 0x00;
1305  //For a public-key operation, the block type BT shall be 0x02
1306  em[1] = 0x02;
1307 
1308  //Point to the buffer where to format the padding string PS
1309  p = em + 2;
1310  //Determine the length of the padding string
1311  n = k - messageLen - 3;
1312 
1313  //Generate an octet string PS of length k - mLen - 3 consisting of
1314  //pseudo-randomly generated nonzero octets
1315  while(n > 0)
1316  {
1317  //Generate random data
1318  error = prngAlgo->read(prngContext, p, n);
1319  //Any error to report?
1320  if(error)
1321  return error;
1322 
1323  //Parse the resulting octet string
1324  for(i = 0, j = 0; j < n; j++)
1325  {
1326  //Strip any byte with a value of zero
1327  if(p[j] != 0)
1328  {
1329  p[i++] = p[j];
1330  }
1331  }
1332 
1333  //Advance data pointer
1334  p += i;
1335  n -= i;
1336  }
1337 
1338  //Append a 0x00 octet to the padding string
1339  *p = 0x00;
1340 
1341  //Copy the message to be encrypted
1342  cryptoMemcpy(p + 1, message, messageLen);
1343 
1344  //Successful processing
1345  return NO_ERROR;
1346 }
1347 
1348 
1349 /**
1350  * @brief EME-PKCS1-v1_5 decoding operation
1351  * @param[in] em Encoded message
1352  * @param[in] k Length of the encoded message
1353  * @param[out] messageLen Length of the decrypted message
1354  * @return The function returns 0 on success, 1 on failure
1355  **/
1356 
1357 uint32_t emePkcs1v15Decode(uint8_t *em, size_t k, size_t *messageLen)
1358 {
1359  size_t i;
1360  size_t m;
1361  uint32_t c;
1362  uint32_t bad;
1363 
1364  //Separate the encoded message EM into an octet string PS consisting of
1365  //nonzero octets and a message M
1366  for(m = 0, i = 2; i < k; i++)
1367  {
1368  //Constant time implementation
1369  c = CRYPTO_TEST_Z_8(em[i]);
1370  c &= CRYPTO_TEST_Z_32(m);
1371  m = CRYPTO_SELECT_32(m, i, c);
1372  }
1373 
1374  //If the first octet of EM does not have hexadecimal value 0x00, then
1375  //report a decryption error
1376  bad = CRYPTO_TEST_NEQ_8(em[0], 0x00);
1377 
1378  //If the second octet of EM does not have hexadecimal value 0x02, then
1379  //report a decryption error
1380  bad |= CRYPTO_TEST_NEQ_8(em[1], 0x02);
1381 
1382  //If there is no octet with hexadecimal value 0x00 to separate PS from M,
1383  //then report a decryption error
1384  bad |= CRYPTO_TEST_Z_32(m);
1385 
1386  //If the length of PS is less than 8 octets, then report a decryption error
1387  bad |= CRYPTO_TEST_LT_32(m, 10);
1388 
1389  //Return the length of the decrypted message
1390  *messageLen = CRYPTO_SELECT_32(k - m - 1, 0, bad);
1391 
1392  //Care must be taken to ensure that an opponent cannot distinguish the
1393  //different error conditions, whether by error message or timing
1394  return bad;
1395 }
1396 
1397 
1398 /**
1399  * @brief EME-OAEP encoding operation
1400  * @param[in] prngAlgo PRNG algorithm
1401  * @param[in] prngContext Pointer to the PRNG context
1402  * @param[in] hash Underlying hash function
1403  * @param[in] label Optional label to be associated with the message
1404  * @param[in] message Message to be encrypted
1405  * @param[in] messageLen Length of the message to be encrypted
1406  * @param[out] em Encoded message
1407  * @param[in] k Length of the encoded message
1408  * @return Error code
1409  **/
1410 
1411 error_t emeOaepEncode(const PrngAlgo *prngAlgo, void *prngContext,
1412  const HashAlgo *hash, const char_t *label, const uint8_t *message,
1413  size_t messageLen, uint8_t *em, size_t k)
1414 {
1415  error_t error;
1416  size_t n;
1417  uint8_t *db;
1418  uint8_t *seed;
1419  HashContext *hashContext;
1420 
1421  //Check the length of the message
1422  if(messageLen > (k - 2 * hash->digestSize - 2))
1423  return ERROR_INVALID_LENGTH;
1424 
1425  //Point to the buffer where to format the seed
1426  seed = em + 1;
1427  //Point to the buffer where to format the data block
1428  db = em + hash->digestSize + 1;
1429 
1430  //Generate a random octet string seed of length hLen
1431  error = prngAlgo->read(prngContext, seed, hash->digestSize);
1432  //Any error to report?
1433  if(error)
1434  return error;
1435 
1436  //Allocate a memory buffer to hold the hash context
1437  hashContext = cryptoAllocMem(hash->contextSize);
1438  //Failed to allocate memory?
1439  if(hashContext == NULL)
1440  return ERROR_OUT_OF_MEMORY;
1441 
1442  //If the label L is not provided, let L be the empty string
1443  if(label == NULL)
1444  label = "";
1445 
1446  //Let lHash = Hash(L)
1447  hash->init(hashContext);
1448  hash->update(hashContext, label, cryptoStrlen(label));
1449  hash->final(hashContext, db);
1450 
1451  //The padding string PS consists of k - mLen - 2hLen - 2 zero octets
1452  n = k - messageLen - 2 * hash->digestSize - 2;
1453  //Generate the padding string
1454  cryptoMemset(db + hash->digestSize, 0, n);
1455 
1456  //Concatenate lHash, PS, a single octet with hexadecimal value 0x01, and
1457  //the message M to form a data block DB of length k - hLen - 1 octets
1458  db[hash->digestSize + n] = 0x01;
1459  cryptoMemcpy(db + hash->digestSize + n + 1, message, messageLen);
1460 
1461  //Calculate the length of the data block
1462  n = k - hash->digestSize - 1;
1463 
1464  //Let maskedDB = DB xor MGF(seed, k - hLen - 1)
1465  mgf1(hash, hashContext, seed, hash->digestSize, db, n);
1466  //Let maskedSeed = seed xor MGF(maskedDB, hLen)
1467  mgf1(hash, hashContext, db, n, seed, hash->digestSize);
1468 
1469  //Concatenate a single octet with hexadecimal value 0x00, maskedSeed, and
1470  //maskedDB to form an encoded message EM of length k octets
1471  em[0] = 0x00;
1472 
1473  //Release hash context
1474  cryptoFreeMem(hashContext);
1475 
1476  //Successful processing
1477  return NO_ERROR;
1478 }
1479 
1480 
1481 /**
1482  * @brief EME-OAEP decoding operation
1483  * @param[in] hash Underlying hash function
1484  * @param[in] label Optional label to be associated with the message
1485  * @param[in] em Encoded message
1486  * @param[in] k Length of the encoded message
1487  * @param[out] messageLen Length of the decrypted message
1488  * @return The function returns 0 on success, 1 on failure
1489  **/
1490 
1491 uint32_t emeOaepDecode(const HashAlgo *hash, const char_t *label, uint8_t *em,
1492  size_t k, size_t *messageLen)
1493 {
1494  size_t i;
1495  size_t m;
1496  size_t n;
1497  uint32_t c;
1498  uint32_t bad;
1499  uint8_t *db;
1500  uint8_t *seed;
1501  HashContext *hashContext;
1502  uint8_t lHash[MAX_HASH_DIGEST_SIZE];
1503 
1504  //Allocate a memory buffer to hold the hash context
1505  hashContext = cryptoAllocMem(hash->contextSize);
1506 
1507  //Successful memory allocation?
1508  if(hashContext != NULL)
1509  {
1510  //If the label L is not provided, let L be the empty string
1511  if(label == NULL)
1512  label = "";
1513 
1514  //Let lHash = Hash(L)
1515  hash->init(hashContext);
1516  hash->update(hashContext, label, cryptoStrlen(label));
1517  hash->final(hashContext, lHash);
1518 
1519  //Separate the encoded message EM into a single octet Y, an octet string
1520  //maskedSeed of length hLen, and an octet string maskedDB of length k - hLen - 1
1521  seed = em + 1;
1522  db = em + hash->digestSize + 1;
1523 
1524  //Calculate the length of the data block
1525  n = k - hash->digestSize - 1;
1526 
1527  //Let seed = maskedSeed xor MGF(maskedDB, hLen)
1528  mgf1(hash, hashContext, db, n, seed, hash->digestSize);
1529  //Let DB = maskedDB xor MGF(seed, k - hLen - 1)
1530  mgf1(hash, hashContext, seed, hash->digestSize, db, n);
1531 
1532  //Release hash context
1533  cryptoFreeMem(hashContext);
1534 
1535  //Separate DB into an octet string lHash' of length hLen, a padding string
1536  //PS consisting of octets with hexadecimal value 0x00, and a message M
1537  for(m = 0, i = hash->digestSize; i < n; i++)
1538  {
1539  //Constant time implementation
1540  c = CRYPTO_TEST_NZ_8(db[i]);
1541  c &= CRYPTO_TEST_Z_32(m);
1542  m = CRYPTO_SELECT_32(m, i, c);
1543  }
1544 
1545  //Make sure the padding string PS is terminated
1546  bad = CRYPTO_TEST_Z_32(m);
1547 
1548  //If there is no octet with hexadecimal value 0x01 to separate PS from M,
1549  //then report a decryption error
1550  bad |= CRYPTO_TEST_NEQ_8(db[m], 0x01);
1551 
1552  //If lHash does not equal lHash', then report a decryption error
1553  for(i = 0; i < hash->digestSize; i++)
1554  {
1555  bad |= CRYPTO_TEST_NEQ_8(db[i], lHash[i]);
1556  }
1557 
1558  //If Y is nonzero, then report a decryption error
1559  bad |= CRYPTO_TEST_NEQ_8(em[0], 0x00);
1560 
1561  //Return the length of the decrypted message
1562  *messageLen = CRYPTO_SELECT_32(n - m - 1, 0, bad);
1563  }
1564  else
1565  {
1566  //Failed to allocate memory
1567  bad = TRUE;
1568  }
1569 
1570  //Care must be taken to ensure that an opponent cannot distinguish the
1571  //different error conditions, whether by error message or timing
1572  return bad;
1573 }
1574 
1575 
1576 /**
1577  * @brief EMSA-PKCS1-v1_5 encoding operation
1578  * @param[in] hash Hash function used to digest the message
1579  * @param[in] digest Digest of the message to be signed
1580  * @param[out] em Encoded message
1581  * @param[in] emLen Intended length of the encoded message
1582  * @return Error code
1583  **/
1584 
1586  const uint8_t *digest, uint8_t *em, size_t emLen)
1587 {
1588  size_t i;
1589  size_t n;
1590 
1591  //Check the intended length of the encoded message
1592  if(emLen < (hash->oidSize + hash->digestSize + 21))
1593  return ERROR_INVALID_LENGTH;
1594 
1595  //Point to the first byte of the encoded message
1596  i = 0;
1597 
1598  //The leading 0x00 octet ensures that the encoded message, converted to
1599  //an integer, is less than the modulus
1600  em[i++] = 0x00;
1601  //Block type 0x01 is used for private-key operations
1602  em[i++] = 0x01;
1603 
1604  //Determine the length of the padding string PS
1605  n = emLen - hash->oidSize - hash->digestSize - 13;
1606 
1607  //Each byte of PS must be set to 0xFF when the block type is 0x01
1608  cryptoMemset(em + i, 0xFF, n);
1609  i += n;
1610 
1611  //Append a 0x00 octet to the padding string
1612  em[i++] = 0x00;
1613 
1614  //Encode the DigestInfo structure using ASN.1
1615  em[i++] = (uint8_t) (ASN1_ENCODING_CONSTRUCTED | ASN1_TYPE_SEQUENCE);
1616  em[i++] = (uint8_t) (hash->oidSize + hash->digestSize + 8);
1617  em[i++] = (uint8_t) (ASN1_ENCODING_CONSTRUCTED | ASN1_TYPE_SEQUENCE);
1618  em[i++] = (uint8_t) (hash->oidSize + 4);
1619  em[i++] = (uint8_t) ASN1_TYPE_OBJECT_IDENTIFIER;
1620  em[i++] = (uint8_t) hash->oidSize;
1621 
1622  //Copy the hash algorithm OID
1623  cryptoMemcpy(em + i, hash->oid, hash->oidSize);
1624  i += hash->oidSize;
1625 
1626  //Encode the rest of the ASN.1 structure
1627  em[i++] = (uint8_t) ASN1_TYPE_NULL;
1628  em[i++] = 0;
1629  em[i++] = (uint8_t) ASN1_TYPE_OCTET_STRING;
1630  em[i++] = (uint8_t) hash->digestSize;
1631 
1632  //Append the hash value
1633  cryptoMemcpy(em + i, digest, hash->digestSize);
1634 
1635  //Successful processing
1636  return NO_ERROR;
1637 }
1638 
1639 
1640 /**
1641  * @brief EMSA-PKCS1-v1_5 verification operation
1642  * @param[in] hash Hash function
1643  * @param[in] digest Digest value
1644  * @param[in] em Encoded message
1645  * @param[in] emLen Length of the encoded message
1646  * @return Error code
1647  **/
1648 
1649 error_t emsaPkcs1v15Verify(const HashAlgo *hash, const uint8_t *digest,
1650  const uint8_t *em, size_t emLen)
1651 {
1652  size_t i;
1653  size_t j;
1654  size_t n;
1655  uint8_t bad;
1656 
1657  //Check the length of the encoded message
1658  if(emLen < (hash->oidSize + hash->digestSize + 21))
1659  return ERROR_INVALID_LENGTH;
1660 
1661  //Point to the first byte of the encoded message
1662  i = 0;
1663 
1664  //The first octet of EM must have hexadecimal value 0x00
1665  bad = em[i++];
1666  //The second octet of EM must have hexadecimal value 0x01
1667  bad |= em[i++] ^ 0x01;
1668 
1669  //Determine the length of the padding string PS
1670  n = emLen - hash->oidSize - hash->digestSize - 13;
1671 
1672  //Each byte of PS must be set to 0xFF when the block type is 0x01
1673  for(j = 0; j < n; j++)
1674  {
1675  bad |= em[i++] ^ 0xFF;
1676  }
1677 
1678  //The padding string must be followed by a 0x00 octet
1679  bad |= em[i++];
1680 
1681  //Check the ASN.1 syntax of the DigestInfo structure
1682  bad |= em[i++] ^ (uint8_t) (ASN1_ENCODING_CONSTRUCTED | ASN1_TYPE_SEQUENCE);
1683  bad |= em[i++] ^ (uint8_t) (hash->oidSize + hash->digestSize + 8);
1684  bad |= em[i++] ^ (uint8_t) (ASN1_ENCODING_CONSTRUCTED | ASN1_TYPE_SEQUENCE);
1685  bad |= em[i++] ^ (uint8_t) (hash->oidSize + 4);
1686  bad |= em[i++] ^ (uint8_t) ASN1_TYPE_OBJECT_IDENTIFIER;
1687  bad |= em[i++] ^ (uint8_t) hash->oidSize;
1688 
1689  //Verify the hash algorithm OID
1690  for(j = 0; j < hash->oidSize; j++)
1691  {
1692  bad |= em[i++] ^ hash->oid[j];
1693  }
1694 
1695  //Check the rest of the ASN.1 structure
1696  bad |= em[i++] ^ (uint8_t) ASN1_TYPE_NULL;
1697  bad |= em[i++];
1698  bad |= em[i++] ^ (uint8_t) ASN1_TYPE_OCTET_STRING;
1699  bad |= em[i++] ^ (uint8_t) hash->digestSize;
1700 
1701  //Recover the underlying hash value, and then compare it to a newly
1702  //computed hash value
1703  for(j = 0; j < hash->digestSize; j++)
1704  {
1705  bad |= em[i++] ^ digest[j];
1706  }
1707 
1708  //Verification result
1709  return (bad != 0) ? ERROR_INCONSISTENT_VALUE : NO_ERROR;
1710 }
1711 
1712 
1713 /**
1714  * @brief EMSA-PSS encoding operation
1715  * @param[in] prngAlgo PRNG algorithm
1716  * @param[in] prngContext Pointer to the PRNG context
1717  * @param[in] hash Underlying hash function
1718  * @param[in] saltLen Length of the salt, in bytes
1719  * @param[in] digest Digest of the message to be signed
1720  * @param[out] em Encoded message
1721  * @param[in] emBits Maximal bit length of the integer OS2IP(EM)
1722  * @return Error code
1723  **/
1724 
1725 error_t emsaPssEncode(const PrngAlgo *prngAlgo, void *prngContext,
1726  const HashAlgo *hash, size_t saltLen, const uint8_t *digest,
1727  uint8_t *em, uint_t emBits)
1728 {
1729  error_t error;
1730  size_t n;
1731  size_t emLen;
1732  uint8_t *db;
1733  uint8_t *salt;
1734  uint8_t h[MAX_HASH_DIGEST_SIZE];
1735  HashContext *hashContext;
1736 
1737  //The encoded message is an octet string of length emLen = ceil(emBits / 8)
1738  emLen = (emBits + 7) / 8;
1739 
1740  //If emLen < hLen + sLen + 2, output "encoding error" and stop
1741  if(emLen < (hash->digestSize + saltLen + 2))
1742  return ERROR_INVALID_LENGTH;
1743 
1744  //The padding string PS consists of emLen - sLen - hLen - 2 zero octets
1745  n = emLen - saltLen - hash->digestSize - 2;
1746 
1747  //Point to the buffer where to format the data block DB
1748  db = em;
1749  //Point to the buffer where to generate the salt
1750  salt = db + n + 1;
1751 
1752  //Generate a random octet string salt of length sLen
1753  error = prngAlgo->read(prngContext, salt, saltLen);
1754  //Any error to report?
1755  if(error)
1756  return error;
1757 
1758  //Allocate a memory buffer to hold the hash context
1759  hashContext = cryptoAllocMem(hash->contextSize);
1760  //Failed to allocate memory?
1761  if(hashContext == NULL)
1762  return ERROR_OUT_OF_MEMORY;
1763 
1764  //Let H = Hash(00 00 00 00 00 00 00 00 || mHash || salt)
1765  hash->init(hashContext);
1766  hash->update(hashContext, padding, sizeof(padding));
1767  hash->update(hashContext, digest, hash->digestSize);
1768  hash->update(hashContext, salt, saltLen);
1769  hash->final(hashContext, h);
1770 
1771  //Let DB = PS || 0x01 || salt
1772  cryptoMemset(db, 0, n);
1773  db[n] = 0x01;
1774 
1775  //Calculate the length of the data block
1776  n += saltLen + 1;
1777 
1778  //Let maskedDB = DB xor MGF(H, emLen - hLen - 1)
1779  mgf1(hash, hashContext, h, hash->digestSize, db, n);
1780 
1781  //Set the leftmost 8emLen - emBits bits of the leftmost octet in maskedDB
1782  //to zero
1783  db[0] &= 0xFF >> (8 * emLen - emBits);
1784 
1785  //Let EM = maskedDB || H || 0xbc
1786  cryptoMemcpy(em + n, h, hash->digestSize);
1787  em[n + hash->digestSize] = 0xBC;
1788 
1789  //Release hash context
1790  cryptoFreeMem(hashContext);
1791 
1792  //Successful processing
1793  return NO_ERROR;
1794 }
1795 
1796 
1797 /**
1798  * @brief EMSA-PSS verification operation
1799  * @param[in] hash Underlying hash function
1800  * @param[in] saltLen Length of the salt, in bytes
1801  * @param[in] digest Digest of the message to be signed
1802  * @param[out] em Encoded message
1803  * @param[in] emBits Maximal bit length of the integer OS2IP(EM)
1804  * @return Error code
1805  **/
1806 
1807 error_t emsaPssVerify(const HashAlgo *hash, size_t saltLen,
1808  const uint8_t *digest, uint8_t *em, uint_t emBits)
1809 {
1810  size_t i;
1811  size_t n;
1812  size_t emLen;
1813  uint8_t bad;
1814  uint8_t mask;
1815  uint8_t *h;
1816  uint8_t *db;
1817  uint8_t *salt;
1818  HashContext *hashContext;
1819 
1820  //The encoded message is an octet string of length emLen = ceil(emBits / 8)
1821  emLen = (emBits + 7) / 8;
1822 
1823  //Check the length of the encoded message EM
1824  if(emLen < (hash->digestSize + saltLen + 2))
1825  return ERROR_INVALID_LENGTH;
1826 
1827  //Allocate a memory buffer to hold the hash context
1828  hashContext = cryptoAllocMem(hash->contextSize);
1829  //Failed to allocate memory?
1830  if(hashContext == NULL)
1831  return ERROR_OUT_OF_MEMORY;
1832 
1833  //If the rightmost octet of EM does not have hexadecimal value 0xbc, output
1834  //"inconsistent" and stop
1835  bad = em[emLen - 1] ^ 0xBC;
1836 
1837  //Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and let H be
1838  //the next hLen octets
1839  db = em;
1840  n = emLen - hash->digestSize - 1;
1841  h = em + n;
1842 
1843  //Form a mask
1844  mask = 0xFF >> (8 * emLen - emBits);
1845 
1846  //If the leftmost 8emLen - emBits bits of the leftmost octet in maskedDB are
1847  //not all equal to zero, output "inconsistent" and stop
1848  bad |= db[0] & ~mask;
1849 
1850  //Let DB = maskedDB xor MGF(H, emLen - hLen - 1)
1851  mgf1(hash, hashContext, h, hash->digestSize, db, n);
1852 
1853  //Set the leftmost 8emLen - emBits bits of the leftmost octet in DB to zero
1854  db[0] &= mask;
1855 
1856  //The padding string PS consists of emLen - sLen - hLen - 2 octets
1857  n = emLen - hash->digestSize - saltLen - 2;
1858 
1859  //If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero, output
1860  //"inconsistent" and stop
1861  for(i = 0; i < n; i++)
1862  {
1863  bad |= db[i];
1864  }
1865 
1866  //If the octet at position emLen - hLen - sLen - 1 does not have hexadecimal
1867  //value 0x01, output "inconsistent" and stop
1868  bad |= db[n] ^ 0x01;
1869 
1870  //Let salt be the last sLen octets of DB
1871  salt = db + n + 1;
1872 
1873  //Let H' = Hash(00 00 00 00 00 00 00 00 || mHash || salt)
1874  hash->init(hashContext);
1875  hash->update(hashContext, padding, sizeof(padding));
1876  hash->update(hashContext, digest, hash->digestSize);
1877  hash->update(hashContext, salt, saltLen);
1878  hash->final(hashContext, NULL);
1879 
1880  //If H = H', output "consistent". Otherwise, output "inconsistent"
1881  for(i = 0; i < hash->digestSize; i++)
1882  {
1883  bad |= h[i] ^ hashContext->digest[i];
1884  }
1885 
1886  //Release hash context
1887  cryptoFreeMem(hashContext);
1888 
1889  //Verification result
1890  return (bad != 0) ? ERROR_INCONSISTENT_VALUE : NO_ERROR;
1891 }
1892 
1893 
1894 /**
1895  * @brief MGF1 mask generation function
1896  * @param[in] hash Hash function
1897  * @param[in] hashContext Hash function context
1898  * @param[in] seed Seed from which the mask is generated
1899  * @param[in] seedLen Length of the seed in bytes
1900  * @param[in,out] data Data block to be masked
1901  * @param[in] dataLen Length of the data block in bytes
1902  **/
1903 
1904 void mgf1(const HashAlgo *hash, HashContext *hashContext, const uint8_t *seed,
1905  size_t seedLen, uint8_t *data, size_t dataLen)
1906 {
1907  size_t i;
1908  size_t n;
1909  uint32_t counter;
1910  uint8_t c[4];
1911 
1912  //The data is processed block by block
1913  for(counter = 0; dataLen > 0; counter++)
1914  {
1915  //Limit the number of bytes to process at a time
1916  n = MIN(dataLen, hash->digestSize);
1917 
1918  //Convert counter to an octet string C of length 4 octets
1919  STORE32BE(counter, c);
1920 
1921  //Calculate Hash(mgfSeed || C)
1922  hash->init(hashContext);
1923  hash->update(hashContext, seed, seedLen);
1924  hash->update(hashContext, c, sizeof(c));
1925  hash->final(hashContext, NULL);
1926 
1927  //Apply the mask
1928  for(i = 0; i < n; i++)
1929  {
1930  data[i] ^= hashContext->digest[i];
1931  }
1932 
1933  //Advance data pointer
1934  data += n;
1935  dataLen -= n;
1936  }
1937 }
1938 
1939 
1940 /**
1941  * @brief RSA key pair generation
1942  * @param[in] prngAlgo PRNG algorithm
1943  * @param[in] prngContext Pointer to the PRNG context
1944  * @param[in] k Required bit length of the modulus n
1945  * @param[in] e Public exponent (3, 5, 17, 257 or 65537)
1946  * @param[out] privateKey RSA private key
1947  * @param[out] publicKey RSA public key
1948  * @return Error code
1949  **/
1950 
1951 error_t rsaGenerateKeyPair(const PrngAlgo *prngAlgo, void *prngContext,
1952  size_t k, uint_t e, RsaPrivateKey *privateKey, RsaPublicKey *publicKey)
1953 {
1954  error_t error;
1955  Mpi t1;
1956  Mpi t2;
1957  Mpi phy;
1958 
1959  //Check parameters
1960  if(prngAlgo == NULL || prngContext == NULL || privateKey == NULL)
1961  return ERROR_INVALID_PARAMETER;
1962 
1963  //Check the length of the modulus
1964  if(k < 8)
1965  return ERROR_INVALID_PARAMETER;
1966 
1967  //Check the value of the public exponent
1968  if(e != 3 && e != 5 && e != 17 && e != 257 && e != 65537)
1969  return ERROR_INVALID_PARAMETER;
1970 
1971  //Initialize multiple precision integers
1972  mpiInit(&t1);
1973  mpiInit(&t2);
1974  mpiInit(&phy);
1975 
1976  //Save public exponent
1977  MPI_CHECK(mpiSetValue(&privateKey->e, e));
1978 
1979  //Generate a large random prime p
1980  do
1981  {
1982  do
1983  {
1984  //Generate a random number of bit length k/2
1985  MPI_CHECK(mpiRand(&privateKey->p, k / 2, prngAlgo, prngContext));
1986  //Set the low bit (this ensures the number is odd)
1987  MPI_CHECK(mpiSetBitValue(&privateKey->p, 0, 1));
1988  //Set the two highest bits (this ensures that the high bit of n is also set)
1989  MPI_CHECK(mpiSetBitValue(&privateKey->p, k / 2 - 1, 1));
1990  MPI_CHECK(mpiSetBitValue(&privateKey->p, k / 2 - 2, 1));
1991 
1992  //Test whether p is a probable prime
1993  error = mpiCheckProbablePrime(&privateKey->p);
1994 
1995  //Repeat until an acceptable value is found
1996  } while(error == ERROR_INVALID_VALUE);
1997 
1998  //Check status code
1999  MPI_CHECK(error);
2000 
2001  //Compute p mod e
2002  MPI_CHECK(mpiMod(&t1, &privateKey->p, &privateKey->e));
2003 
2004  //Repeat as long as p mod e = 1
2005  } while(mpiCompInt(&t1, 1) == 0);
2006 
2007  //Generate a large random prime q
2008  do
2009  {
2010  do
2011  {
2012  //Generate random number of bit length k - k/2
2013  MPI_CHECK(mpiRand(&privateKey->q, k - (k / 2), prngAlgo, prngContext));
2014  //Set the low bit (this ensures the number is odd)
2015  MPI_CHECK(mpiSetBitValue(&privateKey->q, 0, 1));
2016  //Set the two highest bits (this ensures that the high bit of n is also set)
2017  MPI_CHECK(mpiSetBitValue(&privateKey->q, k - (k / 2) - 1, 1));
2018  MPI_CHECK(mpiSetBitValue(&privateKey->q, k - (k / 2) - 2, 1));
2019 
2020  //Test whether q is a probable prime
2021  error = mpiCheckProbablePrime(&privateKey->q);
2022 
2023  //Repeat until an acceptable value is found
2024  } while(error == ERROR_INVALID_VALUE);
2025 
2026  //Check status code
2027  MPI_CHECK(error);
2028 
2029  //Compute q mod e
2030  MPI_CHECK(mpiMod(&t2, &privateKey->q, &privateKey->e));
2031 
2032  //Repeat as long as p mod e = 1
2033  } while(mpiCompInt(&t2, 1) == 0);
2034 
2035  //Make sure p an q are distinct
2036  if(mpiComp(&privateKey->p, &privateKey->q) == 0)
2037  {
2039  }
2040 
2041  //If p < q, then swap p and q (this only matters if the CRT form of
2042  //the private key is used)
2043  if(mpiComp(&privateKey->p, &privateKey->q) < 0)
2044  {
2045  //Swap primes
2046  mpiCopy(&t1, &privateKey->p);
2047  mpiCopy(&privateKey->p, &privateKey->q);
2048  mpiCopy(&privateKey->q, &t1);
2049  }
2050 
2051  //Compute the modulus n = pq
2052  MPI_CHECK(mpiMul(&privateKey->n, &privateKey->p, &privateKey->q));
2053 
2054  //Compute phy = (p-1)(q-1)
2055  MPI_CHECK(mpiSubInt(&t1, &privateKey->p, 1));
2056  MPI_CHECK(mpiSubInt(&t2, &privateKey->q, 1));
2057  MPI_CHECK(mpiMul(&phy, &t1, &t2));
2058 
2059  //Compute d = e^-1 mod phy
2060  MPI_CHECK(mpiInvMod(&privateKey->d, &privateKey->e, &phy));
2061  //Compute dP = d mod (p-1)
2062  MPI_CHECK(mpiMod(&privateKey->dp, &privateKey->d, &t1));
2063  //Compute dQ = d mod (q-1)
2064  MPI_CHECK(mpiMod(&privateKey->dq, &privateKey->d, &t2));
2065  //Compute qInv = q^-1 mod p
2066  MPI_CHECK(mpiInvMod(&privateKey->qinv, &privateKey->q, &privateKey->p));
2067 
2068  //Debug message
2069  TRACE_DEBUG("RSA private key:\r\n");
2070  TRACE_DEBUG(" Modulus:\r\n");
2071  TRACE_DEBUG_MPI(" ", &privateKey->n);
2072  TRACE_DEBUG(" Public exponent:\r\n");
2073  TRACE_DEBUG_MPI(" ", &privateKey->e);
2074  TRACE_DEBUG(" Private exponent:\r\n");
2075  TRACE_DEBUG_MPI(" ", &privateKey->d);
2076  TRACE_DEBUG(" Prime 1:\r\n");
2077  TRACE_DEBUG_MPI(" ", &privateKey->p);
2078  TRACE_DEBUG(" Prime 2:\r\n");
2079  TRACE_DEBUG_MPI(" ", &privateKey->q);
2080  TRACE_DEBUG(" Prime exponent 1:\r\n");
2081  TRACE_DEBUG_MPI(" ", &privateKey->dp);
2082  TRACE_DEBUG(" Prime exponent 2:\r\n");
2083  TRACE_DEBUG_MPI(" ", &privateKey->dq);
2084  TRACE_DEBUG(" Coefficient:\r\n");
2085  TRACE_DEBUG_MPI(" ", &privateKey->qinv);
2086 
2087  //An public key can be optionally generated
2088  if(publicKey != NULL)
2089  {
2090  //The public key is (n, e)
2091  MPI_CHECK(mpiCopy(&publicKey->n, &privateKey->n));
2092  MPI_CHECK(mpiCopy(&publicKey->e, &privateKey->e));
2093 
2094  //Debug message
2095  TRACE_DEBUG("RSA public key:\r\n");
2096  TRACE_DEBUG(" Modulus:\r\n");
2097  TRACE_DEBUG_MPI(" ", &publicKey->n);
2098  TRACE_DEBUG(" Public exponent:\r\n");
2099  TRACE_DEBUG_MPI(" ", &publicKey->e);
2100  }
2101 
2102 end:
2103  //Release multiple precision integers
2104  mpiFree(&t1);
2105  mpiFree(&t2);
2106  mpiFree(&phy);
2107 
2108  //Any error to report?
2109  if(error)
2110  {
2111  //Release RSA private key
2112  rsaFreePrivateKey(privateKey);
2113 
2114  //Release RSA public key
2115  if(publicKey != NULL)
2116  rsaFreePublicKey(publicKey);
2117  }
2118 
2119  //Return status code
2120  return error;
2121 }
2122 
2123 #endif
error_t mpiSubInt(Mpi *r, const Mpi *a, int_t b)
Subtract an integer from a multiple precision integer.
Definition: mpi.c:818
#define CRYPTO_TEST_Z_32(a)
Definition: crypto.h:1017
const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_512_OID[9]
Definition: rsa.c:85
void rsaFreePublicKey(RsaPublicKey *key)
Release an RSA public key.
Definition: rsa.c:118
#define CRYPTO_TEST_EQ_32(a, b)
Definition: crypto.h:1025
Mpi p
First factor.
Definition: rsa.h:64
error_t rsaesOaepDecrypt(const RsaPrivateKey *key, const HashAlgo *hash, const char_t *label, const uint8_t *ciphertext, size_t ciphertextLen, uint8_t *message, size_t messageSize, size_t *messageLen)
RSAES-OAEP decryption operation.
Definition: rsa.c:529
uint8_t a
Definition: ndp.h:410
Arbitrary precision integer.
Definition: mpi.h:69
Common interface for pseudo-random number generators.
Definition: crypto.h:1168
const uint8_t MD5_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:62
error_t rsaesOaepEncrypt(const PrngAlgo *prngAlgo, void *prngContext, const RsaPublicKey *key, const HashAlgo *hash, const char_t *label, const uint8_t *message, size_t messageLen, uint8_t *ciphertext, size_t *ciphertextLen)
RSAES-OAEP encryption operation.
Definition: rsa.c:423
const uint8_t SHA512_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:72
error_t rsasp1(const RsaPrivateKey *key, const Mpi *m, Mpi *s)
RSA signature primitive.
Definition: rsa.c:1248
PrngAlgoRead read
Definition: crypto.h:1176
#define CRYPTO_SELECT_32(a, b, c)
Definition: crypto.h:1049
const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_384_OID[9]
Definition: rsa.c:83
OID (Object Identifier)
uint8_t b[6]
Definition: dtls_misc.h:139
uint8_t p
Definition: ndp.h:298
#define TRUE
Definition: os_port.h:50
const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_224_OID[9]
Definition: rsa.c:79
error_t mpiMulMod(Mpi *r, const Mpi *a, const Mpi *b, const Mpi *p)
Modular multiplication.
Definition: mpi.c:1436
uint8_t signature
Definition: tls.h:1370
Mpi n
Modulus.
Definition: rsa.h:61
#define mpiWriteRaw(a, data, length)
Definition: crypto_legacy.h:36
error_t mpiSetValue(Mpi *r, int_t a)
Set the value of a multiple precision integer.
Definition: mpi.c:437
error_t mpiSetBitValue(Mpi *r, uint_t index, uint_t value)
Set the bit value at the specified index.
Definition: mpi.c:236
Mpi e
Public exponent.
Definition: rsa.h:51
const uint8_t RSASSA_PSS_OID[9]
Definition: rsa.c:88
error_t mpiRand(Mpi *r, uint_t length, const PrngAlgo *prngAlgo, void *prngContext)
Generate a random value.
Definition: mpi.c:468
void mpiInit(Mpi *r)
Initialize a multiple precision integer.
Definition: mpi.c:48
error_t rsaesPkcs1v15Decrypt(const RsaPrivateKey *key, const uint8_t *ciphertext, size_t ciphertextLen, uint8_t *message, size_t messageSize, size_t *messageLen)
RSAES-PKCS1-v1_5 decryption operation.
Definition: rsa.c:274
#define CRYPTO_TEST_Z_8(a)
Definition: crypto.h:945
void rsaInitPrivateKey(RsaPrivateKey *key)
Initialize an RSA private key.
Definition: rsa.c:131
const uint8_t MGF1_OID[9]
Definition: rsa.c:91
Mpi d
Private exponent.
Definition: rsa.h:63
const uint8_t PKCS1_OID[8]
Definition: rsa.c:55
#define mpiReadRaw(r, data, length)
Definition: crypto_legacy.h:35
#define ASN1_ENCODING_CONSTRUCTED
Definition: asn1.h:44
Mpi n
Modulus.
Definition: rsa.h:50
uint8_t t
Definition: llmnr_common.h:81
const uint8_t RSASSA_PKCS1_V1_5_WITH_SHA3_256_OID[9]
Definition: rsa.c:81
error_t mpiMod(Mpi *r, const Mpi *a, const Mpi *p)
Modulo operation.
Definition: mpi.c:1325
uint32_t emePkcs1v15Decode(uint8_t *em, size_t k, size_t *messageLen)
EME-PKCS1-v1_5 decoding operation.
Definition: rsa.c:1357
const uint8_t SHA384_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:70
const uint8_t SHA512_224_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:74
uint8_t h
Definition: ndp.h:300
Invalid parameter.
Definition: error.h:47
#define cryptoStrlen(s)
Definition: crypto.h:660
#define CRYPTO_TEST_NZ_8(a)
Definition: crypto.h:949
error_t mpiSub(Mpi *r, const Mpi *a, const Mpi *b)
Multiple precision subtraction.
Definition: mpi.c:769
error_t
Error codes.
Definition: error.h:42
error_t emeOaepEncode(const PrngAlgo *prngAlgo, void *prngContext, const HashAlgo *hash, const char_t *label, const uint8_t *message, size_t messageLen, uint8_t *em, size_t k)
EME-OAEP encoding operation.
Definition: rsa.c:1411
void rsaFreePrivateKey(RsaPrivateKey *key)
Release an RSA private key.
Definition: rsa.c:150
error_t rsaesPkcs1v15Encrypt(const PrngAlgo *prngAlgo, void *prngContext, const RsaPublicKey *key, const uint8_t *message, size_t messageLen, uint8_t *ciphertext, size_t *ciphertextLen)
RSAES-PKCS1-v1_5 encryption operation.
Definition: rsa.c:176
#define MPI_CHECK(f)
Definition: mpi.h:42
error_t rsavp1(const RsaPublicKey *key, const Mpi *s, Mpi *m)
RSA verification primitive.
Definition: rsa.c:1269
error_t mpiAdd(Mpi *r, const Mpi *a, const Mpi *b)
Multiple precision addition.
Definition: mpi.c:696
error_t emsaPssVerify(const HashAlgo *hash, size_t saltLen, const uint8_t *digest, uint8_t *em, uint_t emBits)
EMSA-PSS verification operation.
Definition: rsa.c:1807
Generic error code.
Definition: error.h:45
Mpi q
Second factor.
Definition: rsa.h:65
error_t rsassaPssSign(const PrngAlgo *prngAlgo, void *prngContext, const RsaPrivateKey *key, const HashAlgo *hash, size_t saltLen, const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
RSASSA-PSS signature generation operation.
Definition: rsa.c:920
RSA public key.
Definition: rsa.h:48
error_t mpiInvMod(Mpi *r, const Mpi *a, const Mpi *p)
Modular inverse.
#define CRYPTO_TEST_LT_32(a, b)
Definition: crypto.h:1033
MPI (Multiple Precision Integer Arithmetic)
General definitions for cryptographic algorithms.
RSA public-key cryptography standard.
#define CRYPTO_SELECT_8(a, b, c)
Definition: crypto.h:977
uint32_t emeOaepDecode(const HashAlgo *hash, const char_t *label, uint8_t *em, size_t k, size_t *messageLen)
EME-OAEP decoding operation.
Definition: rsa.c:1491
uint8_t mask
Definition: web_socket.h:317
error_t mpiCheckProbablePrime(const Mpi *a)
Test whether a number is probable prime.
uint32_t t2
Mpi e
Public exponent.
Definition: rsa.h:62
#define MIN(a, b)
Definition: os_port.h:62
const uint8_t SHA256_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:68
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:195
Mpi qinv
CRT coefficient.
Definition: rsa.h:68
Mpi dq
second factor's CRT exponent
Definition: rsa.h:67
error_t mpiCopy(Mpi *r, const Mpi *a)
Copy a multiple precision integer.
Definition: mpi.c:400
const uint8_t RSA_ENCRYPTION_OID[9]
Definition: rsa.c:57
uint8_t hash
Definition: tls.h:1369
#define cryptoMemset(p, value, length)
Definition: crypto.h:636
#define TRACE_DEBUG(...)
Definition: debug.h:106
char char_t
Definition: compiler_port.h:43
error_t rsassaPkcs1v15Verify(const RsaPublicKey *key, const HashAlgo *hash, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
RSASSA-PKCS1-v1_5 signature verification operation.
Definition: rsa.c:811
error_t rsaGenerateKeyPair(const PrngAlgo *prngAlgo, void *prngContext, size_t k, uint_t e, RsaPrivateKey *privateKey, RsaPublicKey *publicKey)
RSA key pair generation.
Definition: rsa.c:1951
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:107
uint32_t t1
uint8_t digest[1]
Definition: crypto.h:1120
uint8_t m
Definition: ndp.h:302
uint8_t n
RSA private key.
Definition: rsa.h:59
error_t rsassaPssVerify(const RsaPublicKey *key, const HashAlgo *hash, size_t saltLen, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
RSASSA-PSS signature verification operation.
Definition: rsa.c:1040
uint_t size
Definition: mpi.h:72
#define cryptoMemcpy(dest, src, length)
Definition: crypto.h:642
error_t mpiMul(Mpi *r, const Mpi *a, const Mpi *b)
Multiple precision multiplication.
#define cryptoFreeMem(p)
Definition: crypto.h:630
const uint8_t MD2_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:60
error_t emePkcs1v15Encode(const PrngAlgo *prngAlgo, void *prngContext, const uint8_t *message, size_t messageLen, uint8_t *em, size_t k)
EME-PKCS1-v1_5 encoding operation.
Definition: rsa.c:1289
uint8_t s
uint8_t message[]
Definition: chap.h:152
error_t mpiExpMod(Mpi *r, const Mpi *a, const Mpi *e, const Mpi *p)
Modular exponentiation.
#define cryptoAllocMem(size)
Definition: crypto.h:625
const uint8_t SHA224_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:66
error_t rsaep(const RsaPublicKey *key, const Mpi *m, Mpi *c)
RSA encryption primitive.
Definition: rsa.c:1154
Common interface for hash algorithms.
Definition: crypto.h:1128
error_t rsassaPkcs1v15Sign(const RsaPrivateKey *key, const HashAlgo *hash, const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
RSASSA-PKCS1-v1_5 signature generation operation.
Definition: rsa.c:678
#define MAX_HASH_DIGEST_SIZE
Definition: crypto.h:811
int_t mpiComp(const Mpi *a, const Mpi *b)
Compare two multiple precision integers.
Definition: mpi.c:295
Mpi dp
First factor's CRT exponent.
Definition: rsa.h:66
unsigned int uint_t
Definition: compiler_port.h:45
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:109
uint8_t data[]
Definition: dtls_misc.h:176
__weak error_t rsadp(const RsaPrivateKey *key, const Mpi *c, Mpi *m)
RSA decryption primitive.
Definition: rsa.c:1181
void mgf1(const HashAlgo *hash, HashContext *hashContext, const uint8_t *seed, size_t seedLen, uint8_t *data, size_t dataLen)
MGF1 mask generation function.
Definition: rsa.c:1904
int_t mpiCompInt(const Mpi *a, int_t b)
Compare a multiple precision integer with an integer.
Definition: mpi.c:339
error_t emsaPssEncode(const PrngAlgo *prngAlgo, void *prngContext, const HashAlgo *hash, size_t saltLen, const uint8_t *digest, uint8_t *em, uint_t emBits)
EMSA-PSS encoding operation.
Definition: rsa.c:1725
Generic hash algorithm context.
Definition: crypto.h:1118
const uint8_t SHA1_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:64
#define STORE32BE(a, p)
Definition: cpu_endian.h:270
#define CRYPTO_TEST_NEQ_8(a, b)
Definition: crypto.h:957
Success.
Definition: error.h:44
uint8_t c
Definition: ndp.h:513
HMAC (Keyed-Hashing for Message Authentication)
Debugging facilities.
void rsaInitPublicKey(RsaPublicKey *key)
Initialize an RSA public key.
Definition: rsa.c:105
error_t emsaPkcs1v15Encode(const HashAlgo *hash, const uint8_t *digest, uint8_t *em, size_t emLen)
EMSA-PKCS1-v1_5 encoding operation.
Definition: rsa.c:1585
const uint8_t SHA512_256_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:76
error_t emsaPkcs1v15Verify(const HashAlgo *hash, const uint8_t *digest, const uint8_t *em, size_t emLen)
EMSA-PKCS1-v1_5 verification operation.
Definition: rsa.c:1649
ASN.1 (Abstract Syntax Notation One)
uint_t mpiGetByteLength(const Mpi *a)
Get the actual length in bytes.
Definition: mpi.c:156
void mpiFree(Mpi *r)
Release a multiple precision integer.
Definition: mpi.c:62