58baff822a1fda1671e4472c6bae77ac754b8d90
[openssl.git] / apps / dhparam.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <openssl/opensslconf.h>
112 #ifdef OPENSSL_NO_DH
113 NON_EMPTY_TRANSLATION_UNIT
114 #else
115
116 # include <stdio.h>
117 # include <stdlib.h>
118 # include <time.h>
119 # include <string.h>
120 # include "apps.h"
121 # include <openssl/bio.h>
122 # include <openssl/err.h>
123 # include <openssl/bn.h>
124 # include <openssl/dh.h>
125 # include <openssl/x509.h>
126 # include <openssl/pem.h>
127
128 # ifndef OPENSSL_NO_DSA
129 #  include <openssl/dsa.h>
130 # endif
131
132 # define DEFBITS 2048
133
134 static int dh_cb(int p, int n, BN_GENCB *cb);
135
136 typedef enum OPTION_choice {
137     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
138     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
139     OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT,
140     OPT_RAND, OPT_DSAPARAM, OPT_C, OPT_2, OPT_5
141 } OPTION_CHOICE;
142
143 OPTIONS dhparam_options[] = {
144     {OPT_HELP_STR, 1, '-', "Usage: %s [flags] [numbits]\n"},
145     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
146     {"help", OPT_HELP, '-', "Display this summary"},
147     {"in", OPT_IN, '<', "Input file"},
148     {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"},
149     {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"},
150     {"out", OPT_OUT, '>', "Output file"},
151     {"check", OPT_CHECK, '-', "Check the DH parameters"},
152     {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"},
153     {"noout", OPT_NOOUT, '-'},
154     {"rand", OPT_RAND, 's',
155      "Load the file(s) into the random number generator"},
156     {"C", OPT_C, '-', "Print C code"},
157     {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"},
158     {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"},
159 # ifndef OPENSSL_NO_DSA
160     {"dsaparam", OPT_DSAPARAM, '-',
161      "Read or generate DSA parameters, convert to DH"},
162 # endif
163 # ifndef OPENSSL_NO_ENGINE
164     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
165 # endif
166     {NULL}
167 };
168
169 int dhparam_main(int argc, char **argv)
170 {
171     BIO *in = NULL, *out = NULL;
172     DH *dh = NULL;
173     char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL;
174 #ifndef OPENSSL_NO_DSA
175     int dsaparam = 0;
176 #endif
177     int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
178     int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
179     OPTION_CHOICE o;
180
181     prog = opt_init(argc, argv, dhparam_options);
182     while ((o = opt_next()) != OPT_EOF) {
183         switch (o) {
184         case OPT_EOF:
185         case OPT_ERR:
186  opthelp:
187             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
188             goto end;
189         case OPT_HELP:
190             opt_help(dhparam_options);
191             ret = 0;
192             goto end;
193         case OPT_INFORM:
194             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
195                 goto opthelp;
196             break;
197         case OPT_OUTFORM:
198             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
199                 goto opthelp;
200             break;
201         case OPT_IN:
202             infile = opt_arg();
203             break;
204         case OPT_OUT:
205             outfile = opt_arg();
206             break;
207         case OPT_ENGINE:
208             (void)setup_engine(opt_arg(), 0);
209             break;
210         case OPT_CHECK:
211             check = 1;
212             break;
213         case OPT_TEXT:
214             text = 1;
215             break;
216         case OPT_DSAPARAM:
217 #ifndef OPENSSL_NO_DSA
218             dsaparam = 1;
219 #endif
220             break;
221         case OPT_C:
222             C = 1;
223             break;
224         case OPT_2:
225             g = 2;
226             break;
227         case OPT_5:
228             g = 5;
229             break;
230         case OPT_NOOUT:
231             noout = 1;
232             break;
233         case OPT_RAND:
234             inrand = opt_arg();
235             break;
236         }
237     }
238     argc = opt_num_rest();
239     argv = opt_rest();
240
241     if (argv[0] && (!opt_int(argv[0], &num) || num <= 0))
242         goto end;
243
244     if (g && !num)
245         num = DEFBITS;
246
247 # ifndef OPENSSL_NO_DSA
248     if (dsaparam && g) {
249         BIO_printf(bio_err,
250                    "generator may not be chosen for DSA parameters\n");
251         goto end;
252     }
253 # endif
254     /* DH parameters */
255     if (num && !g)
256         g = 2;
257
258     if (num) {
259
260         BN_GENCB *cb;
261         cb = BN_GENCB_new();
262         if (cb == NULL) {
263             ERR_print_errors(bio_err);
264             goto end;
265         }
266
267         BN_GENCB_set(cb, dh_cb, bio_err);
268         if (!app_RAND_load_file(NULL, 1) && inrand == NULL) {
269             BIO_printf(bio_err,
270                        "warning, not much extra random data, consider using the -rand option\n");
271         }
272         if (inrand != NULL)
273             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
274                        app_RAND_load_files(inrand));
275
276 # ifndef OPENSSL_NO_DSA
277         if (dsaparam) {
278             DSA *dsa = DSA_new();
279
280             BIO_printf(bio_err,
281                        "Generating DSA parameters, %d bit long prime\n", num);
282             if (dsa == NULL
283                 || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
284                                                cb)) {
285                 DSA_free(dsa);
286                 BN_GENCB_free(cb);
287                 ERR_print_errors(bio_err);
288                 goto end;
289             }
290
291             dh = DSA_dup_DH(dsa);
292             DSA_free(dsa);
293             if (dh == NULL) {
294                 BN_GENCB_free(cb);
295                 ERR_print_errors(bio_err);
296                 goto end;
297             }
298         } else
299 # endif
300         {
301             dh = DH_new();
302             BIO_printf(bio_err,
303                        "Generating DH parameters, %d bit long safe prime, generator %d\n",
304                        num, g);
305             BIO_printf(bio_err, "This is going to take a long time\n");
306             if (dh == NULL || !DH_generate_parameters_ex(dh, num, g, cb)) {
307                 BN_GENCB_free(cb);
308                 ERR_print_errors(bio_err);
309                 goto end;
310             }
311         }
312
313         BN_GENCB_free(cb);
314         app_RAND_write_file(NULL);
315     } else {
316
317         in = bio_open_default(infile, 'r', informat);
318         if (in == NULL)
319             goto end;
320
321 # ifndef OPENSSL_NO_DSA
322         if (dsaparam) {
323             DSA *dsa;
324
325             if (informat == FORMAT_ASN1)
326                 dsa = d2i_DSAparams_bio(in, NULL);
327             else                /* informat == FORMAT_PEM */
328                 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
329
330             if (dsa == NULL) {
331                 BIO_printf(bio_err, "unable to load DSA parameters\n");
332                 ERR_print_errors(bio_err);
333                 goto end;
334             }
335
336             dh = DSA_dup_DH(dsa);
337             DSA_free(dsa);
338             if (dh == NULL) {
339                 ERR_print_errors(bio_err);
340                 goto end;
341             }
342         } else
343 # endif
344         {
345             if (informat == FORMAT_ASN1)
346                 dh = d2i_DHparams_bio(in, NULL);
347             else                /* informat == FORMAT_PEM */
348                 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
349
350             if (dh == NULL) {
351                 BIO_printf(bio_err, "unable to load DH parameters\n");
352                 ERR_print_errors(bio_err);
353                 goto end;
354             }
355         }
356
357         /* dh != NULL */
358     }
359
360     out = bio_open_default(outfile, 'w', outformat);
361     if (out == NULL)
362         goto end;
363
364     if (text) {
365         DHparams_print(out, dh);
366     }
367
368     if (check) {
369         if (!DH_check(dh, &i)) {
370             ERR_print_errors(bio_err);
371             goto end;
372         }
373         if (i & DH_CHECK_P_NOT_PRIME)
374             printf("p value is not prime\n");
375         if (i & DH_CHECK_P_NOT_SAFE_PRIME)
376             printf("p value is not a safe prime\n");
377         if (i & DH_UNABLE_TO_CHECK_GENERATOR)
378             printf("unable to check the generator value\n");
379         if (i & DH_NOT_SUITABLE_GENERATOR)
380             printf("the g value is not a generator\n");
381         if (i == 0)
382             printf("DH parameters appear to be ok.\n");
383     }
384     if (C) {
385         unsigned char *data;
386         int len, bits;
387
388         len = BN_num_bytes(dh->p);
389         bits = BN_num_bits(dh->p);
390         data = app_malloc(len, "print a BN");
391         BIO_printf(out, "#ifndef HEADER_DH_H\n"
392                         "# include <openssl/dh.h>\n"
393                         "#endif\n"
394                         "\n");
395         BIO_printf(out, "DH *get_dh%d()\n{\n", bits);
396         print_bignum_var(out, dh->p, "dhp", bits, data);
397         print_bignum_var(out, dh->g, "dhg", bits, data);
398         BIO_printf(out, "    DH *dh = DN_new();\n"
399                         "\n"
400                         "    if (dh == NULL)\n"
401                         "        return NULL;\n");
402         BIO_printf(out, "    dh->p = BN_bin2bn(dhp_%d, sizeof (dhp_%d), NULL);\n",
403                bits, bits);
404         BIO_printf(out, "    dh->g = BN_bin2bn(dhg_%d, sizeof (dhg_%d), NULL);\n",
405                bits, bits);
406         BIO_printf(out, "    if (!dh->p || !dh->g) {\n"
407                         "        DH_free(dh);\n"
408                         "        return NULL;\n"
409                         "    }\n");
410         if (dh->length)
411             BIO_printf(out,
412                         "    dh->length = %ld;\n", dh->length);
413         BIO_printf(out, "    return dh;\n}\n");
414         OPENSSL_free(data);
415     }
416
417     if (!noout) {
418         if (outformat == FORMAT_ASN1)
419             i = i2d_DHparams_bio(out, dh);
420         else if (dh->q)
421             i = PEM_write_bio_DHxparams(out, dh);
422         else
423             i = PEM_write_bio_DHparams(out, dh);
424         if (!i) {
425             BIO_printf(bio_err, "unable to write DH parameters\n");
426             ERR_print_errors(bio_err);
427             goto end;
428         }
429     }
430     ret = 0;
431  end:
432     BIO_free(in);
433     BIO_free_all(out);
434     DH_free(dh);
435     return (ret);
436 }
437
438 static int dh_cb(int p, int n, BN_GENCB *cb)
439 {
440     char c = '*';
441
442     if (p == 0)
443         c = '.';
444     if (p == 1)
445         c = '+';
446     if (p == 2)
447         c = '*';
448     if (p == 3)
449         c = '\n';
450     BIO_write(BN_GENCB_get_arg(cb), &c, 1);
451     (void)BIO_flush(BN_GENCB_get_arg(cb));
452     return 1;
453 }
454 #endif