pkcs8.c revision 296465
1/* pkcs8.c */
2/*
3 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
4 * 1999-2004.
5 */
6/* ====================================================================
7 * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in
18 *    the documentation and/or other materials provided with the
19 *    distribution.
20 *
21 * 3. All advertising materials mentioning features or use of this
22 *    software must display the following acknowledgment:
23 *    "This product includes software developed by the OpenSSL Project
24 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25 *
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 *    endorse or promote products derived from this software without
28 *    prior written permission. For written permission, please contact
29 *    licensing@OpenSSL.org.
30 *
31 * 5. Products derived from this software may not be called "OpenSSL"
32 *    nor may "OpenSSL" appear in their names without prior written
33 *    permission of the OpenSSL Project.
34 *
35 * 6. Redistributions of any form whatsoever must retain the following
36 *    acknowledgment:
37 *    "This product includes software developed by the OpenSSL Project
38 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
53 *
54 * This product includes cryptographic software written by Eric Young
55 * (eay@cryptsoft.com).  This product includes software written by Tim
56 * Hudson (tjh@cryptsoft.com).
57 *
58 */
59#include <stdio.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#define PROG pkcs8_main
68
69int MAIN(int, char **);
70
71int MAIN(int argc, char **argv)
72{
73    ENGINE *e = NULL;
74    char **args, *infile = NULL, *outfile = NULL;
75    char *passargin = NULL, *passargout = NULL;
76    BIO *in = NULL, *out = NULL;
77    int topk8 = 0;
78    int pbe_nid = -1;
79    const EVP_CIPHER *cipher = NULL;
80    int iter = PKCS12_DEFAULT_ITER;
81    int informat, outformat;
82    int p8_broken = PKCS8_OK;
83    int nocrypt = 0;
84    X509_SIG *p8;
85    PKCS8_PRIV_KEY_INFO *p8inf;
86    EVP_PKEY *pkey = NULL;
87    char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
88    int badarg = 0;
89#ifndef OPENSSL_NO_ENGINE
90    char *engine = NULL;
91#endif
92
93    if (bio_err == NULL)
94        bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
95
96    if (!load_config(bio_err, NULL))
97        goto end;
98
99    informat = FORMAT_PEM;
100    outformat = FORMAT_PEM;
101
102    ERR_load_crypto_strings();
103    OpenSSL_add_all_algorithms();
104    args = argv + 1;
105    while (!badarg && *args && *args[0] == '-') {
106        if (!strcmp(*args, "-v2")) {
107            if (args[1]) {
108                args++;
109                cipher = EVP_get_cipherbyname(*args);
110                if (!cipher) {
111                    BIO_printf(bio_err, "Unknown cipher %s\n", *args);
112                    badarg = 1;
113                }
114            } else
115                badarg = 1;
116        } else if (!strcmp(*args, "-v1")) {
117            if (args[1]) {
118                args++;
119                pbe_nid = OBJ_txt2nid(*args);
120                if (pbe_nid == NID_undef) {
121                    BIO_printf(bio_err, "Unknown PBE algorithm %s\n", *args);
122                    badarg = 1;
123                }
124            } else
125                badarg = 1;
126        } else if (!strcmp(*args, "-inform")) {
127            if (args[1]) {
128                args++;
129                informat = str2fmt(*args);
130            } else
131                badarg = 1;
132        } else if (!strcmp(*args, "-outform")) {
133            if (args[1]) {
134                args++;
135                outformat = str2fmt(*args);
136            } else
137                badarg = 1;
138        } else if (!strcmp(*args, "-topk8"))
139            topk8 = 1;
140        else if (!strcmp(*args, "-noiter"))
141            iter = 1;
142        else if (!strcmp(*args, "-nocrypt"))
143            nocrypt = 1;
144        else if (!strcmp(*args, "-nooct"))
145            p8_broken = PKCS8_NO_OCTET;
146        else if (!strcmp(*args, "-nsdb"))
147            p8_broken = PKCS8_NS_DB;
148        else if (!strcmp(*args, "-embed"))
149            p8_broken = PKCS8_EMBEDDED_PARAM;
150        else if (!strcmp(*args, "-passin")) {
151            if (!args[1])
152                goto bad;
153            passargin = *(++args);
154        } else if (!strcmp(*args, "-passout")) {
155            if (!args[1])
156                goto bad;
157            passargout = *(++args);
158        }
159#ifndef OPENSSL_NO_ENGINE
160        else if (strcmp(*args, "-engine") == 0) {
161            if (!args[1])
162                goto bad;
163            engine = *(++args);
164        }
165#endif
166        else if (!strcmp(*args, "-in")) {
167            if (args[1]) {
168                args++;
169                infile = *args;
170            } else
171                badarg = 1;
172        } else if (!strcmp(*args, "-out")) {
173            if (args[1]) {
174                args++;
175                outfile = *args;
176            } else
177                badarg = 1;
178        } else
179            badarg = 1;
180        args++;
181    }
182
183    if (badarg) {
184 bad:
185        BIO_printf(bio_err, "Usage pkcs8 [options]\n");
186        BIO_printf(bio_err, "where options are\n");
187        BIO_printf(bio_err, "-in file        input file\n");
188        BIO_printf(bio_err, "-inform X       input format (DER or PEM)\n");
189        BIO_printf(bio_err,
190                   "-passin arg     input file pass phrase source\n");
191        BIO_printf(bio_err, "-outform X      output format (DER or PEM)\n");
192        BIO_printf(bio_err, "-out file       output file\n");
193        BIO_printf(bio_err,
194                   "-passout arg    output file pass phrase source\n");
195        BIO_printf(bio_err, "-topk8          output PKCS8 file\n");
196        BIO_printf(bio_err,
197                   "-nooct          use (nonstandard) no octet format\n");
198        BIO_printf(bio_err,
199                   "-embed          use (nonstandard) embedded DSA parameters format\n");
200        BIO_printf(bio_err,
201                   "-nsdb           use (nonstandard) DSA Netscape DB format\n");
202        BIO_printf(bio_err, "-noiter         use 1 as iteration count\n");
203        BIO_printf(bio_err,
204                   "-nocrypt        use or expect unencrypted private key\n");
205        BIO_printf(bio_err,
206                   "-v2 alg         use PKCS#5 v2.0 and cipher \"alg\"\n");
207        BIO_printf(bio_err,
208                   "-v1 obj         use PKCS#5 v1.5 and cipher \"alg\"\n");
209#ifndef OPENSSL_NO_ENGINE
210        BIO_printf(bio_err,
211                   " -engine e       use engine e, possibly a hardware device.\n");
212#endif
213        return 1;
214    }
215#ifndef OPENSSL_NO_ENGINE
216    e = setup_engine(bio_err, engine, 0);
217#endif
218
219    if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
220        BIO_printf(bio_err, "Error getting passwords\n");
221        return 1;
222    }
223
224    if ((pbe_nid == -1) && !cipher)
225        pbe_nid = NID_pbeWithMD5AndDES_CBC;
226
227    if (infile) {
228        if (!(in = BIO_new_file(infile, "rb"))) {
229            BIO_printf(bio_err, "Can't open input file %s\n", infile);
230            return (1);
231        }
232    } else
233        in = BIO_new_fp(stdin, BIO_NOCLOSE);
234
235    if (outfile) {
236        if (!(out = BIO_new_file(outfile, "wb"))) {
237            BIO_printf(bio_err, "Can't open output file %s\n", outfile);
238            return (1);
239        }
240    } else {
241        out = BIO_new_fp(stdout, BIO_NOCLOSE);
242#ifdef OPENSSL_SYS_VMS
243        {
244            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
245            out = BIO_push(tmpbio, out);
246        }
247#endif
248    }
249    if (topk8) {
250        BIO_free(in);           /* Not needed in this section */
251        pkey = load_key(bio_err, infile, informat, 1, passin, e, "key");
252        if (!pkey) {
253            BIO_free_all(out);
254            return 1;
255        }
256        if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
257            BIO_printf(bio_err, "Error converting key\n");
258            ERR_print_errors(bio_err);
259            EVP_PKEY_free(pkey);
260            BIO_free_all(out);
261            return 1;
262        }
263        if (nocrypt) {
264            if (outformat == FORMAT_PEM)
265                PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
266            else if (outformat == FORMAT_ASN1)
267                i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
268            else {
269                BIO_printf(bio_err, "Bad format specified for key\n");
270                PKCS8_PRIV_KEY_INFO_free(p8inf);
271                EVP_PKEY_free(pkey);
272                BIO_free_all(out);
273                return (1);
274            }
275        } else {
276            if (passout)
277                p8pass = passout;
278            else {
279                p8pass = pass;
280                if (EVP_read_pw_string
281                    (pass, sizeof pass, "Enter Encryption Password:", 1)) {
282                    PKCS8_PRIV_KEY_INFO_free(p8inf);
283                    EVP_PKEY_free(pkey);
284                    BIO_free_all(out);
285                    return (1);
286                }
287            }
288            app_RAND_load_file(NULL, bio_err, 0);
289            if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,
290                                     p8pass, strlen(p8pass),
291                                     NULL, 0, iter, p8inf))) {
292                BIO_printf(bio_err, "Error encrypting key\n");
293                ERR_print_errors(bio_err);
294                PKCS8_PRIV_KEY_INFO_free(p8inf);
295                EVP_PKEY_free(pkey);
296                BIO_free_all(out);
297                return (1);
298            }
299            app_RAND_write_file(NULL, bio_err);
300            if (outformat == FORMAT_PEM)
301                PEM_write_bio_PKCS8(out, p8);
302            else if (outformat == FORMAT_ASN1)
303                i2d_PKCS8_bio(out, p8);
304            else {
305                BIO_printf(bio_err, "Bad format specified for key\n");
306                PKCS8_PRIV_KEY_INFO_free(p8inf);
307                EVP_PKEY_free(pkey);
308                BIO_free_all(out);
309                return (1);
310            }
311            X509_SIG_free(p8);
312        }
313
314        PKCS8_PRIV_KEY_INFO_free(p8inf);
315        EVP_PKEY_free(pkey);
316        BIO_free_all(out);
317        if (passin)
318            OPENSSL_free(passin);
319        if (passout)
320            OPENSSL_free(passout);
321        return (0);
322    }
323
324    if (nocrypt) {
325        if (informat == FORMAT_PEM)
326            p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
327        else if (informat == FORMAT_ASN1)
328            p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
329        else {
330            BIO_printf(bio_err, "Bad format specified for key\n");
331            return (1);
332        }
333    } else {
334        if (informat == FORMAT_PEM)
335            p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
336        else if (informat == FORMAT_ASN1)
337            p8 = d2i_PKCS8_bio(in, NULL);
338        else {
339            BIO_printf(bio_err, "Bad format specified for key\n");
340            return (1);
341        }
342
343        if (!p8) {
344            BIO_printf(bio_err, "Error reading key\n");
345            ERR_print_errors(bio_err);
346            return (1);
347        }
348        if (passin)
349            p8pass = passin;
350        else {
351            p8pass = pass;
352            EVP_read_pw_string(pass, sizeof pass, "Enter Password:", 0);
353        }
354        p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
355        X509_SIG_free(p8);
356    }
357
358    if (!p8inf) {
359        BIO_printf(bio_err, "Error decrypting key\n");
360        ERR_print_errors(bio_err);
361        return (1);
362    }
363
364    if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
365        BIO_printf(bio_err, "Error converting key\n");
366        ERR_print_errors(bio_err);
367        return (1);
368    }
369
370    if (p8inf->broken) {
371        BIO_printf(bio_err, "Warning: broken key encoding: ");
372        switch (p8inf->broken) {
373        case PKCS8_NO_OCTET:
374            BIO_printf(bio_err, "No Octet String in PrivateKey\n");
375            break;
376
377        case PKCS8_EMBEDDED_PARAM:
378            BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
379            break;
380
381        case PKCS8_NS_DB:
382            BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
383            break;
384
385        default:
386            BIO_printf(bio_err, "Unknown broken type\n");
387            break;
388        }
389    }
390
391    PKCS8_PRIV_KEY_INFO_free(p8inf);
392    if (outformat == FORMAT_PEM)
393        PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
394    else if (outformat == FORMAT_ASN1)
395        i2d_PrivateKey_bio(out, pkey);
396    else {
397        BIO_printf(bio_err, "Bad format specified for key\n");
398        return (1);
399    }
400
401 end:
402    EVP_PKEY_free(pkey);
403    BIO_free_all(out);
404    BIO_free(in);
405    if (passin)
406        OPENSSL_free(passin);
407    if (passout)
408        OPENSSL_free(passout);
409
410    return (0);
411}
412