cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
ctx_rsa.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib RSA Encryption Routines *
4 * Copyright Peter Gutmann 1993-2005 *
5 * *
6 ****************************************************************************/
7 
8 /* I suppose if we all used pure RSA, the Illuminati would blackmail God into
9  putting a trapdoor into the laws of mathematics.
10  -- Lyle Seaman */
11 
12 #define PKC_CONTEXT /* Indicate that we're working with PKC contexts */
13 #if defined( INC_ALL )
14  #include "crypt.h"
15  #include "context.h"
16 #else
17  #include "crypt.h"
18  #include "context/context.h"
19 #endif /* Compiler-specific includes */
20 
21 /****************************************************************************
22 * *
23 * Algorithm Self-test *
24 * *
25 ****************************************************************************/
26 
27 /* Perform a pairwise consistency test on a public/private key pair */
28 
30 static BOOLEAN pairwiseConsistencyTest( CONTEXT_INFO *contextInfoPtr )
31  {
34  int status;
35 
36  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
37 
38  /* Encrypt with the public key */
39  memset( buffer, 0, CRYPT_MAX_PKCSIZE );
40  memcpy( buffer + 1, "abcde", 5 );
41  status = capabilityInfoPtr->encryptFunction( contextInfoPtr, buffer,
42  bitsToBytes( contextInfoPtr->ctxPKC->keySizeBits ) );
43  if( cryptStatusError( status ) )
44  return( FALSE );
45 
46  /* Decrypt with the private key */
47  status = capabilityInfoPtr->decryptFunction( contextInfoPtr, buffer,
48  bitsToBytes( contextInfoPtr->ctxPKC->keySizeBits ) );
49  if( cryptStatusError( status ) )
50  return( FALSE );
51 
52  /* Make sure that we're recovered the original, including correct
53  handling of leading zeroes */
54  return( !memcmp( buffer, "\x00" "abcde" "\x00\x00\x00\x00", 10 ) );
55  }
56 
57 #ifndef CONFIG_NO_SELFTEST
58 
59 /* Test the RSA implementation using a sample key. Because a lot of the
60  high-level encryption routines don't exist yet, we cheat a bit and set
61  up a dummy encryption context with just enough information for the
62  following code to work */
63 
64 typedef struct {
65  const int nLen; const BYTE n[ 128 ];
66  const int eLen; const BYTE e[ 3 ];
67  const int dLen; const BYTE d[ 128 ];
68  const int pLen; const BYTE p[ 64 ];
69  const int qLen; const BYTE q[ 64 ];
70  const int uLen; const BYTE u[ 64 ];
71  const int e1Len; const BYTE e1[ 64 ];
72  const int e2Len; const BYTE e2[ 64 ];
73  } RSA_KEY;
74 
75 static const RSA_KEY FAR_BSS rsaTestKey = {
76  /* n */
77  128,
78  { 0x9C, 0x4D, 0x98, 0x18, 0x67, 0xF9, 0x45, 0xBC,
79  0xB6, 0x75, 0x53, 0x5D, 0x2C, 0xFA, 0x55, 0xE4,
80  0x51, 0x54, 0x9F, 0x0C, 0x16, 0xB1, 0xAF, 0x89,
81  0xF6, 0xF3, 0xE7, 0x78, 0xB1, 0x2B, 0x07, 0xFB,
82  0xDC, 0xDE, 0x64, 0x23, 0x34, 0x87, 0xDA, 0x0B,
83  0xE5, 0xB3, 0x17, 0x16, 0xA4, 0xE3, 0x7F, 0x23,
84  0xDF, 0x96, 0x16, 0x28, 0xA6, 0xD2, 0xF0, 0x0A,
85  0x59, 0xEE, 0x06, 0xB3, 0x76, 0x6C, 0x64, 0x19,
86  0xD9, 0x76, 0x41, 0x25, 0x66, 0xD1, 0x93, 0x51,
87  0x52, 0x06, 0x6B, 0x71, 0x50, 0x0E, 0xAB, 0x30,
88  0xA5, 0xC8, 0x41, 0xFC, 0x30, 0xBC, 0x32, 0xD7,
89  0x4B, 0x22, 0xF2, 0x45, 0x4C, 0x94, 0x68, 0xF1,
90  0x92, 0x8A, 0x4C, 0xF9, 0xD4, 0x5E, 0x87, 0x92,
91  0xA8, 0x54, 0x93, 0x92, 0x94, 0x48, 0xA4, 0xA3,
92  0xEE, 0x19, 0x7F, 0x6E, 0xD3, 0x14, 0xB1, 0x48,
93  0xCE, 0x93, 0xD1, 0xEA, 0x4C, 0xE1, 0x9D, 0xEF },
94 
95  /* e */
96  3,
97  { 0x01, 0x00, 0x01 },
98 
99  /* d */
100  128,
101  { 0x37, 0xE2, 0x66, 0x67, 0x13, 0x85, 0xC4, 0xB1,
102  0x5C, 0x6B, 0x46, 0x8B, 0x21, 0xF1, 0xBF, 0x94,
103  0x0A, 0xA0, 0x3E, 0xDD, 0x8B, 0x9F, 0xAC, 0x2B,
104  0x9F, 0xE8, 0x44, 0xF2, 0x9A, 0x25, 0xD0, 0x8C,
105  0xF4, 0xC3, 0x6E, 0xFA, 0x47, 0x65, 0xEB, 0x48,
106  0x25, 0xB0, 0x8A, 0xA8, 0xC5, 0xFB, 0xB1, 0x11,
107  0x9A, 0x77, 0x87, 0x24, 0xB1, 0xC0, 0xE9, 0xA2,
108  0x49, 0xD5, 0x19, 0x00, 0x41, 0x6F, 0x2F, 0xBA,
109  0x9F, 0x28, 0x47, 0xF9, 0xB8, 0xBA, 0xFF, 0xF4,
110  0x8B, 0x20, 0xC9, 0xC9, 0x39, 0xAB, 0x52, 0x0E,
111  0x8A, 0x5A, 0xAF, 0xB3, 0xA3, 0x93, 0x4D, 0xBB,
112  0xFE, 0x62, 0x9B, 0x02, 0xCC, 0xA7, 0xB4, 0xAE,
113  0x86, 0x65, 0x88, 0x19, 0xD7, 0x44, 0xA7, 0xE4,
114  0x18, 0xB6, 0xCE, 0x01, 0xCD, 0xDF, 0x36, 0x81,
115  0xD5, 0xE1, 0x62, 0xF8, 0xD0, 0x27, 0xF1, 0x86,
116  0xA8, 0x58, 0xA7, 0xEB, 0x39, 0x79, 0x56, 0x41 },
117 
118  /* p */
119  64,
120  { 0xCF, 0xDA, 0xF9, 0x99, 0x6F, 0x05, 0x95, 0x84,
121  0x09, 0x90, 0xB3, 0xAB, 0x39, 0xB7, 0xDD, 0x1D,
122  0x7B, 0xFC, 0xFD, 0x10, 0x35, 0xA0, 0x18, 0x1D,
123  0x9A, 0x11, 0x30, 0x90, 0xD4, 0x3B, 0xF0, 0x5A,
124  0xC1, 0xA6, 0xF4, 0x53, 0xD0, 0x94, 0xA0, 0xED,
125  0xE0, 0xE4, 0xE0, 0x8E, 0x44, 0x18, 0x42, 0x42,
126  0xE1, 0x2C, 0x0D, 0xF7, 0x30, 0xE2, 0xB8, 0x09,
127  0x73, 0x50, 0x28, 0xF6, 0x55, 0x85, 0x57, 0x03 },
128 
129  /* q */
130  64,
131  { 0xC0, 0x81, 0xC4, 0x82, 0x6E, 0xF6, 0x1C, 0x92,
132  0x83, 0xEC, 0x17, 0xFB, 0x30, 0x98, 0xED, 0x6E,
133  0x89, 0x92, 0xB2, 0xA1, 0x21, 0x0D, 0xC1, 0x95,
134  0x49, 0x99, 0xD3, 0x79, 0xD3, 0xBD, 0x94, 0x93,
135  0xB9, 0x28, 0x68, 0xFF, 0xDE, 0xEB, 0xE8, 0xD2,
136  0x0B, 0xED, 0x7C, 0x08, 0xD0, 0xD5, 0x59, 0xE3,
137  0xC1, 0x76, 0xEA, 0xC1, 0xCD, 0xB6, 0x8B, 0x39,
138  0x4E, 0x29, 0x59, 0x5F, 0xFA, 0xCE, 0x83, 0xA5 },
139 
140  /* u */
141  64,
142  { 0x4B, 0x87, 0x97, 0x1F, 0x27, 0xED, 0xAA, 0xAF,
143  0x42, 0xF4, 0x57, 0x82, 0x3F, 0xEC, 0x80, 0xED,
144  0x1E, 0x91, 0xF8, 0xB4, 0x33, 0xDA, 0xEF, 0xC3,
145  0x03, 0x53, 0x0F, 0xCE, 0xB9, 0x5F, 0xE4, 0x29,
146  0xCC, 0xEE, 0x6A, 0x5E, 0x11, 0x0E, 0xFA, 0x66,
147  0x85, 0xDC, 0xFC, 0x48, 0x31, 0x0C, 0x00, 0x97,
148  0xC6, 0x0A, 0xF2, 0x34, 0x60, 0x6B, 0xF7, 0x68,
149  0x09, 0x4E, 0xCF, 0xB1, 0x9E, 0x33, 0x9A, 0x41 },
150 
151  /* exponent1 */
152  64,
153  { 0x6B, 0x2A, 0x0D, 0xF8, 0x22, 0x7A, 0x71, 0x8C,
154  0xE2, 0xD5, 0x9D, 0x1C, 0x91, 0xA4, 0x8F, 0x37,
155  0x0D, 0x5E, 0xF1, 0x26, 0x73, 0x4F, 0x78, 0x3F,
156  0x82, 0xD8, 0x8B, 0xFE, 0x8F, 0xBD, 0xDB, 0x7D,
157  0x1F, 0x4C, 0xB1, 0xB9, 0xA8, 0xD7, 0x88, 0x65,
158  0x3C, 0xC7, 0x24, 0x53, 0x95, 0x1E, 0x20, 0xC3,
159  0x94, 0x8E, 0x7F, 0x20, 0xCC, 0x2E, 0x88, 0x0E,
160  0x2F, 0x4A, 0xCB, 0xE3, 0xBD, 0x52, 0x02, 0xFB },
161 
162  /* exponent2 */
163  64,
164  { 0x10, 0x27, 0xD3, 0xD2, 0x0E, 0x75, 0xE1, 0x17,
165  0xFA, 0xB2, 0x49, 0xA0, 0xEF, 0x07, 0x26, 0x85,
166  0xEC, 0x4D, 0xBF, 0x67, 0xFE, 0x5A, 0x25, 0x30,
167  0xDE, 0x28, 0x66, 0xB3, 0x06, 0xAE, 0x16, 0x55,
168  0xFF, 0x68, 0x00, 0xC7, 0xD8, 0x71, 0x7B, 0xEC,
169  0x84, 0xCB, 0xBD, 0x69, 0x0F, 0xFD, 0x97, 0xB9,
170  0xA1, 0x76, 0xD5, 0x64, 0xC6, 0x5A, 0xD7, 0x7C,
171  0x4B, 0xAE, 0xF4, 0xAD, 0x35, 0x63, 0x37, 0x71 }
172  };
173 
174 CHECK_RETVAL \
175 static int selfTest( void )
176  {
177  CONTEXT_INFO contextInfo;
178  PKC_INFO contextData, *pkcInfo = &contextData;
179  BYTE buffer[ 128 + 8 ];
181  int status;
182 
183  /* Initialise the key components */
184  status = staticInitContext( &contextInfo, CONTEXT_PKC,
185  getRSACapability(), &contextData,
186  sizeof( PKC_INFO ), NULL );
187  if( cryptStatusError( status ) )
188  return( CRYPT_ERROR_FAILED );
189  status = importBignum( &pkcInfo->rsaParam_n, rsaTestKey.n,
190  rsaTestKey.nLen, RSAPARAM_MIN_N,
192  if( cryptStatusOK( status ) )
193  status = importBignum( &pkcInfo->rsaParam_e, rsaTestKey.e,
194  rsaTestKey.eLen, RSAPARAM_MIN_E,
195  RSAPARAM_MAX_E, &pkcInfo->rsaParam_n,
197  if( cryptStatusOK( status ) )
198  status = importBignum( &pkcInfo->rsaParam_d, rsaTestKey.d,
199  rsaTestKey.dLen, RSAPARAM_MIN_D,
200  RSAPARAM_MAX_D, &pkcInfo->rsaParam_n,
202  if( cryptStatusOK( status ) )
203  status = importBignum( &pkcInfo->rsaParam_p, rsaTestKey.p,
204  rsaTestKey.pLen, RSAPARAM_MIN_P,
205  RSAPARAM_MAX_P, &pkcInfo->rsaParam_n,
207  if( cryptStatusOK( status ) )
208  status = importBignum( &pkcInfo->rsaParam_q, rsaTestKey.q,
209  rsaTestKey.qLen, RSAPARAM_MIN_Q,
210  RSAPARAM_MAX_Q, &pkcInfo->rsaParam_n,
212  if( cryptStatusOK( status ) )
213  status = importBignum( &pkcInfo->rsaParam_u, rsaTestKey.u,
214  rsaTestKey.uLen, RSAPARAM_MIN_U,
215  RSAPARAM_MAX_U, &pkcInfo->rsaParam_n,
217  if( cryptStatusOK( status ) )
218  status = importBignum( &pkcInfo->rsaParam_exponent1, rsaTestKey.e1,
219  rsaTestKey.e1Len, RSAPARAM_MIN_EXP1,
220  RSAPARAM_MAX_EXP1, &pkcInfo->rsaParam_n,
222  if( cryptStatusOK( status ) )
223  status = importBignum( &pkcInfo->rsaParam_exponent2, rsaTestKey.e2,
224  rsaTestKey.e2Len, RSAPARAM_MIN_EXP2,
225  RSAPARAM_MAX_EXP2, &pkcInfo->rsaParam_n,
227  if( cryptStatusError( status ) )
228  retIntError();
229 
230  /* Perform the test en/decryption of a block of data */
231  capabilityInfoPtr = contextInfo.capabilityInfo;
232  status = capabilityInfoPtr->initKeyFunction( &contextInfo, NULL, 0 );
233  if( cryptStatusOK( status ) && \
234  !pairwiseConsistencyTest( &contextInfo ) )
235  status = CRYPT_ERROR_FAILED;
236  else
237  {
238  /* Try it again with blinding enabled. Note that this uses the
239  randomness subsystem, which can significantly slow down the self-
240  test if it's being performed before the polling has completed */
241  memset( buffer, 0, rsaTestKey.nLen );
242  memcpy( buffer, "abcde", 5 );
244  status = capabilityInfoPtr->initKeyFunction( &contextInfo, NULL, 0 );
245  if( cryptStatusOK( status ) )
246  status = capabilityInfoPtr->encryptFunction( &contextInfo,
247  buffer, rsaTestKey.nLen );
248  if( cryptStatusOK( status ) )
249  status = capabilityInfoPtr->decryptFunction( &contextInfo,
250  buffer, rsaTestKey.nLen );
251  if( cryptStatusError( status ) || memcmp( buffer, "abcde", 5 ) )
252  status = CRYPT_ERROR_FAILED;
253  else
254  {
255  /* And one last time to ensure that the blinding value update
256  works */
257  memset( buffer, 0, rsaTestKey.nLen );
258  memcpy( buffer, "abcde", 5 );
259  status = capabilityInfoPtr->initKeyFunction( &contextInfo, NULL, 0 );
260  if( cryptStatusOK( status ) )
261  status = capabilityInfoPtr->encryptFunction( &contextInfo,
262  buffer, rsaTestKey.nLen );
263  if( cryptStatusOK( status ) )
264  status = capabilityInfoPtr->decryptFunction( &contextInfo,
265  buffer, rsaTestKey.nLen );
266  if( cryptStatusError( status ) || memcmp( buffer, "abcde", 5 ) )
267  status = CRYPT_ERROR_FAILED;
268  }
269  }
270 
271  /* Clean up */
272  staticDestroyContext( &contextInfo );
273 
274  return( status );
275  }
276 #else
277  #define selfTest NULL
278 #endif /* !CONFIG_NO_SELFTEST */
279 
280 /****************************************************************************
281 * *
282 * Encrypt/Decrypt a Data Block *
283 * *
284 ****************************************************************************/
285 
286 /* Encrypt/signature check a single block of data. We have to append the
287  distinguisher 'Fn' to the name since some systems already have 'encrypt'
288  and 'decrypt' in their standard headers */
289 
291 static int encryptFn( INOUT CONTEXT_INFO *contextInfoPtr,
292  INOUT_BUFFER_FIXED( noBytes ) BYTE *buffer,
293  IN_LENGTH_SHORT int noBytes )
294  {
295  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
296  BIGNUM *n = &pkcInfo->rsaParam_n, *e = &pkcInfo->rsaParam_e;
297  BIGNUM *data = &pkcInfo->tmp1;
298  const int length = bitsToBytes( pkcInfo->keySizeBits );
299  int offset, dummy, bnStatus = BN_STATUS, status;
300 
301  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
302  assert( isWritePtr( buffer, length ) );
303 
304  REQUIRES( noBytes == length );
305  REQUIRES( noBytes > 0 && noBytes < MAX_INTLENGTH_SHORT );
306 
307  /* Move the data from the buffer into a bignum */
308  status = importBignum( data, buffer, length,
311  if( cryptStatusError( status ) )
312  return( status );
313 
314  /* Perform the modexp and move the result back into the buffer. Since
315  the bignum code performs leading-zero truncation, we have to adjust
316  where we copy the result to in the buffer to take into account extra
317  zero bytes that aren't extracted from the bignum. In addition we
318  can't use the length returned from exportBignum() because this is the
319  length of the zero-truncated result, not the full length */
320  CK( BN_mod_exp_mont( data, data, e, n, pkcInfo->bnCTX,
321  &pkcInfo->rsaParam_mont_n ) );
322  if( bnStatusError( bnStatus ) )
323  return( getBnStatus( bnStatus ) );
324  offset = length - BN_num_bytes( data );
325  if( offset > 0 )
326  memset( buffer, 0, offset );
327  status = exportBignum( buffer + offset, noBytes - offset, &dummy, data );
328  if( cryptStatusError( status ) )
329  return( status );
330 
331  /* Perform side-channel attack checks if necessary */
332  if( ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) && \
333  cryptStatusError( calculateBignumChecksum( pkcInfo,
334  CRYPT_ALGO_RSA ) ) )
335  {
336  return( CRYPT_ERROR_FAILED );
337  }
338  return( CRYPT_OK );
339  }
340 
341 /* Use the Chinese Remainder Theorem shortcut for RSA decryption/signature
342  generation. n isn't needed because of this.
343 
344  There are two types of side-channel attack protection that we employ for
345  prvate-key operations, the first being standard blinding included in the
346  code below. The second type applies to CRT-based RSA implementations and
347  is based on the fact that if a fault occurs during the computation of p2
348  or q2 (to give, say, p2') then applying the CRT will yield a faulty
349  signature M'. An attacker can then compute q from
350  gcd( M' ** e - ( C mod n ), n ), and the same for q2' and p. The chances
351  of this actually occurring are... unlikely, given that it requires a
352  singleton failure inside the CPU (with data running over ECC-protected
353  buses) at the exact moment of CRT computation (the original threat model
354  assumed a fault-injection attack on a smart card), however we can still
355  provide protection against the problem for people who consider it a
356  genuine threat.
357 
358  The problem was originally pointed out by Marc Joye, Arjen Lenstra, and
359  Jean-Jacques Quisquater in "Chinese Remaindering Based Cryptosystems in
360  the Presence of Faults", Journal of Cryptology, Vol.12, No.4 (Autumn
361  1999), p.241, based on an earlier result "On the importance of checking
362  cryptographic protocols for faults", Dan Boneh, Richard DeMillo, and
363  Richard Lipton, EuroCrypt'97, LNCS Vol.1233, p.37. Adi Shamir presented
364  one possible solution to the problem in the conference's rump session in
365  "How to check modular exponentiation", which performs a parallel
366  computation of the potentially fault-affected portions of the CRT
367  operation in blinded form and then checks that the two outputs are
368  consistent. This has three drawbacks: It's slow, Shamir patented it
369  (US Patent 5,991,415), and if one CRT is faulty there's no guarantee
370  that the parallel CRT won't be faulty as well. Better solutions were
371  suggested by Sung-Ming Yen, Seungjoo Kim, Seongan Lim, and Sangjae
372  Moon in "RSA Speedup with Residue Number System Immune against Hardware
373  Fault Cryptanalysis", ICISC'01, LNCS Vol.2288, p.397. These have less
374  overhead than Shamir's approach and are also less patented, but like
375  Shamir's approach they involve messing around with the CRT computation.
376  A further update to this given by Sung-Ming Yen, Sangjae Kim, and Jae-
377  Cheol Ha in "Hardware Fault Attack on RSA with CRT Revisited", ICISC'02,
378  LNCS Vol.2587, p.374, which updated the earlier work and also found flaws
379  in Shamir's solution.
380 
381  A much simpler solution is just to verify the CRT-based private-key
382  operation with the matching public-key operation after we perform it.
383  Since this is only required for signatures (the output of a decrypt is
384  (a) never visible to an attacker and (b) verified via the PKCS #1
385  padding), we perform this operation at a higher level, performing a
386  signature verify after each signature generation at the crypto mechanism
387  level */
388 
389 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
390 static int decryptFn( INOUT CONTEXT_INFO *contextInfoPtr,
391  INOUT_BUFFER_FIXED( noBytes ) BYTE *buffer,
392  IN_LENGTH_SHORT int noBytes )
393  {
394  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
395  BIGNUM *p = &pkcInfo->rsaParam_p, *q = &pkcInfo->rsaParam_q;
396  BIGNUM *u = &pkcInfo->rsaParam_u, *e1 = &pkcInfo->rsaParam_exponent1;
397  BIGNUM *e2 = &pkcInfo->rsaParam_exponent2;
398  BIGNUM *data = &pkcInfo->tmp1, *p2 = &pkcInfo->tmp2, *q2 = &pkcInfo->tmp3;
399  const int length = bitsToBytes( pkcInfo->keySizeBits );
400  int iterationCount, offset, dummy, bnStatus = BN_STATUS, status;
401 
402  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
403  assert( isWritePtr( buffer, length ) );
404 
405  REQUIRES( noBytes == length );
406  REQUIRES( noBytes > 0 && noBytes < MAX_INTLENGTH_SHORT );
407 
408  /* Move the data from the buffer into a bignum. We need to make an
409  unfortunate exception to the valid-length check for SSL's weird
410  signatures, which sign a raw concatenated MD5 and SHA-1 hash with a
411  total length of 36 bytes */
412  status = importBignum( data, buffer, length, 36, CRYPT_MAX_PKCSIZE,
413  &pkcInfo->rsaParam_n, KEYSIZE_CHECK_NONE );
414  if( cryptStatusError( status ) )
415  return( status );
416  if( BN_num_bytes( data ) != 36 && \
417  BN_num_bytes( data ) < MIN_PKCSIZE - 8 )
418  {
419  /* If it's not the weird SSL signature and it's outside the valid
420  length range, reject it */
421  return( CRYPT_ERROR_BADDATA );
422  }
423 
424  /* If we're blinding the RSA operation, set
425  data = ( ( rand^e ) * data ) mod n */
426  if( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION )
427  {
428  CK( BN_mod_mul( data, data, &pkcInfo->rsaParam_blind_k,
429  &pkcInfo->rsaParam_n, pkcInfo->bnCTX ) );
430  if( bnStatusError( bnStatus ) )
431  return( getBnStatus( bnStatus ) );
432  }
433 
434  /* Rather than decrypting by computing a modexp with full mod n
435  precision, compute a shorter modexp with mod p and mod q precision:
436  p2 = ( ( C mod p ) ** exponent1 ) mod p
437  q2 = ( ( C mod q ) ** exponent2 ) mod q */
438  CK( BN_mod( p2, data, p, /* p2 = C mod p */
439  pkcInfo->bnCTX ) );
440  CK( BN_mod_exp_mont( p2, p2, e1, p, pkcInfo->bnCTX,
441  &pkcInfo->rsaParam_mont_p ) );
442  CK( BN_mod( q2, data, q, /* q2 = C mod q */
443  pkcInfo->bnCTX ) );
444  CK( BN_mod_exp_mont( q2, q2, e2, q, pkcInfo->bnCTX,
445  &pkcInfo->rsaParam_mont_q ) );
446  if( bnStatusError( bnStatus ) )
447  return( getBnStatus( bnStatus ) );
448 
449  /* p2 = p2 - q2; if p2 < 0 then p2 = p2 + p. In some extremely rare
450  cases (q2 large, p2 small) we have to add p twice to get p2
451  positive */
452  CK( BN_sub( p2, p2, q2 ) );
453  for( iterationCount = 0;
454  p2->neg && iterationCount < FAILSAFE_ITERATIONS_SMALL;
455  iterationCount++ )
456  {
457  CK( BN_add( p2, p2, p ) );
458  if( bnStatusError( bnStatus ) )
459  return( getBnStatus( bnStatus ) );
460  }
461  if( iterationCount >= FAILSAFE_ITERATIONS_SMALL )
462  retIntError();
463 
464  /* M = ( ( ( p2 * u ) mod p ) * q ) + q2 */
465  CK( BN_mod_mul( data, p2, u, p, /* data = ( p2 * u ) mod p */
466  pkcInfo->bnCTX ) );
467  CK( BN_mul( p2, data, q, /* p2 = data * q (bn can't reuse data) */
468  pkcInfo->bnCTX ) );
469  CK( BN_add( data, p2, q2 ) ); /* data = p2 + q2 */
470  if( bnStatusError( bnStatus ) )
471  return( getBnStatus( bnStatus ) );
472 
473  /* If we're blinding the RSA operation, set
474  data = ( ( data^e ) / rand ) mod n
475  = ( rand^-1 * data ) mod n */
476  if( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION )
477  {
478  BIGNUM *n = &pkcInfo->rsaParam_n;
479  BIGNUM *k = &pkcInfo->rsaParam_blind_k;
480  BIGNUM *kInv = &pkcInfo->rsaParam_blind_kInv;
481 
482  CK( BN_mod_mul( data, data, kInv, n, pkcInfo->bnCTX ) );
483  if( bnStatusError( bnStatus ) )
484  return( getBnStatus( bnStatus ) );
485 
486  /* Update the blinding values in such a way that we get new random
487  (that is, unpredictable to an outsider) numbers of the correct
488  form without having to do a full modexp as we would if starting
489  with new random data:
490 
491  k = ( k^2 ) mod n
492 
493  In theory we could replace the random blinding value periodically
494  in order to avoid an attacker being able to build up stats on it
495  and the values derived from it, but it seems unlikely that they
496  can do much with this and leads to problems of its own since the
497  process of calculating the new blinding value is itself
498  susceptible to side-channel attacks */
499  CK( BN_mod_mul( k, k, k, n, pkcInfo->bnCTX ) );
500  CK( BN_mod_mul( kInv, kInv, kInv, n, pkcInfo->bnCTX ) );
501  if( bnStatusError( bnStatus ) )
502  return( getBnStatus( bnStatus ) );
503  }
504 
505  /* Copy the result to the output. Since the bignum code performs
506  leading-zero truncation, we have to adjust where we copy the
507  result to in the buffer to take into account extra zero bytes
508  that aren't extracted from the bignum. In addition we can't use
509  the length returned from exportBignum() because this is the length
510  of the zero-truncated result, not the full length */
511  offset = length - BN_num_bytes( data );
512  if( offset > 0 )
513  memset( buffer, 0, offset );
514  status = exportBignum( buffer + offset, noBytes - offset, &dummy, data );
515  if( cryptStatusError( status ) )
516  return( status );
517 
518  /* Perform side-channel attack checks if necessary */
519  if( ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) && \
520  cryptStatusError( calculateBignumChecksum( pkcInfo,
521  CRYPT_ALGO_RSA ) ) )
522  {
523  return( CRYPT_ERROR_FAILED );
524  }
525  return( CRYPT_OK );
526  }
527 
528 /****************************************************************************
529 * *
530 * Load Key Components *
531 * *
532 ****************************************************************************/
533 
534 /* Load key components into an encryption context */
535 
537 static int initKey( INOUT CONTEXT_INFO *contextInfoPtr,
538  IN_BUFFER_OPT( keyLength ) const void *key,
539  IN_LENGTH_SHORT_OPT const int keyLength )
540  {
541  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
542  assert( ( key == NULL && keyLength == 0 ) || \
543  ( isReadPtr( key, keyLength ) && \
544  keyLength == sizeof( CRYPT_PKCINFO_RSA ) ) );
545 
546  REQUIRES( ( key == NULL && keyLength == 0 ) || \
547  ( key != NULL && keyLength == sizeof( CRYPT_PKCINFO_RSA ) ) );
548 
549 #ifndef USE_FIPS140
550  /* Load the key component from the external representation into the
551  internal bignums unless we're doing an internal load */
552  if( key != NULL )
553  {
554  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
555  const CRYPT_PKCINFO_RSA *rsaKey = ( CRYPT_PKCINFO_RSA * ) key;
556  int status;
557 
558  contextInfoPtr->flags |= ( rsaKey->isPublicKey ) ? \
560  status = importBignum( &pkcInfo->rsaParam_n, rsaKey->n,
561  bitsToBytes( rsaKey->nLen ),
564  if( cryptStatusOK( status ) )
565  status = importBignum( &pkcInfo->rsaParam_e, rsaKey->e,
566  bitsToBytes( rsaKey->eLen ),
568  &pkcInfo->rsaParam_n,
570  if( cryptStatusOK( status ) && !rsaKey->isPublicKey )
571  {
572  status = importBignum( &pkcInfo->rsaParam_d, rsaKey->d,
573  bitsToBytes( rsaKey->dLen ),
575  &pkcInfo->rsaParam_n,
577  if( cryptStatusOK( status ) )
578  status = importBignum( &pkcInfo->rsaParam_p, rsaKey->p,
579  bitsToBytes( rsaKey->pLen ),
581  &pkcInfo->rsaParam_n,
583  if( cryptStatusOK( status ) )
584  status = importBignum( &pkcInfo->rsaParam_q, rsaKey->q,
585  bitsToBytes( rsaKey->qLen ),
587  &pkcInfo->rsaParam_n,
589  if( cryptStatusOK( status ) && rsaKey->uLen > 0 )
590  status = importBignum( &pkcInfo->rsaParam_u, rsaKey->u,
591  bitsToBytes( rsaKey->uLen ),
593  &pkcInfo->rsaParam_n,
595  if( cryptStatusOK( status ) && rsaKey->e1Len > 0 )
596  status = importBignum( &pkcInfo->rsaParam_exponent1, rsaKey->e1,
597  bitsToBytes( rsaKey->e1Len ),
599  &pkcInfo->rsaParam_n,
601  if( cryptStatusOK( status ) && rsaKey->e2Len > 0 )
602  status = importBignum( &pkcInfo->rsaParam_exponent2, rsaKey->e2,
603  bitsToBytes( rsaKey->e2Len ),
605  &pkcInfo->rsaParam_n,
607  }
608  contextInfoPtr->flags |= CONTEXT_FLAG_PBO;
609  if( cryptStatusError( status ) )
610  return( status );
611  }
612 #endif /* USE_FIPS140 */
613 
614  /* Complete the key checking and setup */
615  return( initCheckRSAkey( contextInfoPtr ) );
616  }
617 
618 /* Generate a key into an encryption context */
619 
621 static int generateKey( INOUT CONTEXT_INFO *contextInfoPtr,
623  const int keySizeBits )
624  {
625  int status;
626 
627  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
628 
629  REQUIRES( keySizeBits >= bytesToBits( MIN_PKCSIZE ) && \
630  keySizeBits <= bytesToBits( CRYPT_MAX_PKCSIZE ) );
631 
632  status = generateRSAkey( contextInfoPtr, keySizeBits );
633  if( cryptStatusOK( status ) &&
634 #ifndef USE_FIPS140
635  ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) &&
636 #endif /* USE_FIPS140 */
637  !pairwiseConsistencyTest( contextInfoPtr ) )
638  {
639  DEBUG_DIAG(( "Consistency check of freshly-generated RSA key "
640  "failed" ));
641  assert( DEBUG_WARN );
642  status = CRYPT_ERROR_FAILED;
643  }
644  return( status );
645  }
646 
647 /****************************************************************************
648 * *
649 * Capability Access Routines *
650 * *
651 ****************************************************************************/
652 
653 static const CAPABILITY_INFO FAR_BSS capabilityInfo = {
654  CRYPT_ALGO_RSA, bitsToBytes( 0 ), "RSA", 3,
656  selfTest, getDefaultInfo, NULL, NULL, initKey, generateKey, encryptFn, decryptFn,
657  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
658  decryptFn, encryptFn
659  };
660 
662  {
663  return( &capabilityInfo );
664  }