Big apps cleanup (option-parsing, etc)
[openssl.git] / apps / pkcs8.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 1999-2004.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include "apps.h"
62 #include <openssl/pem.h>
63 #include <openssl/err.h>
64 #include <openssl/evp.h>
65 #include <openssl/pkcs12.h>
66
67 typedef enum OPTION_choice {
68     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
69     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
70     OPT_TOPK8, OPT_NOITER, OPT_NOCRYPT, OPT_NOOCT, OPT_NSDB, OPT_EMBED,
71     OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT
72 } OPTION_CHOICE;
73
74 OPTIONS pkcs8_options[] = {
75     {"help", OPT_HELP, '-', "Display this summary"},
76     {"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"},
77     {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"},
78     {"in", OPT_IN, '<', "Input file"},
79     {"out", OPT_OUT, '>', "Output file"},
80     {"topk8", OPT_TOPK8, '-', "Output PKCS8 file"},
81     {"noiter", OPT_NOITER, '-', "Use 1 as iteration count"},
82     {"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"},
83     {"nooct", OPT_NOOCT, '-', "Use (nonstandard) no octet format"},
84     {"nsdb", OPT_NSDB, '-', "Use (nonstandard) DSA Netscape DB format"},
85     {"embed", OPT_EMBED, '-',
86      "Use (nonstandard) embedded DSA parameters format"},
87     {"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"},
88     {"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"},
89     {"v2prf", OPT_V2PRF, 's'},
90     {"iter", OPT_ITER, 'p', "Specify the iteration count"},
91     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
92     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
93 #ifndef OPENSSL_NO_ENGINE
94     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
95 #endif
96     {NULL}
97 };
98
99 int pkcs8_main(int argc, char **argv)
100 {
101     BIO *in = NULL, *out = NULL;
102     ENGINE *e = NULL;
103     EVP_PKEY *pkey = NULL;
104     PKCS8_PRIV_KEY_INFO *p8inf = NULL;
105     X509_SIG *p8 = NULL;
106     const EVP_CIPHER *cipher = NULL;
107     char *engine = NULL, *infile = NULL, *outfile = NULL;
108     char *passinarg = NULL, *passoutarg = NULL, *prog;
109     char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
110     OPTION_CHOICE o;
111     int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER, p8_broken =
112         PKCS8_OK;
113     int informat = FORMAT_PEM, outformat = FORMAT_PEM, topk8 = 0, pbe_nid =
114         -1;
115
116     prog = opt_init(argc, argv, pkcs8_options);
117     while ((o = opt_next()) != OPT_EOF) {
118         switch (o) {
119         case OPT_EOF:
120         case OPT_ERR:
121  opthelp:
122             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
123             goto end;
124         case OPT_HELP:
125             opt_help(pkcs8_options);
126             ret = 0;
127             goto end;
128         case OPT_INFORM:
129             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
130                 goto opthelp;
131             break;
132         case OPT_IN:
133             infile = opt_arg();
134             break;
135         case OPT_OUTFORM:
136             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
137                 goto opthelp;
138             break;
139         case OPT_OUT:
140             outfile = opt_arg();
141             break;
142         case OPT_TOPK8:
143             topk8 = 1;
144             break;
145         case OPT_NOITER:
146             iter = 1;
147             break;
148         case OPT_NOCRYPT:
149             nocrypt = 1;
150             break;
151         case OPT_NOOCT:
152             p8_broken = PKCS8_NO_OCTET;
153             break;
154         case OPT_NSDB:
155             p8_broken = PKCS8_NS_DB;
156             break;
157         case OPT_EMBED:
158             p8_broken = PKCS8_EMBEDDED_PARAM;
159             break;
160         case OPT_V2:
161             if (!opt_cipher(opt_arg(), &cipher))
162                 goto opthelp;
163             break;
164         case OPT_V1:
165             pbe_nid = OBJ_txt2nid(opt_arg());
166             if (pbe_nid == NID_undef) {
167                 BIO_printf(bio_err,
168                            "%s: Unknown PBE algorithm %s\n", prog, opt_arg());
169                 goto opthelp;
170             }
171             break;
172         case OPT_V2PRF:
173             pbe_nid = OBJ_txt2nid(opt_arg());
174             if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
175                 BIO_printf(bio_err,
176                            "%s: Unknown PRF algorithm %s\n", prog, opt_arg());
177                 goto opthelp;
178             }
179             break;
180         case OPT_ITER:
181             if (!opt_int(opt_arg(), &iter))
182                 goto opthelp;
183             break;
184         case OPT_PASSIN:
185             passinarg = opt_arg();
186             break;
187         case OPT_PASSOUT:
188             passoutarg = opt_arg();
189             break;
190         case OPT_ENGINE:
191             engine = opt_arg();
192             break;
193         }
194     }
195     argc = opt_num_rest();
196     argv = opt_rest();
197
198 #ifndef OPENSSL_NO_ENGINE
199     e = setup_engine(engine, 0);
200 #endif
201
202     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
203         BIO_printf(bio_err, "Error getting passwords\n");
204         goto end;
205     }
206
207     if ((pbe_nid == -1) && !cipher)
208         pbe_nid = NID_pbeWithMD5AndDES_CBC;
209
210     in = bio_open_default(infile, "rb");
211     if (in == NULL)
212         goto end;
213     out = bio_open_default(outfile, "wb");
214     if (out == NULL)
215         goto end;
216     if (topk8) {
217         pkey = load_key(infile, informat, 1, passin, e, "key");
218         if (!pkey)
219             goto end;
220         if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
221             BIO_printf(bio_err, "Error converting key\n");
222             ERR_print_errors(bio_err);
223             goto end;
224         }
225         if (nocrypt) {
226             if (outformat == FORMAT_PEM)
227                 PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
228             else if (outformat == FORMAT_ASN1)
229                 i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
230             else {
231                 BIO_printf(bio_err, "Bad format specified for key\n");
232                 goto end;
233             }
234         } else {
235             if (passout)
236                 p8pass = passout;
237             else {
238                 p8pass = pass;
239                 if (EVP_read_pw_string
240                     (pass, sizeof pass, "Enter Encryption Password:", 1))
241                     goto end;
242             }
243             app_RAND_load_file(NULL, 0);
244             if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,
245                                      p8pass, strlen(p8pass),
246                                      NULL, 0, iter, p8inf))) {
247                 BIO_printf(bio_err, "Error encrypting key\n");
248                 ERR_print_errors(bio_err);
249                 goto end;
250             }
251             app_RAND_write_file(NULL);
252             if (outformat == FORMAT_PEM)
253                 PEM_write_bio_PKCS8(out, p8);
254             else if (outformat == FORMAT_ASN1)
255                 i2d_PKCS8_bio(out, p8);
256             else {
257                 BIO_printf(bio_err, "Bad format specified for key\n");
258                 goto end;
259             }
260         }
261
262         ret = 0;
263         goto end;
264     }
265
266     if (nocrypt) {
267         if (informat == FORMAT_PEM)
268             p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
269         else if (informat == FORMAT_ASN1)
270             p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
271         else {
272             BIO_printf(bio_err, "Bad format specified for key\n");
273             goto end;
274         }
275     } else {
276         if (informat == FORMAT_PEM)
277             p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
278         else if (informat == FORMAT_ASN1)
279             p8 = d2i_PKCS8_bio(in, NULL);
280         else {
281             BIO_printf(bio_err, "Bad format specified for key\n");
282             goto end;
283         }
284
285         if (!p8) {
286             BIO_printf(bio_err, "Error reading key\n");
287             ERR_print_errors(bio_err);
288             goto end;
289         }
290         if (passin)
291             p8pass = passin;
292         else {
293             p8pass = pass;
294             EVP_read_pw_string(pass, sizeof pass, "Enter Password:", 0);
295         }
296         p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
297     }
298
299     if (!p8inf) {
300         BIO_printf(bio_err, "Error decrypting key\n");
301         ERR_print_errors(bio_err);
302         goto end;
303     }
304
305     if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
306         BIO_printf(bio_err, "Error converting key\n");
307         ERR_print_errors(bio_err);
308         goto end;
309     }
310
311     if (p8inf->broken) {
312         BIO_printf(bio_err, "Warning: broken key encoding: ");
313         switch (p8inf->broken) {
314         case PKCS8_NO_OCTET:
315             BIO_printf(bio_err, "No Octet String in PrivateKey\n");
316             break;
317
318         case PKCS8_EMBEDDED_PARAM:
319             BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
320             break;
321
322         case PKCS8_NS_DB:
323             BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
324             break;
325
326         case PKCS8_NEG_PRIVKEY:
327             BIO_printf(bio_err, "DSA private key value is negative\n");
328             break;
329
330         default:
331             BIO_printf(bio_err, "Unknown broken type\n");
332             break;
333         }
334     }
335
336     if (outformat == FORMAT_PEM)
337         PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
338     else if (outformat == FORMAT_ASN1)
339         i2d_PrivateKey_bio(out, pkey);
340     else {
341         BIO_printf(bio_err, "Bad format specified for key\n");
342         goto end;
343     }
344     ret = 0;
345
346  end:
347     X509_SIG_free(p8);
348     PKCS8_PRIV_KEY_INFO_free(p8inf);
349     EVP_PKEY_free(pkey);
350     BIO_free_all(out);
351     BIO_free(in);
352     if (passin)
353         OPENSSL_free(passin);
354     if (passout)
355         OPENSSL_free(passout);
356
357     return ret;
358 }