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