3f284125a2be5b2e52df9f6475a89f42376e116c
[openssl.git] / crypto / ecdsa / ecdsatest.c
1 /* crypto/ecdsa/ecdsatest.c */
2 /*
3  * Written by Nils Larsch for the OpenSSL project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2000-2002 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 /* ====================================================================
59  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
60  *
61  * Portions of the attached software ("Contribution") are developed by 
62  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
63  *
64  * The Contribution is licensed pursuant to the OpenSSL open source
65  * license provided above.
66  *
67  * The elliptic curve binary polynomial software is originally written by 
68  * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
69  *
70  */
71
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75
76 #ifdef OPENSSL_NO_ECDSA
77 int main(int argc, char * argv[])
78         {
79         puts("Elliptic curves are disabled.");
80         return 0;
81         }
82 #else
83
84 #include <openssl/crypto.h>
85 #include <openssl/bio.h>
86 #include <openssl/evp.h>
87 #include <openssl/ecdsa.h>
88 #include <openssl/engine.h>
89 #include <openssl/err.h>
90
91 static const char rnd_seed[] = "string to make the random number generator "
92         "think it has entropy";
93
94 /* declaration of the test functions */
95 int x9_62_tests(BIO *);
96 int x9_62_test_internal(BIO *out, int nid, const char *r, const char *s);
97 int test_builtin(BIO *);
98
99 /* functions to change the RAND_METHOD */
100 int change_rand(void);
101 int restore_rand(void);
102 int fbytes(unsigned char *buf, int num);
103
104 RAND_METHOD     fake_rand;
105 const RAND_METHOD *old_rand;
106
107 int change_rand(void)
108         {
109         /* save old rand method */
110         if ((old_rand = RAND_get_rand_method()) == NULL)
111                 return 0;
112
113         fake_rand.seed    = old_rand->seed;
114         fake_rand.cleanup = old_rand->cleanup;
115         fake_rand.add     = old_rand->add;
116         fake_rand.status  = old_rand->status;
117         /* use own random function */
118         fake_rand.bytes      = fbytes;
119         fake_rand.pseudorand = fbytes;
120         /* set new RAND_METHOD */
121         if (!RAND_set_rand_method(&fake_rand))
122                 return 0;
123         return 1;
124         }
125
126 int restore_rand(void)
127         {
128         if (!RAND_set_rand_method(old_rand))
129                 return 0;
130         else
131                 return 1;
132         }
133
134 static int fbytes_counter = 0;
135 static const char *numbers[8] = {
136         "651056770906015076056810763456358567190100156695615665659",
137         "6140507067065001063065065565667405560006161556565665656654",
138         "8763001015071075675010661307616710783570106710677817767166"
139         "71676178726717",
140         "7000000175690566466555057817571571075705015757757057795755"
141         "55657156756655",
142         "1275552191113212300012030439187146164646146646466749494799",
143         "1542725565216523985789236956265265265235675811949404040041",
144         "1456427555219115346513212300075341203043918714616464614664"
145         "64667494947990",
146         "1712787255652165239672857892369562652652652356758119494040"
147         "40041670216363"};
148
149 int fbytes(unsigned char *buf, int num)
150         {
151         int     ret;
152         BIGNUM  *tmp = NULL;
153
154         if (fbytes_counter >= 8)
155                 return 0;
156         tmp = BN_new();
157         if (!tmp)
158                 return 0;
159         if (!BN_dec2bn(&tmp, numbers[fbytes_counter]))
160                 {
161                 BN_free(tmp);
162                 return 0;
163                 }
164         fbytes_counter ++;
165         ret = BN_bn2bin(tmp, buf);      
166         if (ret == 0 || ret != num)
167                 ret = 0;
168         else
169                 ret = 1;
170         if (tmp)
171                 BN_free(tmp);
172         return ret;
173         }
174
175 /* some tests from the X9.62 draft */
176 int x9_62_test_internal(BIO *out, int nid, const char *r_in, const char *s_in)
177         {
178         int     ret = 0;
179         const char message[] = "abc";
180         unsigned char digest[20];
181         unsigned int  dgst_len = 0;
182         EVP_MD_CTX md_ctx;
183         EC_KEY    *key = NULL;
184         ECDSA_SIG *signature = NULL;
185         BIGNUM    *r = NULL, *s = NULL;
186
187         EVP_MD_CTX_init(&md_ctx);
188         /* get the message digest */
189         EVP_DigestInit(&md_ctx, EVP_ecdsa());
190         EVP_DigestUpdate(&md_ctx, (const void*)message, 3);
191         EVP_DigestFinal(&md_ctx, digest, &dgst_len);
192
193         BIO_printf(out, "testing %s: ", OBJ_nid2sn(nid));
194         /* create the key */
195         if ((key = EC_KEY_new()) == NULL)
196                 goto x962_int_err;
197         if ((key->group = EC_GROUP_new_by_nid(nid)) == NULL)
198                 goto x962_int_err;
199         if (!EC_KEY_generate_key(key))
200                 goto x962_int_err;
201         BIO_printf(out, ".");
202         BIO_flush(out);
203         /* create the signature */
204         signature = ECDSA_do_sign(digest, 20, key);
205         if (signature == NULL)
206                 goto x962_int_err;
207         BIO_printf(out, ".");
208         BIO_flush(out);
209         /* compare the created signature with the expected signature */
210         if ((r = BN_new()) == NULL || (s = BN_new()) == NULL)
211                 goto x962_int_err;
212         if (!BN_dec2bn(&r, r_in) ||
213             !BN_dec2bn(&s, s_in))
214                 goto x962_int_err;
215         if (BN_cmp(signature->r ,r) || BN_cmp(signature->s, s))
216                 goto x962_int_err;
217         BIO_printf(out, ".");
218         BIO_flush(out);
219         /* verify the signature */
220         if (ECDSA_do_verify(digest, 20, signature, key) != 1)
221                 goto x962_int_err;
222         BIO_printf(out, ".");
223         BIO_flush(out);
224
225         BIO_printf(out, " ok\n");
226         ret = 1;
227 x962_int_err:
228         if (!ret)
229                 BIO_printf(out, " failed\n");
230         if (key)
231                 EC_KEY_free(key);
232         if (signature)
233                 ECDSA_SIG_free(signature);
234         if (r)
235                 BN_free(r);
236         if (s)
237                 BN_free(s);
238         EVP_MD_CTX_cleanup(&md_ctx);
239         return ret;
240         }
241
242 int x9_62_tests(BIO *out)
243         {
244         int ret = 0;
245
246         BIO_printf(out, "some tests from X9.62:\n");
247
248         /* set own rand method */
249         if (!change_rand())
250                 goto x962_err;
251
252         if (!x9_62_test_internal(out, NID_X9_62_prime192v1,
253                 "3342403536405981729393488334694600415596881826869351677613",
254                 "5735822328888155254683894997897571951568553642892029982342"))
255                 goto x962_err;
256         if (!x9_62_test_internal(out, NID_X9_62_prime239v1,
257                 "3086361431751678114926225473006680188549593787585317781474"
258                 "62058306432176",
259                 "3238135532097973577080787768312505059318910517550078427819"
260                 "78505179448783"))
261                 goto x962_err;
262         if (!x9_62_test_internal(out, NID_X9_62_c2tnb191v1,
263                 "87194383164871543355722284926904419997237591535066528048",
264                 "308992691965804947361541664549085895292153777025772063598"))
265                 goto x962_err;
266         if (!x9_62_test_internal(out, NID_X9_62_c2tnb239v1,
267                 "2159633321041961198501834003903461262881815148684178964245"
268                 "5876922391552",
269                 "1970303740007316867383349976549972270528498040721988191026"
270                 "49413465737174"))
271                 goto x962_err;
272
273         ret = 1;
274 x962_err:
275         if (!restore_rand())
276                 ret = 0;
277         return ret;
278         }
279
280 int test_builtin(BIO *out)
281         {
282         EC_builtin_curve *curves = NULL;
283         size_t          crv_len = 0, n = 0;
284         EC_KEY          *eckey = NULL, *wrong_eckey = NULL;
285         unsigned char   digest[20], wrong_digest[20];
286         unsigned char   *signature; 
287         unsigned int    sig_len;
288         int             nid, ret =  0;
289         
290         /* fill digest values with some random data */
291         if (!RAND_pseudo_bytes(digest, 20) ||
292             !RAND_pseudo_bytes(wrong_digest, 20))
293                 {
294                 BIO_printf(out, "ERROR: unable to get random data\n");
295                 goto builtin_err;
296                 }
297
298         /* create and verify a ecdsa signature with every availble curve
299          * (with ) */
300         BIO_printf(out, "\ntesting ECDSA_sign() and ECDSA_verify() "
301                 "with some internal curves:\n");
302
303         /* get a list of all internal curves */
304         crv_len = EC_get_builtin_curves(NULL, 0);
305
306         curves = OPENSSL_malloc(sizeof(EC_builtin_curve) * crv_len);
307
308         if (curves == NULL)
309                 {
310                 BIO_printf(out, "malloc error\n");
311                 goto builtin_err;
312                 }
313         
314         if (!EC_get_builtin_curves(curves, crv_len))
315                 {
316                 BIO_printf(out, "unable to get internal curves\n");
317                 goto builtin_err;
318                 }
319
320         /* now create and verify a signature for every curve */
321         for (n = 0; n < crv_len; n++)
322                 {
323                 nid = curves[n].nid;
324                 /* create new ecdsa key (== EC_KEY) */
325                 if ((eckey = EC_KEY_new()) == NULL)
326                         goto builtin_err;
327                 if ((eckey->group = EC_GROUP_new_by_nid(nid)) == NULL)
328                         goto builtin_err;
329                 if (EC_GROUP_get_degree(eckey->group) < 160)
330                         /* drop the curve */ 
331                         {
332                         EC_KEY_free(eckey);
333                         eckey = NULL;
334                         continue;
335                         }
336                 BIO_printf(out, "%s: ", OBJ_nid2sn(nid));
337                 /* create key */
338                 if (!EC_KEY_generate_key(eckey))
339                         {
340                         BIO_printf(out, " failed\n");
341                         goto builtin_err;
342                         }
343                 /* create second key */
344                 if ((wrong_eckey = EC_KEY_new()) == NULL)
345                         goto builtin_err;
346                 if ((wrong_eckey->group = EC_GROUP_new_by_nid(nid)) == NULL)
347                         goto builtin_err;
348                 if (!EC_KEY_generate_key(wrong_eckey))
349                         {
350                         BIO_printf(out, " failed\n");
351                         goto builtin_err;
352                         }
353
354                 BIO_printf(out, ".");
355                 BIO_flush(out);
356                 /* check key */
357                 if (!EC_KEY_check_key(eckey))
358                         {
359                         BIO_printf(out, " failed\n");
360                         goto builtin_err;
361                         }
362                 BIO_printf(out, ".");
363                 BIO_flush(out);
364                 /* create signature */
365                 sig_len = ECDSA_size(eckey);
366                 if ((signature = OPENSSL_malloc(sig_len)) == NULL)
367                         goto builtin_err;
368                 if (!ECDSA_sign(0, digest, 20, signature, &sig_len, eckey))
369                         {
370                         BIO_printf(out, " failed\n");
371                         goto builtin_err;
372                         }
373                 BIO_printf(out, ".");
374                 BIO_flush(out);
375                 /* verify signature */
376                 if (ECDSA_verify(0, digest, 20, signature, sig_len, eckey) != 1)
377                         {
378                         BIO_printf(out, " failed\n");
379                         goto builtin_err;
380                         }
381                 BIO_printf(out, ".");
382                 BIO_flush(out);
383                 /* verify signature with the wrong key */
384                 if (ECDSA_verify(0, digest, 20, signature, sig_len, 
385                         wrong_eckey) == 1)
386                         {
387                         BIO_printf(out, " failed\n");
388                         goto builtin_err;
389                         }
390                 BIO_printf(out, ".");
391                 BIO_flush(out);
392                 /* wrong digest */
393                 if (ECDSA_verify(0, wrong_digest, 20, signature, sig_len,
394                         eckey) == 1)
395                         {
396                         BIO_printf(out, " failed\n");
397                         goto builtin_err;
398                         }
399                 BIO_printf(out, ".");
400                 BIO_flush(out);
401                 /* modify signature */
402                 signature[((int)signature[0])%sig_len] ^= 
403                         signature[((int)signature[1])%sig_len];
404                 if (ECDSA_verify(0, digest, 20, signature, sig_len, eckey) == 1)
405                         {
406                         BIO_printf(out, " failed\n");
407                         goto builtin_err;
408                         }
409                 BIO_printf(out, ".");
410                 BIO_flush(out);
411                 
412                 BIO_printf(out, " ok\n");
413                 /* cleanup */
414                 OPENSSL_free(signature);
415                 signature = NULL;
416                 EC_KEY_free(eckey);
417                 eckey = NULL;
418                 EC_KEY_free(wrong_eckey);
419                 wrong_eckey = NULL;
420                 }
421
422         ret = 1;        
423 builtin_err:
424         if (eckey)
425                 EC_KEY_free(eckey);
426         if (wrong_eckey)
427                 EC_KEY_free(wrong_eckey);
428         if (signature);
429                 OPENSSL_free(signature);
430         if (curves)
431                 OPENSSL_free(curves);
432
433         return ret;
434         }
435
436 int main(void)
437         {
438         int     ret = 0;
439         BIO     *out;
440
441         out = BIO_new_fp(stdout, BIO_NOCLOSE);
442         
443         /* enable memory leak checking unless explicitly disabled */
444         if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) && 
445                 (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))))
446                 {
447                 CRYPTO_malloc_debug_init();
448                 CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
449                 }
450         else
451                 {
452                 /* OPENSSL_DEBUG_MEMORY=off */
453                 CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
454                 }
455         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
456
457         ERR_load_crypto_strings();
458
459         /* initialize the prng */
460         RAND_seed(rnd_seed, sizeof(rnd_seed));
461
462         /* the tests */
463         if (!x9_62_tests(out))  goto err;
464         if (!test_builtin(out)) goto err;
465         
466         ret = 1;
467 err:    
468         if (!ret)       
469                 BIO_printf(out, "\nECDSA test failed\n");
470         else 
471                 BIO_printf(out, "\nECDSA test passed\n");
472         if (!ret)
473                 ERR_print_errors(out);
474         CRYPTO_cleanup_all_ex_data();
475         ERR_remove_state(0);
476         ERR_free_strings();
477         CRYPTO_mem_leaks(out);
478         if (out != NULL)
479                 BIO_free(out);
480         return(0);
481         }       
482 #endif