7d8507ca50d95f07103ef87e6aaad23a4b93212e
[openssl.git] / crypto / ec / ec_key.c
1 /*
2  * Written by Nils Larsch for the OpenSSL project.
3  */
4 /* ====================================================================
5  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    openssl-core@openssl.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This product includes cryptographic software written by Eric Young
53  * (eay@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com).
55  *
56  */
57 /* ====================================================================
58  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
59  * Portions originally developed by SUN MICROSYSTEMS, INC., and
60  * contributed to the OpenSSL project.
61  */
62
63 #include <internal/cryptlib.h>
64 #include <string.h>
65 #include "ec_lcl.h"
66 #include <openssl/err.h>
67 #ifndef OPENSSL_NO_ENGINE
68 # include <openssl/engine.h>
69 #endif
70
71 EC_KEY *EC_KEY_new(void)
72 {
73     return EC_KEY_new_method(NULL);
74 }
75
76 EC_KEY *EC_KEY_new_by_curve_name(int nid)
77 {
78     EC_KEY *ret = EC_KEY_new();
79     if (ret == NULL)
80         return NULL;
81     ret->group = EC_GROUP_new_by_curve_name(nid);
82     if (ret->group == NULL) {
83         EC_KEY_free(ret);
84         return NULL;
85     }
86     if (ret->meth->set_group != NULL
87         && ret->meth->set_group(ret, ret->group) == 0) {
88         EC_KEY_free(ret);
89         return NULL;
90     }
91     return ret;
92 }
93
94 void EC_KEY_free(EC_KEY *r)
95 {
96     int i;
97
98     if (r == NULL)
99         return;
100
101     i = CRYPTO_add(&r->references, -1, CRYPTO_LOCK_EC);
102     REF_PRINT_COUNT("EC_KEY", r);
103     if (i > 0)
104         return;
105     REF_ASSERT_ISNT(i < 0);
106
107     if (r->meth->finish != NULL)
108         r->meth->finish(r);
109
110 #ifndef OPENSSL_NO_ENGINE
111     if (r->engine != NULL)
112         ENGINE_finish(r->engine);
113 #endif
114
115     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EC_KEY, r, &r->ex_data);
116     EC_GROUP_free(r->group);
117     EC_POINT_free(r->pub_key);
118     BN_clear_free(r->priv_key);
119
120     OPENSSL_clear_free((void *)r, sizeof(EC_KEY));
121 }
122
123 EC_KEY *EC_KEY_copy(EC_KEY *dest, EC_KEY *src)
124 {
125     if (dest == NULL || src == NULL) {
126         ECerr(EC_F_EC_KEY_COPY, ERR_R_PASSED_NULL_PARAMETER);
127         return NULL;
128     }
129     if (src->meth != dest->meth) {
130         if (dest->meth->finish != NULL)
131             dest->meth->finish(dest);
132 #ifndef OPENSSL_NO_ENGINE
133         if (dest->engine != NULL && ENGINE_finish(dest->engine) == 0)
134             return 0;
135         dest->engine = NULL;
136 #endif
137     }
138     /* copy the parameters */
139     if (src->group != NULL) {
140         const EC_METHOD *meth = EC_GROUP_method_of(src->group);
141         /* clear the old group */
142         EC_GROUP_free(dest->group);
143         dest->group = EC_GROUP_new(meth);
144         if (dest->group == NULL)
145             return NULL;
146         if (!EC_GROUP_copy(dest->group, src->group))
147             return NULL;
148     }
149     /*  copy the public key */
150     if (src->pub_key != NULL && src->group != NULL) {
151         EC_POINT_free(dest->pub_key);
152         dest->pub_key = EC_POINT_new(src->group);
153         if (dest->pub_key == NULL)
154             return NULL;
155         if (!EC_POINT_copy(dest->pub_key, src->pub_key))
156             return NULL;
157     }
158     /* copy the private key */
159     if (src->priv_key != NULL) {
160         if (dest->priv_key == NULL) {
161             dest->priv_key = BN_new();
162             if (dest->priv_key == NULL)
163                 return NULL;
164         }
165         if (!BN_copy(dest->priv_key, src->priv_key))
166             return NULL;
167     }
168
169     /* copy the rest */
170     dest->enc_flag = src->enc_flag;
171     dest->conv_form = src->conv_form;
172     dest->version = src->version;
173     dest->flags = src->flags;
174     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EC_KEY,
175                             &dest->ex_data, &src->ex_data))
176         return NULL;
177
178     if (src->meth != dest->meth) {
179 #ifndef OPENSSL_NO_ENGINE
180         if (src->engine != NULL && ENGINE_init(src->engine) == 0)
181             return NULL;
182         dest->engine = src->engine;
183 #endif
184         dest->meth = src->meth;
185     }
186
187     if (src->meth->copy != NULL && src->meth->copy(dest, src) == 0)
188         return NULL;
189
190     return dest;
191 }
192
193 EC_KEY *EC_KEY_dup(EC_KEY *ec_key)
194 {
195     EC_KEY *ret = EC_KEY_new_method(ec_key->engine);
196
197     if (ret == NULL)
198         return NULL;
199     if (EC_KEY_copy(ret, ec_key) == NULL) {
200         EC_KEY_free(ret);
201         return NULL;
202     }
203     return ret;
204 }
205
206 int EC_KEY_up_ref(EC_KEY *r)
207 {
208     int i = CRYPTO_add(&r->references, 1, CRYPTO_LOCK_EC);
209
210     REF_PRINT_COUNT("EC_KEY", r);
211     REF_ASSERT_ISNT(i < 2);
212     return ((i > 1) ? 1 : 0);
213 }
214
215 int EC_KEY_generate_key(EC_KEY *eckey)
216 {
217     if (eckey == NULL || eckey->group == NULL) {
218         ECerr(EC_F_EC_KEY_GENERATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
219         return 0;
220     }
221     if (eckey->meth->keygen != NULL)
222         return eckey->meth->keygen(eckey);
223     ECerr(EC_F_EC_KEY_GENERATE_KEY, EC_R_OPERATION_NOT_SUPPORTED);
224     return 0;
225 }
226
227 int ossl_ec_key_gen(EC_KEY *eckey)
228 {
229     int ok = 0;
230     BN_CTX *ctx = NULL;
231     BIGNUM *priv_key = NULL;
232     const BIGNUM *order = NULL;
233     EC_POINT *pub_key = NULL;
234
235     if ((ctx = BN_CTX_new()) == NULL)
236         goto err;
237
238     if (eckey->priv_key == NULL) {
239         priv_key = BN_new();
240         if (priv_key == NULL)
241             goto err;
242     } else
243         priv_key = eckey->priv_key;
244
245     order = EC_GROUP_get0_order(eckey->group);
246     if (order == NULL)
247         goto err;
248
249     do
250         if (!BN_rand_range(priv_key, order))
251             goto err;
252     while (BN_is_zero(priv_key)) ;
253
254     if (eckey->pub_key == NULL) {
255         pub_key = EC_POINT_new(eckey->group);
256         if (pub_key == NULL)
257             goto err;
258     } else
259         pub_key = eckey->pub_key;
260
261     if (!EC_POINT_mul(eckey->group, pub_key, priv_key, NULL, NULL, ctx))
262         goto err;
263
264     eckey->priv_key = priv_key;
265     eckey->pub_key = pub_key;
266
267     ok = 1;
268
269  err:
270     if (eckey->pub_key == NULL)
271         EC_POINT_free(pub_key);
272     if (eckey->priv_key != priv_key)
273         BN_free(priv_key);
274     BN_CTX_free(ctx);
275     return (ok);
276 }
277
278 int EC_KEY_check_key(const EC_KEY *eckey)
279 {
280     int ok = 0;
281     BN_CTX *ctx = NULL;
282     const BIGNUM *order = NULL;
283     EC_POINT *point = NULL;
284
285     if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
286         ECerr(EC_F_EC_KEY_CHECK_KEY, ERR_R_PASSED_NULL_PARAMETER);
287         return 0;
288     }
289
290     if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
291         ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_POINT_AT_INFINITY);
292         goto err;
293     }
294
295     if ((ctx = BN_CTX_new()) == NULL)
296         goto err;
297     if ((point = EC_POINT_new(eckey->group)) == NULL)
298         goto err;
299
300     /* testing whether the pub_key is on the elliptic curve */
301     if (EC_POINT_is_on_curve(eckey->group, eckey->pub_key, ctx) <= 0) {
302         ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_POINT_IS_NOT_ON_CURVE);
303         goto err;
304     }
305     /* testing whether pub_key * order is the point at infinity */
306     order = eckey->group->order;
307     if (BN_is_zero(order)) {
308         ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_INVALID_GROUP_ORDER);
309         goto err;
310     }
311     if (!EC_POINT_mul(eckey->group, point, NULL, eckey->pub_key, order, ctx)) {
312         ECerr(EC_F_EC_KEY_CHECK_KEY, ERR_R_EC_LIB);
313         goto err;
314     }
315     if (!EC_POINT_is_at_infinity(eckey->group, point)) {
316         ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_WRONG_ORDER);
317         goto err;
318     }
319     /*
320      * in case the priv_key is present : check if generator * priv_key ==
321      * pub_key
322      */
323     if (eckey->priv_key != NULL) {
324         if (BN_cmp(eckey->priv_key, order) >= 0) {
325             ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_WRONG_ORDER);
326             goto err;
327         }
328         if (!EC_POINT_mul(eckey->group, point, eckey->priv_key,
329                           NULL, NULL, ctx)) {
330             ECerr(EC_F_EC_KEY_CHECK_KEY, ERR_R_EC_LIB);
331             goto err;
332         }
333         if (EC_POINT_cmp(eckey->group, point, eckey->pub_key, ctx) != 0) {
334             ECerr(EC_F_EC_KEY_CHECK_KEY, EC_R_INVALID_PRIVATE_KEY);
335             goto err;
336         }
337     }
338     ok = 1;
339  err:
340     BN_CTX_free(ctx);
341     EC_POINT_free(point);
342     return (ok);
343 }
344
345 int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x,
346                                              BIGNUM *y)
347 {
348     BN_CTX *ctx = NULL;
349     BIGNUM *tx, *ty;
350     EC_POINT *point = NULL;
351     int ok = 0;
352 #ifndef OPENSSL_NO_EC2M
353     int tmp_nid, is_char_two = 0;
354 #endif
355
356     if (key == NULL || key->group == NULL || x == NULL || y == NULL) {
357         ECerr(EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES,
358               ERR_R_PASSED_NULL_PARAMETER);
359         return 0;
360     }
361     ctx = BN_CTX_new();
362     if (ctx == NULL)
363         goto err;
364
365     point = EC_POINT_new(key->group);
366
367     if (point == NULL)
368         goto err;
369
370     tx = BN_CTX_get(ctx);
371     ty = BN_CTX_get(ctx);
372     if (ty == NULL)
373         goto err;
374
375 #ifndef OPENSSL_NO_EC2M
376     tmp_nid = EC_METHOD_get_field_type(EC_GROUP_method_of(key->group));
377
378     if (tmp_nid == NID_X9_62_characteristic_two_field)
379         is_char_two = 1;
380
381     if (is_char_two) {
382         if (!EC_POINT_set_affine_coordinates_GF2m(key->group, point,
383                                                   x, y, ctx))
384             goto err;
385         if (!EC_POINT_get_affine_coordinates_GF2m(key->group, point,
386                                                   tx, ty, ctx))
387             goto err;
388     } else
389 #endif
390     {
391         if (!EC_POINT_set_affine_coordinates_GFp(key->group, point,
392                                                  x, y, ctx))
393             goto err;
394         if (!EC_POINT_get_affine_coordinates_GFp(key->group, point,
395                                                  tx, ty, ctx))
396             goto err;
397     }
398     /*
399      * Check if retrieved coordinates match originals and are less than field
400      * order: if not values are out of range.
401      */
402     if (BN_cmp(x, tx) || BN_cmp(y, ty)
403         || (BN_cmp(x, key->group->field) >= 0)
404         || (BN_cmp(y, key->group->field) >= 0)) {
405         ECerr(EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES,
406               EC_R_COORDINATES_OUT_OF_RANGE);
407         goto err;
408     }
409
410     if (!EC_KEY_set_public_key(key, point))
411         goto err;
412
413     if (EC_KEY_check_key(key) == 0)
414         goto err;
415
416     ok = 1;
417
418  err:
419     BN_CTX_free(ctx);
420     EC_POINT_free(point);
421     return ok;
422
423 }
424
425 const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key)
426 {
427     return key->group;
428 }
429
430 int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group)
431 {
432     if (key->meth->set_group != NULL && key->meth->set_group(key, group) == 0)
433         return 0;
434     EC_GROUP_free(key->group);
435     key->group = EC_GROUP_dup(group);
436     return (key->group == NULL) ? 0 : 1;
437 }
438
439 const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key)
440 {
441     return key->priv_key;
442 }
443
444 int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key)
445 {
446     if (key->meth->set_private != NULL
447         && key->meth->set_private(key, priv_key) == 0)
448         return 0;
449     BN_clear_free(key->priv_key);
450     key->priv_key = BN_dup(priv_key);
451     return (key->priv_key == NULL) ? 0 : 1;
452 }
453
454 const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key)
455 {
456     return key->pub_key;
457 }
458
459 int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key)
460 {
461     if (key->meth->set_public != NULL
462         && key->meth->set_public(key, pub_key) == 0)
463         return 0;
464     EC_POINT_free(key->pub_key);
465     key->pub_key = EC_POINT_dup(pub_key, key->group);
466     return (key->pub_key == NULL) ? 0 : 1;
467 }
468
469 unsigned int EC_KEY_get_enc_flags(const EC_KEY *key)
470 {
471     return key->enc_flag;
472 }
473
474 void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags)
475 {
476     key->enc_flag = flags;
477 }
478
479 point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key)
480 {
481     return key->conv_form;
482 }
483
484 void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform)
485 {
486     key->conv_form = cform;
487     if (key->group != NULL)
488         EC_GROUP_set_point_conversion_form(key->group, cform);
489 }
490
491 void EC_KEY_set_asn1_flag(EC_KEY *key, int flag)
492 {
493     if (key->group != NULL)
494         EC_GROUP_set_asn1_flag(key->group, flag);
495 }
496
497 int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx)
498 {
499     if (key->group == NULL)
500         return 0;
501     return EC_GROUP_precompute_mult(key->group, ctx);
502 }
503
504 int EC_KEY_get_flags(const EC_KEY *key)
505 {
506     return key->flags;
507 }
508
509 void EC_KEY_set_flags(EC_KEY *key, int flags)
510 {
511     key->flags |= flags;
512 }
513
514 void EC_KEY_clear_flags(EC_KEY *key, int flags)
515 {
516     key->flags &= ~flags;
517 }
518
519 size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
520                         unsigned char **pbuf, BN_CTX *ctx)
521 {
522     if (key == NULL || key->pub_key == NULL || key->group == NULL)
523         return 0;
524     return EC_POINT_point2buf(key->group, key->pub_key, form, pbuf, ctx);
525 }
526
527 int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len,
528                    BN_CTX *ctx)
529 {
530     if (key == NULL || key->group == NULL)
531         return 0;
532     if (key->pub_key == NULL)
533         key->pub_key = EC_POINT_new(key->group);
534     if (key->pub_key == NULL)
535         return 0;
536     return EC_POINT_oct2point(key->group, key->pub_key, buf, len, ctx);
537 }
538
539 size_t EC_KEY_priv2oct(const EC_KEY *eckey, unsigned char *buf, size_t len)
540 {
541     size_t buf_len;
542     if (eckey->group == NULL || eckey->group->meth == NULL)
543         return 0;
544
545     buf_len = (EC_GROUP_get_degree(eckey->group) + 7) / 8;
546     if (eckey->priv_key == NULL)
547         return 0;
548     if (buf == NULL)
549         return buf_len;
550     else if (len < buf_len)
551         return 0;
552
553     /* Octetstring may need leading zeros if BN is to short */
554
555     if (BN_bn2binpad(eckey->priv_key, buf, buf_len) == -1) {
556         ECerr(EC_F_EC_KEY_PRIV2OCT, EC_R_BUFFER_TOO_SMALL);
557         return 0;
558     }
559
560     return buf_len;
561 }
562
563 int EC_KEY_oct2priv(EC_KEY *eckey, unsigned char *buf, size_t len)
564 {
565     if (eckey->group == NULL || eckey->group->meth == NULL)
566         return 0;
567
568     if (eckey->priv_key == NULL)
569         eckey->priv_key = BN_secure_new();
570     if (eckey->priv_key == NULL) {
571         ECerr(EC_F_EC_KEY_OCT2PRIV, ERR_R_MALLOC_FAILURE);
572         return 0;
573     }
574     eckey->priv_key = BN_bin2bn(buf, len, eckey->priv_key);
575     if (eckey->priv_key == NULL) {
576         ECerr(EC_F_EC_KEY_OCT2PRIV, ERR_R_BN_LIB);
577         return 0;
578     }
579     return 1;
580 }
581
582 size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf)
583 {
584     size_t len;
585     unsigned char *buf;
586     len = EC_KEY_priv2oct(eckey, NULL, 0);
587     if (len == 0)
588         return 0;
589     buf = OPENSSL_malloc(len);
590     if (buf == NULL)
591         return 0;
592     len = EC_KEY_priv2oct(eckey, buf, len);
593     if (len == 0) {
594         OPENSSL_free(buf);
595         return 0;
596     }
597     *pbuf = buf;
598     return len;
599 }