1251881Speter/* pkcs8.c */
2251881Speter/*
3251881Speter * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
4251881Speter * 1999-2004.
5251881Speter */
6251881Speter/* ====================================================================
7251881Speter * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
8251881Speter *
9251881Speter * Redistribution and use in source and binary forms, with or without
10251881Speter * modification, are permitted provided that the following conditions
11251881Speter * are met:
12251881Speter *
13251881Speter * 1. Redistributions of source code must retain the above copyright
14251881Speter *    notice, this list of conditions and the following disclaimer.
15251881Speter *
16251881Speter * 2. Redistributions in binary form must reproduce the above copyright
17251881Speter *    notice, this list of conditions and the following disclaimer in
18251881Speter *    the documentation and/or other materials provided with the
19251881Speter *    distribution.
20251881Speter *
21251881Speter * 3. All advertising materials mentioning features or use of this
22251881Speter *    software must display the following acknowledgment:
23251881Speter *    "This product includes software developed by the OpenSSL Project
24251881Speter *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25251881Speter *
26251881Speter * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27251881Speter *    endorse or promote products derived from this software without
28251881Speter *    prior written permission. For written permission, please contact
29251881Speter *    licensing@OpenSSL.org.
30289180Speter *
31251881Speter * 5. Products derived from this software may not be called "OpenSSL"
32251881Speter *    nor may "OpenSSL" appear in their names without prior written
33251881Speter *    permission of the OpenSSL Project.
34251881Speter *
35251881Speter * 6. Redistributions of any form whatsoever must retain the following
36251881Speter *    acknowledgment:
37251881Speter *    "This product includes software developed by the OpenSSL Project
38289180Speter *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39289180Speter *
40251881Speter * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41251881Speter * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42251881Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43251881Speter * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44251881Speter * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45251881Speter * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46251881Speter * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47251881Speter * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48251881Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49251881Speter * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50251881Speter * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51251881Speter * OF THE POSSIBILITY OF SUCH DAMAGE.
52251881Speter * ====================================================================
53251881Speter *
54251881Speter * This product includes cryptographic software written by Eric Young
55251881Speter * (eay@cryptsoft.com).  This product includes software written by Tim
56251881Speter * Hudson (tjh@cryptsoft.com).
57251881Speter *
58251881Speter */
59251881Speter#include <stdio.h>
60251881Speter#include <string.h>
61251881Speter#include "apps.h"
62251881Speter#include <openssl/pem.h>
63251881Speter#include <openssl/err.h>
64251881Speter#include <openssl/evp.h>
65251881Speter#include <openssl/pkcs12.h>
66251881Speter
67251881Speter#define PROG pkcs8_main
68251881Speter
69251881Speterint MAIN(int, char **);
70251881Speter
71251881Speterint MAIN(int argc, char **argv)
72251881Speter{
73251881Speter    ENGINE *e = NULL;
74251881Speter    char **args, *infile = NULL, *outfile = NULL;
75251881Speter    char *passargin = NULL, *passargout = NULL;
76251881Speter    BIO *in = NULL, *out = NULL;
77251881Speter    int topk8 = 0;
78251881Speter    int pbe_nid = -1;
79251881Speter    const EVP_CIPHER *cipher = NULL;
80251881Speter    int iter = PKCS12_DEFAULT_ITER;
81251881Speter    int informat, outformat;
82289180Speter    int p8_broken = PKCS8_OK;
83289180Speter    int nocrypt = 0;
84289180Speter    X509_SIG *p8 = NULL;
85289180Speter    PKCS8_PRIV_KEY_INFO *p8inf = NULL;
86289180Speter    EVP_PKEY *pkey = NULL;
87289180Speter    char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
88289180Speter    int badarg = 0;
89289180Speter    int ret = 1;
90289180Speter    char *engine = NULL;
91289180Speter
92289180Speter    if (bio_err == NULL)
93289180Speter        bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
94289180Speter
95289180Speter    if (!load_config(bio_err, NULL))
96251881Speter        goto end;
97251881Speter
98251881Speter    informat = FORMAT_PEM;
99251881Speter    outformat = FORMAT_PEM;
100251881Speter
101251881Speter    ERR_load_crypto_strings();
102251881Speter    OpenSSL_add_all_algorithms();
103289180Speter    args = argv + 1;
104289180Speter    while (!badarg && *args && *args[0] == '-') {
105289180Speter        if (!strcmp(*args, "-v2")) {
106251881Speter            if (args[1]) {
107289180Speter                args++;
108289180Speter                cipher = EVP_get_cipherbyname(*args);
109251881Speter                if (!cipher) {
110289180Speter                    BIO_printf(bio_err, "Unknown cipher %s\n", *args);
111289180Speter                    badarg = 1;
112251881Speter                }
113289180Speter            } else
114289180Speter                badarg = 1;
115251881Speter        } else if (!strcmp(*args, "-v1")) {
116289180Speter            if (args[1]) {
117289180Speter                args++;
118251881Speter                pbe_nid = OBJ_txt2nid(*args);
119251881Speter                if (pbe_nid == NID_undef) {
120251881Speter                    BIO_printf(bio_err, "Unknown PBE algorithm %s\n", *args);
121251881Speter                    badarg = 1;
122251881Speter                }
123289180Speter            } else
124289180Speter                badarg = 1;
125289180Speter        } else if (!strcmp(*args, "-v2prf")) {
126251881Speter            if (args[1]) {
127251881Speter                args++;
128251881Speter                pbe_nid = OBJ_txt2nid(*args);
129251881Speter                if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
130251881Speter                    BIO_printf(bio_err, "Unknown PRF algorithm %s\n", *args);
131251881Speter                    badarg = 1;
132251881Speter                }
133251881Speter            } else
134251881Speter                badarg = 1;
135251881Speter        } else if (!strcmp(*args, "-inform")) {
136            if (args[1]) {
137                args++;
138                informat = str2fmt(*args);
139            } else
140                badarg = 1;
141        } else if (!strcmp(*args, "-outform")) {
142            if (args[1]) {
143                args++;
144                outformat = str2fmt(*args);
145            } else
146                badarg = 1;
147        } else if (!strcmp(*args, "-topk8"))
148            topk8 = 1;
149        else if (!strcmp(*args, "-noiter"))
150            iter = 1;
151        else if (!strcmp(*args, "-nocrypt"))
152            nocrypt = 1;
153        else if (!strcmp(*args, "-nooct"))
154            p8_broken = PKCS8_NO_OCTET;
155        else if (!strcmp(*args, "-nsdb"))
156            p8_broken = PKCS8_NS_DB;
157        else if (!strcmp(*args, "-embed"))
158            p8_broken = PKCS8_EMBEDDED_PARAM;
159        else if (!strcmp(*args, "-passin")) {
160            if (!args[1])
161                goto bad;
162            passargin = *(++args);
163        } else if (!strcmp(*args, "-passout")) {
164            if (!args[1])
165                goto bad;
166            passargout = *(++args);
167        }
168#ifndef OPENSSL_NO_ENGINE
169        else if (strcmp(*args, "-engine") == 0) {
170            if (!args[1])
171                goto bad;
172            engine = *(++args);
173        }
174#endif
175        else if (!strcmp(*args, "-in")) {
176            if (args[1]) {
177                args++;
178                infile = *args;
179            } else
180                badarg = 1;
181        } else if (!strcmp(*args, "-out")) {
182            if (args[1]) {
183                args++;
184                outfile = *args;
185            } else
186                badarg = 1;
187        } else
188            badarg = 1;
189        args++;
190    }
191
192    if (badarg) {
193 bad:
194        BIO_printf(bio_err, "Usage pkcs8 [options]\n");
195        BIO_printf(bio_err, "where options are\n");
196        BIO_printf(bio_err, "-in file        input file\n");
197        BIO_printf(bio_err, "-inform X       input format (DER or PEM)\n");
198        BIO_printf(bio_err,
199                   "-passin arg     input file pass phrase source\n");
200        BIO_printf(bio_err, "-outform X      output format (DER or PEM)\n");
201        BIO_printf(bio_err, "-out file       output file\n");
202        BIO_printf(bio_err,
203                   "-passout arg    output file pass phrase source\n");
204        BIO_printf(bio_err, "-topk8          output PKCS8 file\n");
205        BIO_printf(bio_err,
206                   "-nooct          use (nonstandard) no octet format\n");
207        BIO_printf(bio_err,
208                   "-embed          use (nonstandard) embedded DSA parameters format\n");
209        BIO_printf(bio_err,
210                   "-nsdb           use (nonstandard) DSA Netscape DB format\n");
211        BIO_printf(bio_err, "-noiter         use 1 as iteration count\n");
212        BIO_printf(bio_err,
213                   "-nocrypt        use or expect unencrypted private key\n");
214        BIO_printf(bio_err,
215                   "-v2 alg         use PKCS#5 v2.0 and cipher \"alg\"\n");
216        BIO_printf(bio_err,
217                   "-v1 obj         use PKCS#5 v1.5 and cipher \"alg\"\n");
218#ifndef OPENSSL_NO_ENGINE
219        BIO_printf(bio_err,
220                   " -engine e       use engine e, possibly a hardware device.\n");
221#endif
222        goto end;
223    }
224    e = setup_engine(bio_err, engine, 0);
225
226    if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
227        BIO_printf(bio_err, "Error getting passwords\n");
228        goto end;
229    }
230
231    if ((pbe_nid == -1) && !cipher)
232        pbe_nid = NID_pbeWithMD5AndDES_CBC;
233
234    if (infile) {
235        if (!(in = BIO_new_file(infile, "rb"))) {
236            BIO_printf(bio_err, "Can't open input file %s\n", infile);
237            goto end;
238        }
239    } else
240        in = BIO_new_fp(stdin, BIO_NOCLOSE);
241
242    if (outfile) {
243        if (!(out = BIO_new_file(outfile, "wb"))) {
244            BIO_printf(bio_err, "Can't open output file %s\n", outfile);
245            goto end;
246        }
247    } else {
248        out = BIO_new_fp(stdout, BIO_NOCLOSE);
249#ifdef OPENSSL_SYS_VMS
250        {
251            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
252            out = BIO_push(tmpbio, out);
253        }
254#endif
255    }
256    if (topk8) {
257        pkey = load_key(bio_err, infile, informat, 1, passin, e, "key");
258        if (!pkey)
259            goto end;
260        if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
261            BIO_printf(bio_err, "Error converting key\n");
262            ERR_print_errors(bio_err);
263            goto end;
264        }
265        if (nocrypt) {
266            if (outformat == FORMAT_PEM)
267                PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
268            else if (outformat == FORMAT_ASN1)
269                i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
270            else {
271                BIO_printf(bio_err, "Bad format specified for key\n");
272                goto end;
273            }
274        } else {
275            if (passout)
276                p8pass = passout;
277            else {
278                p8pass = pass;
279                if (EVP_read_pw_string
280                    (pass, sizeof(pass), "Enter Encryption Password:", 1))
281                    goto end;
282            }
283            app_RAND_load_file(NULL, bio_err, 0);
284            if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,
285                                     p8pass, strlen(p8pass),
286                                     NULL, 0, iter, p8inf))) {
287                BIO_printf(bio_err, "Error encrypting key\n");
288                ERR_print_errors(bio_err);
289                goto end;
290            }
291            app_RAND_write_file(NULL, bio_err);
292            if (outformat == FORMAT_PEM)
293                PEM_write_bio_PKCS8(out, p8);
294            else if (outformat == FORMAT_ASN1)
295                i2d_PKCS8_bio(out, p8);
296            else {
297                BIO_printf(bio_err, "Bad format specified for key\n");
298                goto end;
299            }
300        }
301
302        ret = 0;
303        goto end;
304    }
305
306    if (nocrypt) {
307        if (informat == FORMAT_PEM)
308            p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
309        else if (informat == FORMAT_ASN1)
310            p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
311        else {
312            BIO_printf(bio_err, "Bad format specified for key\n");
313            goto end;
314        }
315    } else {
316        if (informat == FORMAT_PEM)
317            p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
318        else if (informat == FORMAT_ASN1)
319            p8 = d2i_PKCS8_bio(in, NULL);
320        else {
321            BIO_printf(bio_err, "Bad format specified for key\n");
322            goto end;
323        }
324
325        if (!p8) {
326            BIO_printf(bio_err, "Error reading key\n");
327            ERR_print_errors(bio_err);
328            goto end;
329        }
330        if (passin)
331            p8pass = passin;
332        else {
333            p8pass = pass;
334            EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0);
335        }
336        p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
337    }
338
339    if (!p8inf) {
340        BIO_printf(bio_err, "Error decrypting key\n");
341        ERR_print_errors(bio_err);
342        goto end;
343    }
344
345    if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
346        BIO_printf(bio_err, "Error converting key\n");
347        ERR_print_errors(bio_err);
348        goto end;
349    }
350
351    if (p8inf->broken) {
352        BIO_printf(bio_err, "Warning: broken key encoding: ");
353        switch (p8inf->broken) {
354        case PKCS8_NO_OCTET:
355            BIO_printf(bio_err, "No Octet String in PrivateKey\n");
356            break;
357
358        case PKCS8_EMBEDDED_PARAM:
359            BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
360            break;
361
362        case PKCS8_NS_DB:
363            BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
364            break;
365
366        case PKCS8_NEG_PRIVKEY:
367            BIO_printf(bio_err, "DSA private key value is negative\n");
368            break;
369
370        default:
371            BIO_printf(bio_err, "Unknown broken type\n");
372            break;
373        }
374    }
375
376    if (outformat == FORMAT_PEM)
377        PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
378    else if (outformat == FORMAT_ASN1)
379        i2d_PrivateKey_bio(out, pkey);
380    else {
381        BIO_printf(bio_err, "Bad format specified for key\n");
382        goto end;
383    }
384    ret = 0;
385
386 end:
387    X509_SIG_free(p8);
388    PKCS8_PRIV_KEY_INFO_free(p8inf);
389    EVP_PKEY_free(pkey);
390    release_engine(e);
391    BIO_free_all(out);
392    BIO_free(in);
393    if (passin)
394        OPENSSL_free(passin);
395    if (passout)
396        OPENSSL_free(passout);
397
398    return ret;
399}
400