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