cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
kg_rsa.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib RSA Key Generation/Checking Routines *
4 * Copyright Peter Gutmann 1997-2008 *
5 * *
6 ****************************************************************************/
7 
8 #define PKC_CONTEXT /* Indicate that we're working with PKC contexts */
9 #if defined( INC_ALL )
10  #include "crypt.h"
11  #include "context.h"
12  #include "keygen.h"
13 #else
14  #include "crypt.h"
15  #include "context/context.h"
16  #include "context/keygen.h"
17 #endif /* Compiler-specific includes */
18 
19 /* We use F4 as the default public exponent e unless the user chooses to
20  override this with some other value:
21 
22  Fn = 2^(2^n) + 1, n = 0...4.
23 
24  F0 = 3, F1 = 5, F2 = 17, F3 = 257, F4 = 65537.
25 
26  The older (X.509v1) recommended value of 3 is insecure for general use
27  and more recent work indicates that values like 17 (used by PGP) are also
28  insecure against the Hastad attack. We could work around this by using
29  41 or 257 as the exponent, however current best practice favours F4
30  unless you're doing banking standards, in which case you set e=2 (EMV)
31  and use raw, unpadded RSA (HBCI) to make it easier for students to break
32  your banking security as a homework exercise.
33 
34  Since some systems may be using 16-bit bignum component values we use an
35  exponent of 257 for these cases to ensure that it fits in a single
36  component value */
37 
38 #ifndef RSA_PUBLIC_EXPONENT
39  #ifdef SIXTEEN_BIT
40  #define RSA_PUBLIC_EXPONENT 257
41  #else
42  #define RSA_PUBLIC_EXPONENT 65537L
43  #endif /* 16-bit bignum components */
44 #endif /* RSA_PUBLIC_EXPONENT */
45 
46 /* The minimum allowed public exponent. In theory this could go as low as 3,
47  however there are all manner of obscure corner cases that have to be
48  checked if this exponent is used and in general the necessary checking
49  presents a more or less intractable problem. To avoid this minefield we
50  require a minimum exponent of at 17, the next generally-used value above
51  3. However even this is only used by PGP 2.x, the next minimum is 33 (a
52  weird value used by OpenSSH until mid-2010, see the comment further
53  down), 41 (another weird value used by GPG until mid-2006), and then 257
54  or (in practice) F4 / 65537 by everything else */
55 
56 #if defined( USE_PGP ) || defined( USE_PGPKEYS )
57  #define MIN_PUBLIC_EXPONENT 17
58 #elif defined( USE_SSH )
59  #define MIN_PUBLIC_EXPONENT 33
60 #else
61  #define MIN_PUBLIC_EXPONENT 257
62 #endif /* Smallest exponents used by various crypto protocols */
63 #if ( MIN_PUBLIC_EXPONENT <= 0xFF && RSAPARAM_MIN_E > 1 ) || \
64  ( MIN_PUBLIC_EXPONENT <= 0xFFFF && RSAPARAM_MIN_E > 2 )
65  #error RSAPARAM_MIN_E is too large for MIN_PUBLIC_EXPONENT
66 #endif /* MIN_PUBLIC_EXPONENT size > RSAPARAM_MIN_E value */
67 
68 /****************************************************************************
69 * *
70 * Utility Functions *
71 * *
72 ****************************************************************************/
73 
74 /* Enable various side-channel protection mechanisms */
75 
76 #if defined( __WINCE__ ) && defined( ARMV4 ) && defined( NDEBUG )
77  #pragma optimize( "g", off )
78 #endif /* eVC++ 4.0 ARMv4 optimiser bug */
79 
81 static int enableSidechannelProtection( INOUT PKC_INFO *pkcInfo,
82  const BOOLEAN isPrivateKey )
83  {
84  BIGNUM *n = &pkcInfo->rsaParam_n, *e = &pkcInfo->rsaParam_e;
85  BIGNUM *k = &pkcInfo->rsaParam_blind_k;
86  BIGNUM *kInv = &pkcInfo->rsaParam_blind_kInv;
89  int noBytes = bitsToBytes( pkcInfo->keySizeBits );
90  int bnStatus = BN_STATUS, status;
91 
92  assert( isWritePtr( pkcInfo, sizeof( PKC_INFO ) ) );
93 
94  /* Generate a random bignum for blinding. Since this merely has to be
95  unpredictable to an outsider but not cryptographically strong, and to
96  avoid having more crypto RNG output than necessary sitting around in
97  memory, we get it from the nonce PRNG rather than the crypto one. In
98  addition we don't have to perform a range check on import to see if
99  it's larger than 'n' since we're about to reduce it mod n in the next
100  step, and doing so would give false positives */
101  setMessageData( &msgData, buffer, noBytes );
103  &msgData, CRYPT_IATTRIBUTE_RANDOM_NONCE );
104  if( cryptStatusOK( status ) )
105  {
106  buffer[ 0 ] &= 0xFF >> ( -pkcInfo->keySizeBits & 7 );
107  status = importBignum( k, buffer, noBytes, MIN_PKCSIZE - 8,
108  CRYPT_MAX_PKCSIZE, NULL,
110  }
111  zeroise( buffer, noBytes );
112  if( cryptStatusError( status ) )
113  return( status );
114 
115  /* Set up the blinding and unblinding values */
116  CK( BN_mod( k, k, n, pkcInfo->bnCTX ) ); /* k = rand() mod n */
117  CKPTR( BN_mod_inverse( kInv, k, n, pkcInfo->bnCTX ) );
118  /* kInv = k^-1 mod n */
119  CK( BN_mod_exp_mont( k, k, e, n, pkcInfo->bnCTX,
120  &pkcInfo->rsaParam_mont_n ) );
121  /* k = k^e mod n */
122  if( bnStatusError( bnStatus ) )
123  return( getBnStatus( bnStatus ) );
124 
125  /* Use constant-time modexp() to protect the private key from timing
126  channels if required */
127  if( isPrivateKey )
128  {
129  BN_set_flags( &pkcInfo->rsaParam_exponent1, BN_FLG_EXP_CONSTTIME );
130  BN_set_flags( &pkcInfo->rsaParam_exponent2, BN_FLG_EXP_CONSTTIME );
131  }
132 
133  /* Checksum the bignums to try and detect fault attacks. Since we're
134  setting the checksum at this point there's no need to check the
135  return value */
136  ( void ) calculateBignumChecksum( pkcInfo, CRYPT_ALGO_RSA );
137 
138  return( CRYPT_OK );
139  }
140 
141 #if defined( __WINCE__ ) && defined( ARMV4 ) && defined( NDEBUG )
142  #pragma optimize( "g", on )
143 #endif /* eVC++ 4.0 ARMv4 optimiser bug */
144 
145 /* Adjust p and q if necessary to ensure that the CRT decrypt works */
146 
148 static int fixCRTvalues( INOUT PKC_INFO *pkcInfo,
149  const BOOLEAN fixPKCSvalues )
150  {
151  BIGNUM *p = &pkcInfo->rsaParam_p, *q = &pkcInfo->rsaParam_q;
152 
153  assert( isWritePtr( pkcInfo, sizeof( PKC_INFO ) ) );
154 
155  /* Make sure that p > q, which is required for the CRT decrypt */
156  if( BN_cmp( p, q ) >= 0 )
157  return( CRYPT_OK );
158 
159  /* Swap the values p and q and, if necessary, the PKCS parameters e1
160  and e2 that depend on them (e1 = d mod (p - 1) and
161  e2 = d mod (q - 1)), and recompute u = qInv mod p */
162  BN_swap( p, q );
163  if( !fixPKCSvalues )
164  return( CRYPT_OK );
165  BN_swap( &pkcInfo->rsaParam_exponent1, &pkcInfo->rsaParam_exponent2 );
166  return( BN_mod_inverse( &pkcInfo->rsaParam_u, q, p,
167  pkcInfo->bnCTX ) != NULL ? \
169  }
170 
171 /* Evaluate the Montgomery forms for public and private components */
172 
174 static int getRSAMontgomery( INOUT PKC_INFO *pkcInfo,
175  const BOOLEAN isPrivateKey )
176  {
177  assert( isWritePtr( pkcInfo, sizeof( PKC_INFO ) ) );
178 
179  /* Evaluate the public value */
180  if( !BN_MONT_CTX_set( &pkcInfo->rsaParam_mont_n, &pkcInfo->rsaParam_n,
181  pkcInfo->bnCTX ) )
182  return( CRYPT_ERROR_FAILED );
183  if( !isPrivateKey )
184  return( CRYPT_OK );
185 
186  /* Evaluate the private values */
187  return( BN_MONT_CTX_set( &pkcInfo->rsaParam_mont_p, &pkcInfo->rsaParam_p,
188  pkcInfo->bnCTX ) && \
189  BN_MONT_CTX_set( &pkcInfo->rsaParam_mont_q, &pkcInfo->rsaParam_q,
190  pkcInfo->bnCTX ) ? \
192  }
193 
194 /****************************************************************************
195 * *
196 * Check an RSA Key *
197 * *
198 ****************************************************************************/
199 
200 /* Perform validity checks on the public key. We have to make the PKC_INFO
201  data non-const because the bignum code wants to modify some of the values
202  as it's working with them */
203 
205 static int checkRSAPublicKeyComponents( INOUT PKC_INFO *pkcInfo )
206  {
207  BIGNUM *n = &pkcInfo->rsaParam_n, *e = &pkcInfo->rsaParam_e;
208  const BN_ULONG eWord = BN_get_word( e );
209  int length;
210 
211  assert( isWritePtr( pkcInfo, sizeof( PKC_INFO ) ) );
212 
213  /* Verify that nLen >= RSAPARAM_MIN_N (= MIN_PKCSIZE),
214  nLen <= RSAPARAM_MAX_N (= CRYPT_MAX_PKCSIZE) */
215  length = BN_num_bytes( n );
216  if( isShortPKCKey( length ) )
217  {
218  /* Special-case handling for insecure-sized public keys */
219  return( CRYPT_ERROR_NOSECURE );
220  }
221  if( length < RSAPARAM_MIN_N || length > RSAPARAM_MAX_N )
222  return( CRYPT_ARGERROR_STR1 );
223 
224  /* Verify that n is not (obviously) composite */
225  if( !primeSieve( n ) )
226  return( CRYPT_ARGERROR_STR1 );
227 
228  /* Verify that e >= MIN_PUBLIC_EXPONENT, eLen <= RSAPARAM_MAX_E
229  (= 32 bits). The latter check is to preclude DoS attacks due to
230  ridiculously large e values. BN_get_word() works even on 16-bit
231  systems because it returns BN_MASK2 (== UINT_MAX) if the value
232  can't be represented in a machine word */
233  if( eWord < MIN_PUBLIC_EXPONENT || \
235  return( CRYPT_ARGERROR_STR1 );
236 
237  /* Perform a second check to make sure that e will fit into a signed
238  integer. This isn't strictly required since a BN_ULONG is unsigned
239  but it's unlikely that anyone would consciously use a full 32-bit e
240  value (well, except for the German RegTP, who do all sorts of other
241  bizarre things as well) so we weed out any attempts to use one here */
242  if( BN_num_bits( e ) >= bytesToBits( sizeof( int ) ) )
243  return( CRYPT_ARGERROR_STR1 );
244 
245  /* Verify that e is a small prime. The easiest way to do this would be
246  to compare it to a set of standard values but there'll always be some
247  wierdo implementation that uses a nonstandard value and that would
248  therefore fail the test so we perform a quick check that just tries
249  dividing by all primes below 1000. In addition since in almost all
250  cases e will be one of a standard set of values we don't bother with
251  the trial division unless it's an unusual value. This test isn't
252  perfect but it'll catch obvious non-primes */
253  if( eWord != 17 && eWord != 257 && eWord != 65537L && !primeSieve( e ) )
254  {
255  /* OpenSSH versions up to 5.4 (released in 2010) hardcoded e = 35,
256  which is both a suboptimal exponent (it's less efficient that a
257  safer value like 257 or F4) and non-prime. The reason for this
258  was that the original SSH used an e relatively prime to
259  (p-1)(q-1), choosing odd (in both senses of the word)
260  numbers > 31. 33 or 35 probably ended up being chosen frequently
261  so it was hardcoded into OpenSSH for cargo-cult reasons, finally
262  being fixed after more than a decade to use F4. In order to use
263  pre-5.4 OpenSSH keys that use this odd value we make a special-
264  case exception for SSH use */
265 #ifdef USE_SSH
266  if( eWord == 33 || eWord == 35 )
267  return( CRYPT_OK );
268 #endif /* USE_SSH */
269 
270  return( CRYPT_ARGERROR_STR1 );
271  }
272 
273  return( CRYPT_OK );
274  }
275 
276 /* Perform validity checks on the private key. We have to make the PKC_INFO
277  data non-const because the bignum code wants to modify some of the values
278  as it's working with them */
279 
281 static int checkRSAPrivateKeyComponents( INOUT PKC_INFO *pkcInfo )
282  {
283  BIGNUM *n = &pkcInfo->rsaParam_n, *e = &pkcInfo->rsaParam_e;
284  BIGNUM *d = &pkcInfo->rsaParam_d, *p = &pkcInfo->rsaParam_p;
285  BIGNUM *q = &pkcInfo->rsaParam_q;
286  BIGNUM *p1 = &pkcInfo->tmp1, *q1 = &pkcInfo->tmp2, *tmp = &pkcInfo->tmp3;
287  const BN_ULONG eWord = BN_get_word( e );
288  int bnStatus = BN_STATUS;
289 
290  assert( isWritePtr( pkcInfo, sizeof( PKC_INFO ) ) );
291 
292  /* Verify that p, q aren't (obviously) composite */
293  if( !primeSieve( p ) || !primeSieve( q ) )
294  return( CRYPT_ARGERROR_STR1 );
295 
296  /* Verify that |p-q| > 128 bits. FIPS 186-3 requires only 100 bits,
297  this check is slightly more conservative but in any case both values
298  are somewhat arbitrary and are merely meant to delimit "not too
299  close". There's a second more obscure check that we could in theory
300  perform to make sure that p and q don't have the least significant
301  nLen / 4 bits the same (which would still lead to |p-q| > 128), this
302  would make the Boneh/Durfee attack marginally less improbable (result
303  by Zhao and Qi). Since the chance of them having 256 LSB bits the
304  same is vanishingly small and the Boneh/Dufree attack requires
305  special properties for d (see the comment in generateRSAkey()) we
306  don't bother with this check */
307  if( BN_cmp( p, q ) >= 0 )
308  {
309  CKPTR( BN_copy( tmp, p ) );
310  CK( BN_sub( tmp, tmp, q ) );
311  }
312  else
313  {
314  CKPTR( BN_copy( tmp, q ) );
315  CK( BN_sub( tmp, tmp, p ) );
316  }
317  if( bnStatusError( bnStatus ) || \
318  BN_num_bits( tmp ) < 128 )
319  return( CRYPT_ARGERROR_STR1 );
320 
321  /* Calculate p - 1, q - 1 */
322  CKPTR( BN_copy( p1, p ) );
323  CK( BN_sub_word( p1, 1 ) );
324  CKPTR( BN_copy( q1, q ) );
325  CK( BN_sub_word( q1, 1 ) );
326  if( bnStatusError( bnStatus ) )
327  return( CRYPT_ARGERROR_STR1 );
328 
329  /* Verify that n = p * q */
330  CK( BN_mul( tmp, p, q, pkcInfo->bnCTX ) );
331  if( bnStatusError( bnStatus ) || BN_cmp( n, tmp ) != 0 )
332  return( CRYPT_ARGERROR_STR1 );
333 
334  /* Verify that:
335 
336  p, q < d
337  ( d * e ) mod p-1 == 1
338  ( d * e ) mod q-1 == 1
339 
340  Some implementations don't store d since it's not needed when the CRT
341  shortcut is used so we can only perform this check if d is present */
342  if( !BN_is_zero( d ) )
343  {
344  if( BN_cmp( p, d ) >= 0 || BN_cmp( q, d ) >= 0 )
345  return( CRYPT_ARGERROR_STR1 );
346  CK( BN_mod_mul( tmp, d, e, p1, pkcInfo->bnCTX ) );
347  if( bnStatusError( bnStatus ) || !BN_is_one( tmp ) )
348  return( CRYPT_ARGERROR_STR1 );
349  CK( BN_mod_mul( tmp, d, e, q1, pkcInfo->bnCTX ) );
350  if( bnStatusError( bnStatus ) || !BN_is_one( tmp ) )
351  return( CRYPT_ARGERROR_STR1 );
352  }
353 
354 #ifdef USE_FIPS140
355  /* Verify that sizeof( d ) > sizeof( p ) / 2, a weird requirement set by
356  FIPS 186-3. This is one of those things where the probability of the
357  check going wrong in some way outweighs the probability of the
358  situation actually occurring by about two dozen orders of magnitude
359  so we only do this when we have to. The fact that this parameter is
360  never even used makes the check even less meaningful */
361  if( BN_num_bits( d ) <= pkcInfo->keySizeBits )
362  return( CRYPT_ARGERROR_STR1 );
363 #endif /* USE_FIPS140 */
364 
365  /* Verify that ( q * u ) mod p == 1. In some cases the p and q values
366  haven't been set up yet for the CRT decrypt to work (see the comment
367  in fixCRTvalues()) so we have to be prepared to accept them in either
368  order */
369  if( BN_cmp( p, q ) >= 0 )
370  CK( BN_mod_mul( tmp, q, &pkcInfo->rsaParam_u, p, pkcInfo->bnCTX ) );
371  else
372  CK( BN_mod_mul( tmp, p, &pkcInfo->rsaParam_u, q, pkcInfo->bnCTX ) );
373  if( bnStatusError( bnStatus ) || !BN_is_one( tmp ) )
374  return( CRYPT_ARGERROR_STR1 );
375 
376  /* Verify that e1 < p, e2 < q */
377  if( BN_cmp( &pkcInfo->rsaParam_exponent1, p ) >= 0 || \
378  BN_cmp( &pkcInfo->rsaParam_exponent2, q ) >= 0 )
379  return( CRYPT_ARGERROR_STR1 );
380 
381  /* Verify that u < p, where u was calculated as q^-1 mod p */
382  if( BN_cmp( &pkcInfo->rsaParam_u, p ) >= 0 )
383  return( CRYPT_ARGERROR_STR1 );
384 
385  /* A very small number of systems/compilers can't handle 32 * 32 -> 64
386  ops which means that we have to use 16-bit bignum components. For
387  the common case where e = F4 the value won't fit into a 16-bit bignum
388  component so we have to use the full BN_mod() form of the checks that
389  are carried out further on */
390 #ifdef SIXTEEN_BIT
391  CK( BN_mod( tmp, p1, e, pkcInfo->bnCTX ) );
392  if( bnStatusError( bnStatus ) || BN_is_zero( tmp ) )
393  return( CRYPT_ARGERROR_STR1 );
394  CK( BN_mod( tmp, q1, e, pkcInfo->bnCTX ) );
395  if( bnStatusError( bnStatus ) || BN_is_zero( tmp ) )
396  return( CRYPT_ARGERROR_STR1 );
397  return( CRYPT_OK );
398 #endif /* Systems without 32 * 32 -> 64 ops */
399 
400  /* Verify that gcd( ( p - 1 )( q - 1), e ) == 1
401 
402  Since e is a small prime we can do this much more efficiently by
403  checking that:
404 
405  ( p - 1 ) mod e != 0
406  ( q - 1 ) mod e != 0 */
407  if( BN_mod_word( p1, eWord ) == 0 || BN_mod_word( q1, eWord ) == 0 )
408  return( CRYPT_ARGERROR_STR1 );
409 
410  return( CRYPT_OK );
411  }
412 
413 /****************************************************************************
414 * *
415 * Initialise/Check an RSA Key *
416 * *
417 ****************************************************************************/
418 
419 /* Generate an RSA key pair into an encryption context. For FIPS 140
420  purposes the keygen method used here complies with FIPS 186-3 Appendix
421  B.3, "IFC Key Pair Generation", specifically method B.3.3, "Generation of
422  Random Primes that are Probably Prime". Note that FIPS 186-3 provides a
423  range of key-generation methods and allows implementations to select one
424  that's appropriate, this implementation provides the one in B.3.3, with
425  the exception that it allows keys in the range MIN_PKC_SIZE ...
426  CRYPT_MAX_PKCSIZE to be generated. FIPS 186-3 is rather confusing in
427  that it discusses conditions and requirements for generating pairs from
428  512 ... 3072 bits and then gives different lengths and restrictions on
429  lengths depending on which portion of text you consult. Because of this
430  confusion, and the fact that telling users that they can't generate the
431  key that they want because of some obscure document that they've never
432  even heard of will cause friction, we leave it as a policy decision to
433  define the appropriate key size to use */
434 
436 int generateRSAkey( INOUT CONTEXT_INFO *contextInfoPtr,
437  IN_LENGTH_SHORT_MIN( MIN_PKCSIZE * 8 ) const int keyBits )
438  {
439  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
440  BIGNUM *d = &pkcInfo->rsaParam_d, *p = &pkcInfo->rsaParam_p;
441  BIGNUM *q = &pkcInfo->rsaParam_q;
442  BIGNUM *tmp = &pkcInfo->tmp1;
443  int pBits, qBits, bnStatus = BN_STATUS, status;
444 
445  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
446 
447  REQUIRES( keyBits >= bytesToBits( MIN_PKCSIZE ) && \
448  keyBits <= bytesToBits( CRYPT_MAX_PKCSIZE ) );
449 
450  /* Determine how many bits to give to each of p and q */
451  pBits = ( keyBits + 1 ) / 2;
452  qBits = keyBits - pBits;
453  pkcInfo->keySizeBits = pBits + qBits;
454 
455  /* Generate the primes p and q and set them up so that the CRT decrypt
456  will work. FIPS 186-3 requires that they be in the range
457  sqr(2) * 2^(keyBits-1) ... 2^keyBits (so that pq will be exactly
458  keyBits long), but this is guaranteed by the way that generatePrime()
459  selects its prime values so we don't have to check explicitly for it
460  here */
461  BN_set_word( &pkcInfo->rsaParam_e, RSA_PUBLIC_EXPONENT );
462  status = generatePrime( pkcInfo, p, pBits, RSA_PUBLIC_EXPONENT );
463  if( cryptStatusOK( status ) )
464  status = generatePrime( pkcInfo, q, qBits, RSA_PUBLIC_EXPONENT );
465  if( cryptStatusOK( status ) )
466  status = fixCRTvalues( pkcInfo, FALSE );
467  if( cryptStatusError( status ) )
468  return( status );
469 
470  /* Compute d = eInv mod (p - 1)(q - 1) */
471  CK( BN_sub_word( p, 1 ) );
472  CK( BN_sub_word( q, 1 ) );
473  CK( BN_mul( tmp, p, q, pkcInfo->bnCTX ) );
474  CKPTR( BN_mod_inverse( d, &pkcInfo->rsaParam_e, tmp, pkcInfo->bnCTX ) );
475  if( bnStatusError( bnStatus ) )
476  return( getBnStatus( bnStatus ) );
477 
478 #ifdef USE_FIPS140
479  /* Check that sizeof( d ) > sizeof( p ) / 2, a weird requirement set by
480  FIPS 186-3. This is one of those things where the probability of the
481  check going wrong in some way outweighs the probability of the
482  situation actually occurring by about two dozen orders of magnitude
483  so we only do this when we have to. The fact that this parameter is
484  never even used makes the check even less meaningful.
485 
486  (This check possibly has something to do with defending against
487  Wiener's continued-fraction attack, which requires d < n^(1/4) in
488  order to succeed, later extended into the range d < n^(0.29) by
489  Boneh and Durfee/Bloemer and May and d < 1/2 n^(1/2) by Maitra and
490  Sarkar) */
491  if( BN_num_bits( d ) <= pkcInfo->keySizeBits / 2 )
492  return( CRYPT_ERROR_FAILED );
493 #endif /* USE_FIPS140 */
494 
495  /* Compute e1 = d mod (p - 1), e2 = d mod (q - 1) */
496  CK( BN_mod( &pkcInfo->rsaParam_exponent1, d,
497  p, pkcInfo->bnCTX ) );
498  CK( BN_mod( &pkcInfo->rsaParam_exponent2, d, q, pkcInfo->bnCTX ) );
499  CK( BN_add_word( p, 1 ) );
500  CK( BN_add_word( q, 1 ) );
501  if( bnStatusError( bnStatus ) )
502  return( getBnStatus( bnStatus ) );
503 
504  /* Compute n = pq, u = qInv mod p */
505  CK( BN_mul( &pkcInfo->rsaParam_n, p, q, pkcInfo->bnCTX ) );
506  CKPTR( BN_mod_inverse( &pkcInfo->rsaParam_u, q, p, pkcInfo->bnCTX ) );
507  if( bnStatusError( bnStatus ) )
508  return( getBnStatus( bnStatus ) );
509 
510  /* Since the keygen is randomised it may occur that the final size of
511  the public value that determines its nominal size is slightly smaller
512  than the requested nominal size. To handle this we recalculate the
513  effective key size after we've finished generating the public value
514  that determines its nominal size */
515  pkcInfo->keySizeBits = BN_num_bits( &pkcInfo->rsaParam_n );
516 
517  /* Evaluate the Montgomery forms */
518  status = getRSAMontgomery( pkcInfo, TRUE );
519  if( cryptStatusError( status ) )
520  return( status );
521 
522  /* Make sure that the generated values are valid */
523  status = checkRSAPublicKeyComponents( pkcInfo );
524  if( cryptStatusOK( status ) )
525  status = checkRSAPrivateKeyComponents( pkcInfo );
526  if( cryptStatusError( status ) )
527  return( status );
528 
529  /* Enable side-channel protection if required */
530  if( !( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) )
531  return( CRYPT_OK );
532  return( enableSidechannelProtection( pkcInfo, TRUE ) );
533  }
534 
535 /* Initialise and check an RSA key */
536 
538 int initCheckRSAkey( INOUT CONTEXT_INFO *contextInfoPtr )
539  {
540  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
541  BIGNUM *n = &pkcInfo->rsaParam_n, *e = &pkcInfo->rsaParam_e;
542  BIGNUM *d = &pkcInfo->rsaParam_d, *p = &pkcInfo->rsaParam_p;
543  BIGNUM *q = &pkcInfo->rsaParam_q;
544  const BOOLEAN isPrivateKey = \
545  ( contextInfoPtr->flags & CONTEXT_FLAG_ISPUBLICKEY ) ? FALSE : TRUE;
546  int bnStatus = BN_STATUS, status = CRYPT_OK;
547 
548  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
549 
550  /* Make sure that the necessary key parameters have been initialised */
551  if( BN_is_zero( n ) || BN_is_zero( e ) )
552  return( CRYPT_ARGERROR_STR1 );
553  if( isPrivateKey )
554  {
555  if( BN_is_zero( p ) || BN_is_zero( q ) )
556  return( CRYPT_ARGERROR_STR1 );
557  if( BN_is_zero( d ) && \
558  ( BN_is_zero( &pkcInfo->rsaParam_exponent1 ) || \
559  BN_is_zero( &pkcInfo->rsaParam_exponent2 ) ) )
560  {
561  /* Either d or e1+e2 must be present, d isn't needed if we have
562  e1+e2 and e1+e2 can be reconstructed from d */
563  return( CRYPT_ARGERROR_STR1 );
564  }
565  }
566 
567  /* Make sure that the public key parameters are valid */
568  status = checkRSAPublicKeyComponents( pkcInfo );
569  if( cryptStatusError( status ) )
570  return( status );
571 
572  /* If it's a public key, we're done */
573  if( !isPrivateKey )
574  {
575  /* Precompute the Montgomery forms of required values */
576  status = getRSAMontgomery( pkcInfo, FALSE );
577  if( cryptStatusError( status ) )
578  return( status );
579  pkcInfo->keySizeBits = BN_num_bits( &pkcInfo->rsaParam_n );
580 
581  /* Enable side-channel protection if required */
582  if( !( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) )
583  return( CRYPT_OK );
584  return( enableSidechannelProtection( pkcInfo, FALSE ) );
585  }
586 
587  /* If we're not using PKCS keys that have exponent1 = d mod ( p - 1 )
588  and exponent2 = d mod ( q - 1 ) precalculated, evaluate them now.
589  If there's no u precalculated, evaluate it now */
590  if( BN_is_zero( &pkcInfo->rsaParam_exponent1 ) )
591  {
592  BIGNUM *exponent1 = &pkcInfo->rsaParam_exponent1;
593  BIGNUM *exponent2 = &pkcInfo->rsaParam_exponent2;
594 
595  /* exponent1 = d mod ( p - 1 ) ) */
596  CKPTR( BN_copy( exponent1, p ) );
597  CK( BN_sub_word( exponent1, 1 ) );
598  CK( BN_mod( exponent1, d, exponent1, pkcInfo->bnCTX ) );
599  if( bnStatusError( bnStatus ) )
600  return( getBnStatus( bnStatus ) );
601 
602  /* exponent2 = d mod ( q - 1 ) ) */
603  CKPTR( BN_copy( exponent2, q ) );
604  CK( BN_sub_word( exponent2, 1 ) );
605  CK( BN_mod( exponent2, d, exponent2, pkcInfo->bnCTX ) );
606  if( bnStatusError( bnStatus ) )
607  return( getBnStatus( bnStatus ) );
608  }
609  if( BN_is_zero( &pkcInfo->rsaParam_u ) )
610  {
611  CKPTR( BN_mod_inverse( &pkcInfo->rsaParam_u, q, p,
612  pkcInfo->bnCTX ) );
613  if( bnStatusError( bnStatus ) )
614  return( getBnStatus( bnStatus ) );
615  }
616 
617  /* We've got the remaining components set up, perform further validity
618  checks on the private key */
619  status = checkRSAPrivateKeyComponents( pkcInfo );
620  if( cryptStatusError( status ) )
621  return( status );
622 
623  /* Make sure that p and q are set up correctly for the CRT decryption
624  (we can do this after checkRSAPrivateKeyComponents() since it'll work
625  with the CRT values in any order) */
626  status = fixCRTvalues( pkcInfo, TRUE );
627  if( cryptStatusError( status ) )
628  return( status );
629 
630  /* Precompute the Montgomery forms of required values */
631  status = getRSAMontgomery( pkcInfo, TRUE );
632  if( cryptStatusError( status ) )
633  return( status );
634  pkcInfo->keySizeBits = BN_num_bits( &pkcInfo->rsaParam_n );
635 
636  /* Enable side-channel protection if required */
637  if( !( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) )
638  return( CRYPT_OK );
639  return( enableSidechannelProtection( pkcInfo, TRUE ) );
640  }