APPS: Fix 'openssl dsaparam -genkey'
[openssl.git] / apps / dsaparam.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #include <openssl/opensslconf.h>
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <time.h>
15 #include <string.h>
16 #include "apps.h"
17 #include "progs.h"
18 #include <openssl/bio.h>
19 #include <openssl/err.h>
20 #include <openssl/bn.h>
21 #include <openssl/dsa.h>
22 #include <openssl/x509.h>
23 #include <openssl/pem.h>
24
25 static int verbose = 0;
26
27 static int gendsa_cb(EVP_PKEY_CTX *ctx);
28
29 typedef enum OPTION_choice {
30     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
31     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C,
32     OPT_NOOUT, OPT_GENKEY, OPT_ENGINE, OPT_VERBOSE,
33     OPT_R_ENUM, OPT_PROV_ENUM
34 } OPTION_CHOICE;
35
36 const OPTIONS dsaparam_options[] = {
37     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"},
38
39     OPT_SECTION("General"),
40     {"help", OPT_HELP, '-', "Display this summary"},
41 #ifndef OPENSSL_NO_ENGINE
42     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
43 #endif
44
45     OPT_SECTION("Input"),
46     {"in", OPT_IN, '<', "Input file"},
47     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
48
49     OPT_SECTION("Output"),
50     {"out", OPT_OUT, '>', "Output file"},
51     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
52     {"text", OPT_TEXT, '-', "Print as text"},
53     {"C", OPT_C, '-', "Output C code"},
54     {"noout", OPT_NOOUT, '-', "No output"},
55     {"verbose", OPT_VERBOSE, '-', "Verbose output"},
56     {"genkey", OPT_GENKEY, '-', "Generate a DSA key"},
57
58     OPT_R_OPTIONS,
59     OPT_PROV_OPTIONS,
60
61     OPT_PARAMETERS(),
62     {"numbits", 0, 0, "Number of bits if generating parameters (optional)"},
63     {NULL}
64 };
65
66 int dsaparam_main(int argc, char **argv)
67 {
68     ENGINE *e = NULL;
69     BIO *in = NULL, *out = NULL;
70     EVP_PKEY *params = NULL, *pkey = NULL;
71     EVP_PKEY_CTX *ctx = NULL;
72     int numbits = -1, num = 0, genkey = 0;
73     int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0;
74     int ret = 1, i, text = 0, private = 0;
75     char *infile = NULL, *outfile = NULL, *prog;
76     OPTION_CHOICE o;
77
78     prog = opt_init(argc, argv, dsaparam_options);
79     while ((o = opt_next()) != OPT_EOF) {
80         switch (o) {
81         case OPT_EOF:
82         case OPT_ERR:
83  opthelp:
84             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
85             goto end;
86         case OPT_HELP:
87             opt_help(dsaparam_options);
88             ret = 0;
89             goto end;
90         case OPT_INFORM:
91             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
92                 goto opthelp;
93             break;
94         case OPT_IN:
95             infile = opt_arg();
96             break;
97         case OPT_OUTFORM:
98             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
99                 goto opthelp;
100             break;
101         case OPT_OUT:
102             outfile = opt_arg();
103             break;
104         case OPT_ENGINE:
105             e = setup_engine(opt_arg(), 0);
106             break;
107         case OPT_TEXT:
108             text = 1;
109             break;
110         case OPT_C:
111             C = 1;
112             break;
113         case OPT_GENKEY:
114             genkey = 1;
115             break;
116         case OPT_R_CASES:
117             if (!opt_rand(o))
118                 goto end;
119             break;
120         case OPT_PROV_CASES:
121             if (!opt_provider(o))
122                 goto end;
123             break;
124         case OPT_NOOUT:
125             noout = 1;
126             break;
127         case OPT_VERBOSE:
128             verbose = 1;
129             break;
130         }
131     }
132     argc = opt_num_rest();
133     argv = opt_rest();
134
135     if (argc == 1) {
136         if (!opt_int(argv[0], &num) || num < 0)
137             goto end;
138         /* generate a key */
139         numbits = num;
140     }
141     private = genkey ? 1 : 0;
142
143     in = bio_open_default(infile, 'r', informat);
144     if (in == NULL)
145         goto end;
146     out = bio_open_owner(outfile, outformat, private);
147     if (out == NULL)
148         goto end;
149
150     ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL);
151     if (ctx == NULL) {
152         ERR_print_errors(bio_err);
153         BIO_printf(bio_err,
154                    "Error, DSA parameter generation context allocation failed\n");
155         goto end;
156     }
157     if (numbits > 0) {
158         if (numbits > OPENSSL_DSA_MAX_MODULUS_BITS)
159             BIO_printf(bio_err,
160                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
161                        "         Your key size is %d! Larger key size may behave not as expected.\n",
162                        OPENSSL_DSA_MAX_MODULUS_BITS, numbits);
163
164         EVP_PKEY_CTX_set_cb(ctx, gendsa_cb);
165         EVP_PKEY_CTX_set_app_data(ctx, bio_err);
166         if (verbose) {
167             BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n",
168                        num);
169             BIO_printf(bio_err, "This could take some time\n");
170         }
171         if (EVP_PKEY_paramgen_init(ctx) <= 0) {
172             ERR_print_errors(bio_err);
173             BIO_printf(bio_err,
174                        "Error, DSA key generation paramgen init failed\n");
175             goto end;
176         }
177         if (!EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num)) {
178             ERR_print_errors(bio_err);
179             BIO_printf(bio_err,
180                        "Error, DSA key generation setting bit length failed\n");
181             goto end;
182         }
183         if (EVP_PKEY_paramgen(ctx, &params) <= 0) {
184             ERR_print_errors(bio_err);
185             BIO_printf(bio_err, "Error, DSA key generation failed\n");
186             goto end;
187         }
188     } else if (informat == FORMAT_ASN1) {
189         params = d2i_KeyParams_bio(EVP_PKEY_DSA, NULL, in);
190     } else {
191         params = PEM_read_bio_Parameters(in, NULL);
192     }
193     if (params == NULL) {
194         BIO_printf(bio_err, "unable to load DSA parameters\n");
195         ERR_print_errors(bio_err);
196         goto end;
197     }
198
199     if (text) {
200         EVP_PKEY_print_params(out, params, 0, NULL);
201     }
202
203     if (C) {
204         BIGNUM *p = NULL, *q = NULL, *g = NULL;
205         unsigned char *data;
206         int len, bits_p;
207
208         EVP_PKEY_get_bn_param(params, "p", &p);
209         EVP_PKEY_get_bn_param(params, "q", &q);
210         EVP_PKEY_get_bn_param(params, "g", &g);
211         len = BN_num_bytes(p);
212         bits_p = BN_num_bits(p);
213
214         data = app_malloc(len + 20, "BN space");
215
216         BIO_printf(bio_out, "static DSA *get_dsa%d(void)\n{\n", bits_p);
217         print_bignum_var(bio_out, p, "dsap", bits_p, data);
218         print_bignum_var(bio_out, q, "dsaq", bits_p, data);
219         print_bignum_var(bio_out, g, "dsag", bits_p, data);
220         BIO_printf(bio_out, "    DSA *dsa = DSA_new();\n"
221                             "    BIGNUM *p, *q, *g;\n"
222                             "\n");
223         BIO_printf(bio_out, "    if (dsa == NULL)\n"
224                             "        return NULL;\n");
225         BIO_printf(bio_out, "    if (!DSA_set0_pqg(dsa, p = BN_bin2bn(dsap_%d, sizeof(dsap_%d), NULL),\n",
226                    bits_p, bits_p);
227         BIO_printf(bio_out, "                           q = BN_bin2bn(dsaq_%d, sizeof(dsaq_%d), NULL),\n",
228                    bits_p, bits_p);
229         BIO_printf(bio_out, "                           g = BN_bin2bn(dsag_%d, sizeof(dsag_%d), NULL))) {\n",
230                    bits_p, bits_p);
231         BIO_printf(bio_out, "        DSA_free(dsa);\n"
232                             "        BN_free(p);\n"
233                             "        BN_free(q);\n"
234                             "        BN_free(g);\n"
235                             "        return NULL;\n"
236                             "    }\n"
237                             "    return dsa;\n}\n");
238         OPENSSL_free(data);
239     }
240
241     if (outformat == FORMAT_ASN1 && genkey)
242         noout = 1;
243
244     if (!noout) {
245         if (outformat == FORMAT_ASN1)
246             i = i2d_KeyParams_bio(out, params);
247         else
248             i = PEM_write_bio_Parameters(out, params);
249         if (!i) {
250             BIO_printf(bio_err, "unable to write DSA parameters\n");
251             ERR_print_errors(bio_err);
252             goto end;
253         }
254     }
255     if (genkey) {
256         EVP_PKEY_CTX_free(ctx);
257         ctx = EVP_PKEY_CTX_new(params, NULL);
258         if (ctx == NULL) {
259             ERR_print_errors(bio_err);
260             BIO_printf(bio_err,
261                        "Error, DSA key generation context allocation failed\n");
262             goto end;
263         }
264         if (!EVP_PKEY_keygen_init(ctx)) {
265             BIO_printf(bio_err, "unable to initialise for key generation\n");
266             ERR_print_errors(bio_err);
267             goto end;
268         }
269         if (!EVP_PKEY_keygen(ctx, &pkey)) {
270             BIO_printf(bio_err, "unable to generate key\n");
271             ERR_print_errors(bio_err);
272             goto end;
273         }
274         assert(private);
275         if (outformat == FORMAT_ASN1)
276             i = i2d_PrivateKey_bio(out, pkey);
277         else
278             i = PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, NULL);
279     }
280     ret = 0;
281  end:
282     BIO_free(in);
283     BIO_free_all(out);
284     EVP_PKEY_CTX_free(ctx);
285     EVP_PKEY_free(pkey);
286     EVP_PKEY_free(params);
287     release_engine(e);
288     return ret;
289 }
290
291 static int gendsa_cb(EVP_PKEY_CTX *ctx)
292 {
293     static const char symbols[] = ".+*\n";
294     int p;
295     char c;
296     BIO *b;
297
298     if (!verbose)
299         return 1;
300
301     b = EVP_PKEY_CTX_get_app_data(ctx);
302     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
303     c = (p >= 0 && (size_t)p < sizeof(symbols) - 1) ? symbols[p] : '?';
304
305     BIO_write(b, &c, 1);
306     (void)BIO_flush(b);
307     return 1;
308 }