cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
ctx_ecdsa.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib ECDSA Encryption Routines *
4 * Copyright Matthias Bruestle and Peter Gutmann 2006-2009 *
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 #else
13  #include "crypt.h"
14  #include "context/context.h"
15 #endif /* Compiler-specific includes */
16 
17 #ifdef USE_ECDSA
18 
19 /* ECDSA has the same problem with parameters that DSA does (see the comment
20  in the DSA code for details), see "Digital Signature Schemes with Domain
21  Parameters", Serge Vaudenay, ACISP'04, p.188 */
22 
23 /****************************************************************************
24 * *
25 * Utility Routines *
26 * *
27 ****************************************************************************/
28 
29 /* Technically, ECDSA can be used with any hash function, including ones
30  with a block size larger than the subgroup order (although in practice
31  the hash function always seems to be matched to the subgroup size). To
32  handle the possibility of a mismatched size we use the following custom
33  conversion function, which applies the conversion rules for transforming
34  the hash value into an integer from X9.62. For a group order n, of size
35  nlen (where 2 ^ (nlen-1) <= n < 2 ^ nlen), X9.62 mandates that the hash
36  value is first truncated to its leftmost nlen bits if nlen is smaller
37  than the hash value bit length before conversion to a bignum.
38  Mathematically, this is equivalent to first converting the value to a
39  bignum and then right-shifting it by hlen - nlen bits, where hlen is the
40  hash length in bits (a more generic way to view the required conversion
41  is 'while( BN_num_bits( hash ) > BN_num_bits( n )
42  { BN_rshift( hash, 1 ); }'). Finally, we reduce the value modulo n,
43  which is a simple matter of a compare-and-subtract */
44 
45 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
46 static int hashToBignum( INOUT BIGNUM *bigNum,
47  IN_BUFFER( hashLength ) const void *hash,
48  IN_LENGTH_HASH const int hashLength,
49  const BIGNUM *n )
50  {
51  const int hlen = bytesToBits( hashLength );
52  const int nlen = BN_num_bits( n );
53  int bnStatus = BN_STATUS, status;
54 
55  assert( isWritePtr( bigNum, sizeof( BIGNUM ) ) );
56  assert( isReadPtr( hash, hashLength ) );
57  assert( isReadPtr( n, sizeof( BIGNUM ) ) );
58 
59  REQUIRES( hashLength >= 20 && hashLength <= CRYPT_MAX_HASHSIZE );
60 
61  /* Convert the hash value into a bignum. We have to be careful when
62  we specify the bounds because, with increasingly smaller
63  probabilities, the leading bytes of the hash value may be zero.
64  The check used here gives one in 4 billion chance of a false
65  positive */
66  status = importBignum( bigNum, hash, hashLength,
67  hashLength - 3, hashLength + 1, NULL,
69  if( cryptStatusError( status ) )
70  return( status );
71 
72  /* Shift out any extra bits */
73  if( hlen > nlen )
74  {
75  CK( BN_rshift( bigNum, bigNum, hlen - nlen ) );
76  if( bnStatusError( bnStatus ) )
77  return( getBnStatus( bnStatus ) );
78  }
79 
80  /* Make sure that the value really is smaller than the group order */
81  if( BN_cmp( bigNum, n ) >= 0 )
82  {
83  CK( BN_sub( bigNum, bigNum, n ) );
84  if( bnStatusError( bnStatus ) )
85  return( getBnStatus( bnStatus ) );
86  }
87 
88  return( CRYPT_OK );
89  }
90 
91 /****************************************************************************
92 * *
93 * Algorithm Self-test *
94 * *
95 ****************************************************************************/
96 
97 /* The SHA-256 hash of the string "Example of ECDSA with ansip256r1 and
98  SHA-256". Note that X9.62-2005 contains both the message text and its
99  hash value, but the text (as given in X9.62) is wrong since it uses
100  'ansix9p256r1' instead of 'ansip256r1'. The text above matches the given
101  hash value, and the rest of the test vector */
102 
103 static const FAR_BSS BYTE shaM[] = {
104  0x1B, 0xD4, 0xED, 0x43, 0x0B, 0x0F, 0x38, 0x4B,
105  0x4E, 0x8D, 0x45, 0x8E, 0xFF, 0x1A, 0x8A, 0x55,
106  0x32, 0x86, 0xD7, 0xAC, 0x21, 0xCB, 0x2F, 0x68,
107  0x06, 0x17, 0x2E, 0xF5, 0xF9, 0x4A, 0x06, 0xAD
108  };
109 
110 /* Perform a pairwise consistency test on a public/private key pair */
111 
113 static BOOLEAN pairwiseConsistencyTest( CONTEXT_INFO *contextInfoPtr )
114  {
115  const CAPABILITY_INFO *capabilityInfoPtr = contextInfoPtr->capabilityInfo;
116  DLP_PARAMS dlpParams;
117  BYTE buffer[ 128 + 8 ];
118  int sigSize, status;
119 
120  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
121 
122  /* Generate a signature with the private key */
123  setDLPParams( &dlpParams, shaM, 32, buffer, 128 );
124  dlpParams.inLen2 = -999;
125  status = capabilityInfoPtr->signFunction( contextInfoPtr,
126  ( BYTE * ) &dlpParams, sizeof( DLP_PARAMS ) );
127  if( cryptStatusError( status ) )
128  return( FALSE );
129 
130  /* Verify the signature with the public key */
131  sigSize = dlpParams.outLen;
132  setDLPParams( &dlpParams, shaM, 32, NULL, 0 );
133  dlpParams.inParam2 = buffer;
134  dlpParams.inLen2 = sigSize;
135  status = capabilityInfoPtr->sigCheckFunction( contextInfoPtr,
136  ( BYTE * ) &dlpParams, sizeof( DLP_PARAMS ) );
137  return( cryptStatusOK( status ) ? TRUE : FALSE );
138  }
139 
140 #ifndef CONFIG_NO_SELFTEST
141 
142 /* Test the ECDSA implementation using the test vectors from ANSI
143  X9.62-2005, in this case from section L.4.2, which uses P-256. Note that
144  the test vector contains the Q point in compressed format only. Qy can
145  be computed from the private key d or by using point decompression, which
146  was done manually here: Qy is one of the square roots of Qx^3-3*Qx+b (the
147  compressed format contains the LSB of Qy, here 1, which allows us to
148  unambiguously choose the square root).
149 
150  Because a lot of the high-level encryption routines don't exist yet, we
151  cheat a bit and set up a dummy encryption context with just enough
152  information for the following code to work */
153 
154 #define ECDSA_TESTVECTOR_SIZE 32
155 
156 typedef struct {
157  const int qxLen; const BYTE qx[ 32 ];
158  const int qyLen; const BYTE qy[ 32 ];
159  const int dLen; const BYTE d[ 32 ];
160  } ECC_KEY;
161 
162 static const FAR_BSS ECC_KEY ecdsaTestKey = {
163  /* qx */
164  32,
165  { 0x59, 0x63, 0x75, 0xE6, 0xCE, 0x57, 0xE0, 0xF2,
166  0x02, 0x94, 0xFC, 0x46, 0xBD, 0xFC, 0xFD, 0x19,
167  0xA3, 0x9F, 0x81, 0x61, 0xB5, 0x86, 0x95, 0xB3,
168  0xEC, 0x5B, 0x3D, 0x16, 0x42, 0x7C, 0x27, 0x4D },
169  32,
170  /* qy */
171  { 0x42, 0x75, 0x4D, 0xFD, 0x25, 0xC5, 0x6F, 0x93,
172  0x9A, 0x79, 0xF2, 0xB2, 0x04, 0x87, 0x6B, 0x3A,
173  0x3A, 0xB1, 0xCE, 0xB2, 0xE4, 0xFF, 0x57, 0x1A,
174  0xBF, 0x4F, 0xBF, 0x36, 0x32, 0x6C, 0x8B, 0x27 },
175  32,
176  /* d */
177  { 0x2C, 0xA1, 0x41, 0x1A, 0x41, 0xB1, 0x7B, 0x24,
178  0xCC, 0x8C, 0x3B, 0x08, 0x9C, 0xFD, 0x03, 0x3F,
179  0x19, 0x20, 0x20, 0x2A, 0x6C, 0x0D, 0xE8, 0xAB,
180  0xB9, 0x7D, 0xF1, 0x49, 0x8D, 0x50, 0xD2, 0xC8 }
181  };
182 
183 /* If we're doing a self-test using the X9.62 values we use the following
184  fixed k data rather than a randomly-generated value. The corresponding
185  signature value for the fixed k should be:
186 
187  r = D73CD3722BAE6CC0B39065BB4003D8ECE1EF2F7A8A55BFD677234B0B3B902650
188  s = D9C88297FEFED8441E08DDA69554A6452B8A0BD4A0EA1DDB750499F0C2298C2F */
189 
190 static const FAR_BSS BYTE kVal[] = {
191  0xA0, 0x64, 0x0D, 0x49, 0x57, 0xF2, 0x7D, 0x09,
192  0x1A, 0xB1, 0xAE, 0xBC, 0x69, 0x94, 0x9D, 0x96,
193  0xE5, 0xAC, 0x2B, 0xB2, 0x83, 0xED, 0x52, 0x84,
194  0xA5, 0x67, 0x47, 0x58, 0xB1, 0x2F, 0x08, 0xDF
195  };
196 
197 CHECK_RETVAL \
198 static int selfTest( void )
199  {
200  CONTEXT_INFO contextInfo;
201  PKC_INFO contextData, *pkcInfo = &contextData;
202  int status;
203 
204  /* Initialise the key components */
205  status = staticInitContext( &contextInfo, CONTEXT_PKC,
206  getECDSACapability(), &contextData,
207  sizeof( PKC_INFO ), NULL );
208  if( cryptStatusError( status ) )
209  return( CRYPT_ERROR_FAILED );
210  pkcInfo->curveType = CRYPT_ECCCURVE_P256;
211  status = importBignum( &pkcInfo->eccParam_qx, ecdsaTestKey.qx,
212  ecdsaTestKey.qxLen, ECCPARAM_MIN_QX,
214  if( cryptStatusOK( status ) )
215  status = importBignum( &pkcInfo->eccParam_qy, ecdsaTestKey.qy,
216  ecdsaTestKey.qyLen, ECCPARAM_MIN_QY,
218  if( cryptStatusOK( status ) )
219  status = importBignum( &pkcInfo->eccParam_d, ecdsaTestKey.d,
220  ecdsaTestKey.dLen, ECCPARAM_MIN_D,
222  if( cryptStatusError( status ) )
223  {
224  staticDestroyContext( &contextInfo );
225  retIntError();
226  }
227 
228  /* Perform the test sign/sig.check of the X9.62 test values */
229  status = contextInfo.capabilityInfo->initKeyFunction( &contextInfo, NULL, 0 );
230  if( cryptStatusOK( status ) && \
231  !pairwiseConsistencyTest( &contextInfo ) )
232  status = CRYPT_ERROR_FAILED;
233 
234  /* Clean up */
235  staticDestroyContext( &contextInfo );
236 
237  return( status );
238  }
239 #else
240  #define selfTest NULL
241 #endif /* !CONFIG_NO_SELFTEST */
242 
243 /****************************************************************************
244 * *
245 * Create/Check a Signature *
246 * *
247 ****************************************************************************/
248 
249 /* Since ECDSA signature generation produces two values and the
250  cryptEncrypt() model only provides for passing a byte string in and out
251  (or, more specifically, the internal bignum data can't be exported to the
252  outside world) we need to encode the resulting data into a flat format.
253  This is done by encoding the output as an X9.31 Dss-Sig record, which is
254  also used for ECDSA:
255 
256  Dss-Sig ::= SEQUENCE {
257  r INTEGER,
258  s INTEGER
259  } */
260 
261 /* Sign a single block of data. There's a possibility of fault attacks
262  against ECDSA as detailed by a variety of authors, "Differential Fault
263  Attacks on Elliptic Curve Cryptosystems", Ingrid Biehl, Bernd Meyer and
264  Volker Mueller, Crypto 2000, LNCS No.1880, p.131, "Validation of Elliptic
265  Curve Public Keys", Adrian Antipa, Daniel Brown, Alfred Menezes, Ren�
266  Struik and Scott Vanstone, PKC 2003, LNCS No.2567, p.211, "Elliptic Curve
267  Cryptosystems in the Presence of Permanent and Transient Faults", Mathieu
268  Ciet and Marc Joye, Designs, Codes and Cryptography, Vol.36, No.1 (2005),
269  p.33, and "Error Detection and Fault Tolerance in ECSM Using Input
270  Randomisation", Agustin Dominguez-Oviedo and M. Anwar Hasan, IEEE
271  Transactions on Dependable and Secure Computing, Vol.6, No.6, p.175, which
272  for the most case can be defended against by point validation, i.e.
273  through the use of isPointOnCurve() in kg_ecc.c.
274 
275  A much simpler solution is just to verify the private-key operation with
276  the matching public-key operation after we perform it. This operation is
277  handled at a higher level (to accomodate algorithms like RSA for which
278  the private-key operation could be a sign or a decrypt and we only need
279  to check the sign), performing a signature verify after each signature
280  generation at the crypto mechanism level */
281 
282 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
283 static int sign( INOUT CONTEXT_INFO *contextInfoPtr,
284  INOUT_BUFFER_FIXED( noBytes ) BYTE *buffer,
285  IN_LENGTH_FIXED( sizeof( DLP_PARAMS ) ) int noBytes )
286  {
287  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
288  DLP_PARAMS *eccParams = ( DLP_PARAMS * ) buffer;
289  BIGNUM *n = &pkcInfo->eccParam_n;
290  BIGNUM *hash = &pkcInfo->tmp1, *x = &pkcInfo->tmp2;
291  BIGNUM *k = &pkcInfo->tmp3, *r = &pkcInfo->tmp4, *s = &pkcInfo->tmp5;
292  EC_GROUP *ecCTX = pkcInfo->ecCTX;
293  EC_POINT *kg = pkcInfo->tmpPoint;
294  int bnStatus = BN_STATUS, status = CRYPT_OK;
295 
296  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
297  assert( isWritePtr( eccParams, sizeof( DLP_PARAMS ) ) );
298  assert( isReadPtr( eccParams->inParam1, eccParams->inLen1 ) );
299  assert( isWritePtr( eccParams->outParam, eccParams->outLen ) );
300 
301  REQUIRES( noBytes == sizeof( DLP_PARAMS ) );
302  REQUIRES( eccParams->inParam2 == NULL && \
303  ( eccParams->inLen2 == 0 || eccParams->inLen2 == -999 ) );
304  REQUIRES( eccParams->outLen >= MIN_CRYPT_OBJECTSIZE && \
305  eccParams->outLen < MAX_INTLENGTH_SHORT );
306 
307  /* Generate the secret random value k. During the initial self-test the
308  random data pool may not exist yet, and may in fact never exist in a
309  satisfactory condition if there isn't enough randomness present in
310  the system to generate cryptographically strong random numbers. To
311  bypass this problem, if the caller passes in a second length
312  parameter of -999 we know that it's an internal self-test call and
313  use a fixed bit pattern for k that avoids having to call
314  generateBignum() (this also means that we can use the fixed self-test
315  value for k). This is a somewhat ugly use of 'magic numbers' but
316  it's safe because this function can only be called internally so all
317  that we need to trap is accidental use of the parameter which is
318  normally unused */
319  if( eccParams->inLen2 == -999 )
320  {
321  status = importBignum( k, ( BYTE * ) kVal, ECDSA_TESTVECTOR_SIZE,
322  ECDSA_TESTVECTOR_SIZE,
323  ECDSA_TESTVECTOR_SIZE, NULL,
325  }
326  else
327  {
328  /* Generate the random value k from [1...n-1], i.e. a random value
329  mod n. Using a random value of the same length as r would
330  produce a slight bias in k that leaks a small amount of the
331  private key in each signature. Because of this we start with a
332  value which is DLP_OVERFLOW_SIZE larger than r and then do the
333  reduction, eliminating the bias */
334  status = generateBignum( k, BN_num_bits( n ) + \
335  bytesToBits( DLP_OVERFLOW_SIZE ), 0x80, 0 );
336  }
337  if( cryptStatusError( status ) )
338  return( status );
339  if( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION )
340  {
341  /* Use constant-time modexp() to protect the secret random value
342  from timing channels. We could also use blinding, but neither of
343  these measures are actually terribly useful because we're using a
344  random exponent each time so the timing information isn't of much
345  use to an attacker */
347  }
348  CK( BN_mod( k, k, n, /* Reduce k to the correct range */
349  pkcInfo->bnCTX ) );
350  if( bnStatusError( bnStatus ) )
351  return( getBnStatus( bnStatus ) );
352 
353  /* Make sure that the result isn't zero (or more generally less than 64
354  bits). Admittedly the chances of this are infinitesimally small
355  (2^-192, the size of the smallest curve, or less for a value of zero,
356  2^-128 for 64 bits) but someone's bound to complain if we don't
357  check */
358  ENSURES( BN_num_bytes( k ) > 8 );
359 
360  /* Convert the hash value to an integer in the proper range */
361  status = hashToBignum( hash, eccParams->inParam1, eccParams->inLen1, n );
362  if( cryptStatusError( status ) )
363  return( status );
364 
365  /* Compute the point kG. EC_POINT_mul() extracts the generator G from
366  the curve definition (and see the long comment in sigCheck() about
367  the peculiarities of this function) */
368  CK( EC_POINT_mul( ecCTX, kg, k, NULL, NULL, pkcInfo->bnCTX ) );
369  if( bnStatusError( bnStatus ) )
370  return( getBnStatus( bnStatus ) );
371 
372  /* r = kG.x mod G.r (s is a dummy) */
373  CK( EC_POINT_get_affine_coordinates_GFp( ecCTX, kg, x, s,
374  pkcInfo->bnCTX ) );
375  CK( BN_mod( r, x, n, pkcInfo->bnCTX ) );
376  if( bnStatusError( bnStatus ) )
377  return( getBnStatus( bnStatus ) );
378 
379  /* k = ( k^-1 ) mod n */
380  CKPTR( BN_mod_inverse( k, k, n, pkcInfo->bnCTX ) );
381  if( bnStatusError( bnStatus ) )
382  return( getBnStatus( bnStatus ) );
383 
384  /* s = k^-1 * ( d * r + e ) mod n */
385  CK( BN_mod_mul( s, &pkcInfo->eccParam_d, r, n, pkcInfo->bnCTX ) );
386  CK( BN_mod_add( s, s, hash, n, pkcInfo->bnCTX ) );
387  CK( BN_mod_mul( s, s, k, n, pkcInfo->bnCTX ) );
388  if( bnStatusError( bnStatus ) )
389  return( getBnStatus( bnStatus ) );
390 
391  /* Check that neither r = 0 or s = 0. See the earlier comment where k
392  is checked for the real necessity of this check */
393  ENSURES( !BN_is_zero( r ) && !BN_is_zero( s ) );
394 
395  /* Encode the result as a DL data block */
396  status = pkcInfo->encodeDLValuesFunction( eccParams->outParam,
397  eccParams->outLen, &eccParams->outLen,
398  r, s, eccParams->formatType );
399  if( cryptStatusError( status ) )
400  return( status );
401 
402  /* Perform side-channel attack checks if necessary */
403  if( ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) && \
404  cryptStatusError( calculateBignumChecksum( pkcInfo,
405  CRYPT_ALGO_ECDSA ) ) )
406  {
407  return( CRYPT_ERROR_FAILED );
408  }
409  return( CRYPT_OK );
410  }
411 
412 /* Signature check a single block of data */
413 
414 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
415 static int sigCheck( INOUT CONTEXT_INFO *contextInfoPtr,
416  IN_BUFFER( noBytes ) BYTE *buffer,
417  IN_LENGTH_FIXED( sizeof( DLP_PARAMS ) ) int noBytes )
418  {
419  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
420  DLP_PARAMS *eccParams = ( DLP_PARAMS * ) buffer;
421  BIGNUM *n = &pkcInfo->eccParam_n;
422  BIGNUM *qx = &pkcInfo->eccParam_qx, *qy = &pkcInfo->eccParam_qy;
423  BIGNUM *u1 = &pkcInfo->tmp1, *u2 = &pkcInfo->tmp2;
424  BIGNUM *r = &pkcInfo->tmp3, *s = &pkcInfo->tmp4;
425  EC_GROUP *ecCTX = pkcInfo->ecCTX;
426  EC_POINT *u1gu2q = pkcInfo->tmpPoint, *u2q;
427  int bnStatus = BN_STATUS, status;
428 
429  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
430  assert( isWritePtr( eccParams, sizeof( DLP_PARAMS ) ) );
431  assert( isReadPtr( eccParams->inParam1, eccParams->inLen1 ) );
432  assert( isReadPtr( eccParams->inParam2, eccParams->inLen2 ) );
433 
434  REQUIRES( noBytes == sizeof( DLP_PARAMS ) );
435  REQUIRES( eccParams->outParam == NULL && eccParams->outLen == 0 );
436 
437  /* Decode the values from a DL data block and make sure that r and s are
438  valid, i.e. r, s = [1...n-1] */
439  status = pkcInfo->decodeDLValuesFunction( eccParams->inParam2,
440  eccParams->inLen2, r, s, n,
441  eccParams->formatType );
442  if( cryptStatusError( status ) )
443  return( status );
444 
445  /* Convert the hash value to an integer in the proper range. */
446  status = hashToBignum( u1, eccParams->inParam1, eccParams->inLen1, n );
447  if( cryptStatusError( status ) )
448  return( status );
449 
450  /* We've got all the data that we need, allocate the EC points working
451  variable */
452  CKPTR( u2q = EC_POINT_new( ecCTX ) );
453  if( bnStatusError( bnStatus ) )
454  return( getBnStatus( bnStatus ) );
455 
456  /* w = s^-1 mod G.r */
457  CKPTR( BN_mod_inverse( u2, s, n, pkcInfo->bnCTX ) );
458 
459  /* u1 = ( hash * w ) mod G.r */
460  CK( BN_mod_mul( u1, u1, u2, n, pkcInfo->bnCTX ) );
461 
462  /* u2 = ( r * w ) mod G.r */
463  CK( BN_mod_mul( u2, r, u2, n, pkcInfo->bnCTX ) );
464 
465  /* R = u1*G + u2*Q. EC_POINT_mul() is a somewhat weird function that
466  supports faster ECDSA signature verification by allowing two point
467  multiplications to be done in a single call to EC_POINT_mul(). The
468  implementation of the multiplication process uses window-based
469  optimizations (also known as "Shamir's trick", according to the
470  "Guide to Elliptic Curve Cryptography") which computes nG + mQ faster
471  than if both point multiplications were done separately */
472  CK( EC_POINT_set_affine_coordinates_GFp( ecCTX, u2q, qx, qy,
473  pkcInfo->bnCTX ) );
474  CK( EC_POINT_mul( ecCTX, u1gu2q, u1, u2q, u2, pkcInfo->bnCTX ) );
475  if( bnStatusError( bnStatus ) )
476  {
477  EC_POINT_free( u2q );
478  return( getBnStatus( bnStatus ) );
479  }
480 
481  /* Convert point (x1, y1) to an integer r':
482 
483  r' = p((x1, y1)) mod n
484  = x1 mod n */
485  CK( EC_POINT_get_affine_coordinates_GFp( ecCTX, u1gu2q, u1, u2,
486  pkcInfo->bnCTX ) );
487  CK( BN_mod( u1, u1, n, pkcInfo->bnCTX ) );
488  if( bnStatusError( bnStatus ) )
489  {
490  EC_POINT_free( u2q );
491  return( getBnStatus( bnStatus ) );
492  }
493 
494  /* Clean up */
495  EC_POINT_free( u2q );
496 
497  /* If r == r' then the signature is good */
498  if( BN_cmp( r, u1 ) )
499  return( CRYPT_ERROR_SIGNATURE );
500 
501  /* Perform side-channel attack checks if necessary */
502  if( ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) && \
503  cryptStatusError( calculateBignumChecksum( pkcInfo,
504  CRYPT_ALGO_ECDSA ) ) )
505  {
506  return( CRYPT_ERROR_FAILED );
507  }
508  return( status );
509  }
510 
511 /****************************************************************************
512 * *
513 * Key Management *
514 * *
515 ****************************************************************************/
516 
517 /* Load key components into an encryption context */
518 
520 static int initKey( INOUT CONTEXT_INFO *contextInfoPtr,
521  IN_BUFFER_OPT( keyLength ) const void *key,
522  IN_LENGTH_SHORT_OPT const int keyLength )
523  {
524  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
525  assert( ( key == NULL && keyLength == 0 ) || \
526  ( isReadPtr( key, keyLength ) && \
527  keyLength == sizeof( CRYPT_PKCINFO_ECC ) ) );
528 
529  REQUIRES( ( key == NULL && keyLength == 0 ) || \
530  ( key != NULL && keyLength == sizeof( CRYPT_PKCINFO_ECC ) ) );
531 
532 #ifndef USE_FIPS140
533  /* Load the key component from the external representation into the
534  internal bignums unless we're doing an internal load */
535  if( key != NULL )
536  {
537  PKC_INFO *pkcInfo = contextInfoPtr->ctxPKC;
538  const CRYPT_PKCINFO_ECC *eccKey = ( CRYPT_PKCINFO_ECC * ) key;
539  int status;
540 
541  contextInfoPtr->flags |= ( eccKey->isPublicKey ) ? \
543  if( eccKey->curveType == CRYPT_ECCCURVE_NONE )
544  {
545  status = importBignum( &pkcInfo->eccParam_p, eccKey->p,
546  bitsToBytes( eccKey->pLen ),
548  NULL, KEYSIZE_CHECK_ECC );
549  if( cryptStatusOK( status ) )
550  status = importBignum( &pkcInfo->eccParam_a, eccKey->a,
551  bitsToBytes( eccKey->aLen ),
553  NULL, KEYSIZE_CHECK_NONE );
554  if( cryptStatusOK( status ) )
555  status = importBignum( &pkcInfo->eccParam_b, eccKey->b,
556  bitsToBytes( eccKey->bLen ),
558  NULL, KEYSIZE_CHECK_NONE );
559  if( cryptStatusOK( status ) )
560  status = importBignum( &pkcInfo->eccParam_gx, eccKey->gx,
561  bitsToBytes( eccKey->gxLen ),
563  NULL, KEYSIZE_CHECK_NONE );
564  if( cryptStatusOK( status ) )
565  status = importBignum( &pkcInfo->eccParam_gy, eccKey->gy,
566  bitsToBytes( eccKey->gyLen ),
568  NULL, KEYSIZE_CHECK_NONE );
569  if( cryptStatusOK( status ) )
570  status = importBignum( &pkcInfo->eccParam_n, eccKey->n,
571  bitsToBytes( eccKey->nLen ),
573  NULL, KEYSIZE_CHECK_NONE );
574  if( cryptStatusError( status ) )
575  return( status );
576  }
577  else
578  {
579  if( eccKey->curveType <= CRYPT_ECCCURVE_NONE || \
580  eccKey->curveType >= CRYPT_ECCCURVE_LAST )
581  return( CRYPT_ARGERROR_STR1 );
582  pkcInfo->curveType = eccKey->curveType;
583  }
584  status = importBignum( &pkcInfo->eccParam_qx, eccKey->qx,
585  bitsToBytes( eccKey->qxLen ),
587  NULL, KEYSIZE_CHECK_NONE );
588  if( cryptStatusOK( status ) )
589  status = importBignum( &pkcInfo->eccParam_qy, eccKey->qy,
590  bitsToBytes( eccKey->qyLen ),
592  NULL, KEYSIZE_CHECK_NONE );
593  if( cryptStatusOK( status ) && !eccKey->isPublicKey )
594  status = importBignum( &pkcInfo->eccParam_d, eccKey->d,
595  bitsToBytes( eccKey->dLen ),
597  NULL, KEYSIZE_CHECK_NONE );
598  contextInfoPtr->flags |= CONTEXT_FLAG_PBO;
599  if( cryptStatusError( status ) )
600  return( status );
601  }
602 #endif /* USE_FIPS140 */
603 
604  /* Complete the key checking and setup */
605  return( initCheckECCkey( contextInfoPtr, FALSE ) );
606  }
607 
608 /* Generate a key into an encryption context */
609 
611 static int generateKey( INOUT CONTEXT_INFO *contextInfoPtr,
613  const int keySizeBits )
614  {
615  int status;
616 
617  assert( isWritePtr( contextInfoPtr, sizeof( CONTEXT_INFO ) ) );
618 
619  REQUIRES( keySizeBits >= bytesToBits( MIN_PKCSIZE_ECC ) && \
620  keySizeBits <= bytesToBits( CRYPT_MAX_PKCSIZE_ECC ) );
621 
622  status = generateECCkey( contextInfoPtr, keySizeBits );
623  if( cryptStatusOK( status ) &&
624 #ifndef USE_FIPS140
625  ( contextInfoPtr->flags & CONTEXT_FLAG_SIDECHANNELPROTECTION ) &&
626 #endif /* USE_FIPS140 */
627  !pairwiseConsistencyTest( contextInfoPtr ) )
628  {
629  DEBUG_DIAG(( "Consistency check of freshly-generated ECDSA key "
630  "failed" ));
631  assert( DEBUG_WARN );
632  status = CRYPT_ERROR_FAILED;
633  }
634  return( status );
635  }
636 
637 /****************************************************************************
638 * *
639 * Capability Access Routines *
640 * *
641 ****************************************************************************/
642 
643 static const CAPABILITY_INFO FAR_BSS capabilityInfo = {
644  CRYPT_ALGO_ECDSA, bitsToBytes( 0 ), "ECDSA", 5,
646  selfTest, getDefaultInfo, NULL, NULL, initKey, generateKey,
647  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
648  sign, sigCheck
649  };
650 
651 const CAPABILITY_INFO *getECDSACapability( void )
652  {
653  return( &capabilityInfo );
654  }
655 #endif /* USE_ECDSA */