a3696c9d9525ba3159f2d96480e6bc1493b306e4
[openssl.git] / apps / ecparam.c
1 /*
2  * Copyright 2002-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  *
13  * Portions of the attached software ("Contribution") are developed by
14  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
15  *
16  * The Contribution is licensed pursuant to the OpenSSL open source
17  * license provided above.
18  *
19  * The elliptic curve binary polynomial software is originally written by
20  * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
21  *
22  */
23
24 #include <openssl/opensslconf.h>
25 #ifdef OPENSSL_NO_EC
26 NON_EMPTY_TRANSLATION_UNIT
27 #else
28
29 # include <stdio.h>
30 # include <stdlib.h>
31 # include <time.h>
32 # include <string.h>
33 # include "apps.h"
34 # include <openssl/bio.h>
35 # include <openssl/err.h>
36 # include <openssl/bn.h>
37 # include <openssl/ec.h>
38 # include <openssl/x509.h>
39 # include <openssl/pem.h>
40
41 typedef enum OPTION_choice {
42     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
43     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C,
44     OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME,
45     OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_RAND, OPT_ENGINE
46 } OPTION_CHOICE;
47
48 const OPTIONS ecparam_options[] = {
49     {"help", OPT_HELP, '-', "Display this summary"},
50     {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"},
51     {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"},
52     {"in", OPT_IN, '<', "Input file  - default stdin"},
53     {"out", OPT_OUT, '>', "Output file - default stdout"},
54     {"text", OPT_TEXT, '-', "Print the ec parameters in text form"},
55     {"C", OPT_C, '-', "Print a 'C' function creating the parameters"},
56     {"check", OPT_CHECK, '-', "Validate the ec parameters"},
57     {"list_curves", OPT_LIST_CURVES, '-',
58      "Prints a list of all curve 'short names'"},
59     {"no_seed", OPT_NO_SEED, '-',
60      "If 'explicit' parameters are chosen do not use the seed"},
61     {"noout", OPT_NOOUT, '-', "Do not print the ec parameter"},
62     {"name", OPT_NAME, 's',
63      "Use the ec parameters with specified 'short name'"},
64     {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "},
65     {"param_enc", OPT_PARAM_ENC, 's',
66      "Specifies the way the ec parameters are encoded"},
67     {"genkey", OPT_GENKEY, '-', "Generate ec key"},
68     {"rand", OPT_RAND, 's', "Files to use for random number input"},
69 # ifndef OPENSSL_NO_ENGINE
70     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
71 # endif
72     {NULL}
73 };
74
75 static OPT_PAIR forms[] = {
76     {"compressed", POINT_CONVERSION_COMPRESSED},
77     {"uncompressed", POINT_CONVERSION_UNCOMPRESSED},
78     {"hybrid", POINT_CONVERSION_HYBRID},
79     {NULL}
80 };
81
82 static OPT_PAIR encodings[] = {
83     {"named_curve", OPENSSL_EC_NAMED_CURVE},
84     {"explicit", 0},
85     {NULL}
86 };
87
88 int ecparam_main(int argc, char **argv)
89 {
90     ENGINE *e = NULL;
91     BIGNUM *ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL;
92     BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL;
93     BIO *in = NULL, *out = NULL;
94     EC_GROUP *group = NULL;
95     point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
96     char *curve_name = NULL, *inrand = NULL;
97     char *infile = NULL, *outfile = NULL, *prog;
98     unsigned char *buffer = NULL;
99     OPTION_CHOICE o;
100     int asn1_flag = OPENSSL_EC_NAMED_CURVE, new_asn1_flag = 0;
101     int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0;
102     int ret = 1, private = 0;
103     int list_curves = 0, no_seed = 0, check = 0, new_form = 0;
104     int text = 0, i, need_rand = 0, genkey = 0;
105
106     prog = opt_init(argc, argv, ecparam_options);
107     while ((o = opt_next()) != OPT_EOF) {
108         switch (o) {
109         case OPT_EOF:
110         case OPT_ERR:
111  opthelp:
112             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
113             goto end;
114         case OPT_HELP:
115             opt_help(ecparam_options);
116             ret = 0;
117             goto end;
118         case OPT_INFORM:
119             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
120                 goto opthelp;
121             break;
122         case OPT_IN:
123             infile = opt_arg();
124             break;
125         case OPT_OUTFORM:
126             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
127                 goto opthelp;
128             break;
129         case OPT_OUT:
130             outfile = opt_arg();
131             break;
132         case OPT_TEXT:
133             text = 1;
134             break;
135         case OPT_C:
136             C = 1;
137             break;
138         case OPT_CHECK:
139             check = 1;
140             break;
141         case OPT_LIST_CURVES:
142             list_curves = 1;
143             break;
144         case OPT_NO_SEED:
145             no_seed = 1;
146             break;
147         case OPT_NOOUT:
148             noout = 1;
149             break;
150         case OPT_NAME:
151             curve_name = opt_arg();
152             break;
153         case OPT_CONV_FORM:
154             if (!opt_pair(opt_arg(), forms, &new_form))
155                 goto opthelp;
156             form = new_form;
157             new_form = 1;
158             break;
159         case OPT_PARAM_ENC:
160             if (!opt_pair(opt_arg(), encodings, &asn1_flag))
161                 goto opthelp;
162             new_asn1_flag = 1;
163             break;
164         case OPT_GENKEY:
165             genkey = need_rand = 1;
166             break;
167         case OPT_RAND:
168             inrand = opt_arg();
169             need_rand = 1;
170             break;
171         case OPT_ENGINE:
172             e = setup_engine(opt_arg(), 0);
173             break;
174         }
175     }
176     argc = opt_num_rest();
177     if (argc != 0)
178         goto opthelp;
179
180     private = genkey ? 1 : 0;
181
182     in = bio_open_default(infile, 'r', informat);
183     if (in == NULL)
184         goto end;
185     out = bio_open_owner(outfile, outformat, private);
186     if (out == NULL)
187         goto end;
188
189     if (list_curves) {
190         EC_builtin_curve *curves = NULL;
191         size_t crv_len = EC_get_builtin_curves(NULL, 0);
192         size_t n;
193
194         curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves");
195         if (!EC_get_builtin_curves(curves, crv_len)) {
196             OPENSSL_free(curves);
197             goto end;
198         }
199
200         for (n = 0; n < crv_len; n++) {
201             const char *comment;
202             const char *sname;
203             comment = curves[n].comment;
204             sname = OBJ_nid2sn(curves[n].nid);
205             if (comment == NULL)
206                 comment = "CURVE DESCRIPTION NOT AVAILABLE";
207             if (sname == NULL)
208                 sname = "";
209
210             BIO_printf(out, "  %-10s: ", sname);
211             BIO_printf(out, "%s\n", comment);
212         }
213
214         OPENSSL_free(curves);
215         ret = 0;
216         goto end;
217     }
218
219     if (curve_name != NULL) {
220         int nid;
221
222         /*
223          * workaround for the SECG curve names secp192r1 and secp256r1 (which
224          * are the same as the curves prime192v1 and prime256v1 defined in
225          * X9.62)
226          */
227         if (strcmp(curve_name, "secp192r1") == 0) {
228             BIO_printf(bio_err, "using curve name prime192v1 "
229                        "instead of secp192r1\n");
230             nid = NID_X9_62_prime192v1;
231         } else if (strcmp(curve_name, "secp256r1") == 0) {
232             BIO_printf(bio_err, "using curve name prime256v1 "
233                        "instead of secp256r1\n");
234             nid = NID_X9_62_prime256v1;
235         } else {
236             nid = OBJ_sn2nid(curve_name);
237         }
238
239         if (nid == 0)
240             nid = EC_curve_nist2nid(curve_name);
241
242         if (nid == 0) {
243             BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name);
244             goto end;
245         }
246
247         group = EC_GROUP_new_by_curve_name(nid);
248         if (group == NULL) {
249             BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name);
250             goto end;
251         }
252         EC_GROUP_set_asn1_flag(group, asn1_flag);
253         EC_GROUP_set_point_conversion_form(group, form);
254     } else if (informat == FORMAT_ASN1) {
255         group = d2i_ECPKParameters_bio(in, NULL);
256     } else {
257         group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL);
258     }
259     if (group == NULL) {
260         BIO_printf(bio_err, "unable to load elliptic curve parameters\n");
261         ERR_print_errors(bio_err);
262         goto end;
263     }
264
265     if (new_form)
266         EC_GROUP_set_point_conversion_form(group, form);
267
268     if (new_asn1_flag)
269         EC_GROUP_set_asn1_flag(group, asn1_flag);
270
271     if (no_seed) {
272         EC_GROUP_set_seed(group, NULL, 0);
273     }
274
275     if (text) {
276         if (!ECPKParameters_print(out, group, 0))
277             goto end;
278     }
279
280     if (check) {
281         BIO_printf(bio_err, "checking elliptic curve parameters: ");
282         if (!EC_GROUP_check(group, NULL)) {
283             BIO_printf(bio_err, "failed\n");
284             ERR_print_errors(bio_err);
285             goto end;
286         }
287         BIO_printf(bio_err, "ok\n");
288
289     }
290
291     if (C) {
292         size_t buf_len = 0, tmp_len = 0;
293         const EC_POINT *point;
294         int is_prime, len = 0;
295         const EC_METHOD *meth = EC_GROUP_method_of(group);
296
297         if ((ec_p = BN_new()) == NULL
298                 || (ec_a = BN_new()) == NULL
299                 || (ec_b = BN_new()) == NULL
300                 || (ec_gen = BN_new()) == NULL
301                 || (ec_order = BN_new()) == NULL
302                 || (ec_cofactor = BN_new()) == NULL) {
303             perror("Can't allocate BN");
304             goto end;
305         }
306
307         is_prime = (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field);
308         if (!is_prime) {
309             BIO_printf(bio_err, "Can only handle X9.62 prime fields\n");
310             goto end;
311         }
312
313         if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a, ec_b, NULL))
314             goto end;
315
316         if ((point = EC_GROUP_get0_generator(group)) == NULL)
317             goto end;
318         if (!EC_POINT_point2bn(group, point,
319                                EC_GROUP_get_point_conversion_form(group),
320                                ec_gen, NULL))
321             goto end;
322         if (!EC_GROUP_get_order(group, ec_order, NULL))
323             goto end;
324         if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
325             goto end;
326
327         if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor)
328             goto end;
329
330         len = BN_num_bits(ec_order);
331
332         if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len)
333             buf_len = tmp_len;
334         if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len)
335             buf_len = tmp_len;
336         if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len)
337             buf_len = tmp_len;
338         if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len)
339             buf_len = tmp_len;
340         if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len)
341             buf_len = tmp_len;
342         if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len)
343             buf_len = tmp_len;
344
345         buffer = app_malloc(buf_len, "BN buffer");
346
347         BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n{\n", len);
348         print_bignum_var(out, ec_p, "ec_p", len, buffer);
349         print_bignum_var(out, ec_a, "ec_a", len, buffer);
350         print_bignum_var(out, ec_b, "ec_b", len, buffer);
351         print_bignum_var(out, ec_gen, "ec_gen", len, buffer);
352         print_bignum_var(out, ec_order, "ec_order", len, buffer);
353         print_bignum_var(out, ec_cofactor, "ec_cofactor", len, buffer);
354         BIO_printf(out, "    int ok = 0;\n"
355                         "    EC_GROUP *group = NULL;\n"
356                         "    EC_POINT *point = NULL;\n"
357                         "    BIGNUM *tmp_1 = NULL;\n"
358                         "    BIGNUM *tmp_2 = NULL;\n"
359                         "    BIGNUM *tmp_3 = NULL;\n"
360                         "\n");
361
362         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_p_%d, sizeof (ec_p_%d), NULL)) == NULL)\n"
363                         "        goto err;\n", len, len);
364         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_a_%d, sizeof (ec_a_%d), NULL)) == NULL)\n"
365                         "        goto err;\n", len, len);
366         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_b_%d, sizeof (ec_b_%d), NULL)) == NULL)\n"
367                         "        goto err;\n", len, len);
368         BIO_printf(out, "    if ((group = EC_GROUP_new_curve_GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)\n"
369                         "        goto err;\n"
370                         "\n");
371         BIO_printf(out, "    /* build generator */\n");
372         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_gen_%d, sizeof (ec_gen_%d), tmp_1)) == NULL)\n"
373                         "        goto err;\n", len, len);
374         BIO_printf(out, "    point = EC_POINT_bn2point(group, tmp_1, NULL, NULL);\n");
375         BIO_printf(out, "    if (point == NULL)\n"
376                         "        goto err;\n");
377         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_order_%d, sizeof (ec_order_%d), tmp_2)) == NULL)\n"
378                         "        goto err;\n", len, len);
379         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_cofactor_%d, sizeof (ec_cofactor_%d), tmp_3)) == NULL)\n"
380                         "        goto err;\n", len, len);
381         BIO_printf(out, "    if (!EC_GROUP_set_generator(group, point, tmp_2, tmp_3))\n"
382                         "        goto err;\n"
383                         "ok = 1;"
384                         "\n");
385         BIO_printf(out, "err:\n"
386                         "    BN_free(tmp_1);\n"
387                         "    BN_free(tmp_2);\n"
388                         "    BN_free(tmp_3);\n"
389                         "    EC_POINT_free(point);\n"
390                         "    if (!ok) {\n"
391                         "        EC_GROUP_free(group);\n"
392                         "        return NULL;\n"
393                         "    }\n"
394                         "    return (group);\n"
395                         "}\n");
396     }
397
398     if (!noout) {
399         if (outformat == FORMAT_ASN1)
400             i = i2d_ECPKParameters_bio(out, group);
401         else
402             i = PEM_write_bio_ECPKParameters(out, group);
403         if (!i) {
404             BIO_printf(bio_err, "unable to write elliptic "
405                        "curve parameters\n");
406             ERR_print_errors(bio_err);
407             goto end;
408         }
409     }
410
411     if (need_rand) {
412         app_RAND_load_file(NULL, (inrand != NULL));
413         if (inrand != NULL)
414             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
415                        app_RAND_load_files(inrand));
416     }
417
418     if (genkey) {
419         EC_KEY *eckey = EC_KEY_new();
420
421         if (eckey == NULL)
422             goto end;
423
424         assert(need_rand);
425
426         if (EC_KEY_set_group(eckey, group) == 0) {
427             BIO_printf(bio_err, "unable to set group when generating key\n");
428             EC_KEY_free(eckey);
429             ERR_print_errors(bio_err);
430             goto end;
431         }
432
433         if (!EC_KEY_generate_key(eckey)) {
434             BIO_printf(bio_err, "unable to generate key\n");
435             EC_KEY_free(eckey);
436             ERR_print_errors(bio_err);
437             goto end;
438         }
439         assert(private);
440         if (outformat == FORMAT_ASN1)
441             i = i2d_ECPrivateKey_bio(out, eckey);
442         else
443             i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
444                                            NULL, 0, NULL, NULL);
445         EC_KEY_free(eckey);
446     }
447
448     if (need_rand)
449         app_RAND_write_file(NULL);
450
451     ret = 0;
452  end:
453     BN_free(ec_p);
454     BN_free(ec_a);
455     BN_free(ec_b);
456     BN_free(ec_gen);
457     BN_free(ec_order);
458     BN_free(ec_cofactor);
459     OPENSSL_free(buffer);
460     EC_GROUP_free(group);
461     release_engine(e);
462     BIO_free(in);
463     BIO_free_all(out);
464     return (ret);
465 }
466
467 #endif