GH601: Various spelling fixes.
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 2006.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 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
59 #include "apps.h"
60 #include <string.h>
61 #include <openssl/err.h>
62 #include <openssl/pem.h>
63 #include <openssl/evp.h>
64
65 #define KEY_PRIVKEY     1
66 #define KEY_PUBKEY      2
67 #define KEY_CERT        3
68
69 static EVP_PKEY_CTX *init_ctx(int *pkeysize,
70                               const char *keyfile, int keyform, int key_type,
71                               char *passinarg, int pkey_op, ENGINE *e,
72                               const int impl);
73
74 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
75                       ENGINE *e);
76
77 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
78                     unsigned char *out, size_t *poutlen,
79                     unsigned char *in, size_t inlen);
80
81 typedef enum OPTION_choice {
82     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
83     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
84     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
85     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
86     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
87     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT
88 } OPTION_CHOICE;
89
90 OPTIONS pkeyutl_options[] = {
91     {"help", OPT_HELP, '-', "Display this summary"},
92     {"in", OPT_IN, '<', "Input file"},
93     {"out", OPT_OUT, '>', "Output file"},
94     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
95     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
96     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
97     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
98     {"sign", OPT_SIGN, '-', "Sign with private key"},
99     {"verify", OPT_VERIFY, '-', "Verify with public key"},
100     {"verifyrecover", OPT_VERIFYRECOVER, '-',
101      "Verify with public key, recover original data"},
102     {"rev", OPT_REV, '-', "Reverse the input buffer"},
103     {"encrypt", OPT_ENCRYPT, '-', "Encrypt with public key"},
104     {"decrypt", OPT_DECRYPT, '-', "Decrypt with private key"},
105     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
106     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
107     {"inkey", OPT_INKEY, 's', "Input key"},
108     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
109     {"passin", OPT_PASSIN, 's', "Pass phrase source"},
110     {"peerform", OPT_PEERFORM, 'E', "Peer key format - default PEM"},
111     {"keyform", OPT_KEYFORM, 'E', "Private key format - default PEM"},
112     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
113 #ifndef OPENSSL_NO_ENGINE
114     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
115     {"engine_impl", OPT_ENGINE_IMPL, '-', "Also use engine given by -engine for crypto operations"},
116 #endif
117     {NULL}
118 };
119
120 int pkeyutl_main(int argc, char **argv)
121 {
122     BIO *in = NULL, *out = NULL;
123     ENGINE *e = NULL;
124     EVP_PKEY_CTX *ctx = NULL;
125     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
126     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
127     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
128     OPTION_CHOICE o;
129     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform =
130         FORMAT_PEM;
131     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
132     int engine_impl = 0;
133     int ret = 1, rv = -1;
134     size_t buf_outlen;
135     const char *inkey = NULL;
136     const char *peerkey = NULL;
137     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
138
139     prog = opt_init(argc, argv, pkeyutl_options);
140     while ((o = opt_next()) != OPT_EOF) {
141         switch (o) {
142         case OPT_EOF:
143         case OPT_ERR:
144  opthelp:
145             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
146             goto end;
147         case OPT_HELP:
148             opt_help(pkeyutl_options);
149             ret = 0;
150             goto end;
151         case OPT_IN:
152             infile = opt_arg();
153             break;
154         case OPT_OUT:
155             outfile = opt_arg();
156             break;
157         case OPT_SIGFILE:
158             sigfile = opt_arg();
159             break;
160         case OPT_ENGINE_IMPL:
161             engine_impl = 1;
162             break;
163         case OPT_INKEY:
164             inkey = opt_arg();
165             break;
166         case OPT_PEERKEY:
167             peerkey = opt_arg();
168             break;
169         case OPT_PASSIN:
170             passinarg = opt_arg();
171             break;
172         case OPT_PEERFORM:
173             if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
174                 goto opthelp;
175             break;
176         case OPT_KEYFORM:
177             if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
178                 goto opthelp;
179             break;
180         case OPT_ENGINE:
181             e = setup_engine(opt_arg(), 0);
182             break;
183         case OPT_PUBIN:
184             key_type = KEY_PUBKEY;
185             break;
186         case OPT_CERTIN:
187             key_type = KEY_CERT;
188             break;
189         case OPT_ASN1PARSE:
190             asn1parse = 1;
191             break;
192         case OPT_HEXDUMP:
193             hexdump = 1;
194             break;
195         case OPT_SIGN:
196             pkey_op = EVP_PKEY_OP_SIGN;
197             break;
198         case OPT_VERIFY:
199             pkey_op = EVP_PKEY_OP_VERIFY;
200             break;
201         case OPT_VERIFYRECOVER:
202             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
203             break;
204         case OPT_ENCRYPT:
205             pkey_op = EVP_PKEY_OP_ENCRYPT;
206             break;
207         case OPT_DECRYPT:
208             pkey_op = EVP_PKEY_OP_DECRYPT;
209             break;
210         case OPT_DERIVE:
211             pkey_op = EVP_PKEY_OP_DERIVE;
212             break;
213         case OPT_REV:
214             rev = 1;
215             break;
216         case OPT_PKEYOPT:
217             if ((pkeyopts == NULL &&
218                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
219                 sk_OPENSSL_STRING_push(pkeyopts, *++argv) == 0) {
220                 BIO_puts(bio_err, "out of memory\n");
221                 goto end;
222             }
223             break;
224         }
225     }
226     argc = opt_num_rest();
227     argv = opt_rest();
228
229     if (inkey == NULL ||
230         (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE))
231         goto opthelp;
232
233     ctx = init_ctx(&keysize, inkey, keyform, key_type,
234                    passinarg, pkey_op, e, engine_impl);
235     if (ctx == NULL) {
236         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
237         ERR_print_errors(bio_err);
238         goto end;
239     }
240     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
241         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
242         ERR_print_errors(bio_err);
243         goto end;
244     }
245     if (pkeyopts != NULL) {
246         int num = sk_OPENSSL_STRING_num(pkeyopts);
247         int i;
248
249         for (i = 0; i < num; ++i) {
250             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
251
252             if (pkey_ctrl_string(ctx, opt) <= 0) {
253                 BIO_printf(bio_err, "%s: Can't set parameter:\n", prog);
254                 ERR_print_errors(bio_err);
255                 goto end;
256             }
257         }
258     }
259
260     if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) {
261         BIO_printf(bio_err,
262                    "%s: Signature file specified for non verify\n", prog);
263         goto end;
264     }
265
266     if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) {
267         BIO_printf(bio_err,
268                    "%s: No signature file specified for verify\n", prog);
269         goto end;
270     }
271
272 /* FIXME: seed PRNG only if needed */
273     app_RAND_load_file(NULL, 0);
274
275     if (pkey_op != EVP_PKEY_OP_DERIVE) {
276         in = bio_open_default(infile, 'r', FORMAT_BINARY);
277         if (in == NULL)
278             goto end;
279     }
280     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
281     if (out == NULL)
282         goto end;
283
284     if (sigfile) {
285         BIO *sigbio = BIO_new_file(sigfile, "rb");
286         if (!sigbio) {
287             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
288             goto end;
289         }
290         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
291         BIO_free(sigbio);
292         if (siglen < 0) {
293             BIO_printf(bio_err, "Error reading signature data\n");
294             goto end;
295         }
296     }
297
298     if (in) {
299         /* Read the input data */
300         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
301         if (buf_inlen < 0) {
302             BIO_printf(bio_err, "Error reading input Data\n");
303             exit(1);
304         }
305         if (rev) {
306             size_t i;
307             unsigned char ctmp;
308             size_t l = (size_t)buf_inlen;
309             for (i = 0; i < l / 2; i++) {
310                 ctmp = buf_in[i];
311                 buf_in[i] = buf_in[l - 1 - i];
312                 buf_in[l - 1 - i] = ctmp;
313             }
314         }
315     }
316
317     if (pkey_op == EVP_PKEY_OP_VERIFY) {
318         rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
319                              buf_in, (size_t)buf_inlen);
320         if (rv == 1) {
321             BIO_puts(out, "Signature Verified Successfully\n");
322             ret = 0;
323         } else
324             BIO_puts(out, "Signature Verification Failure\n");
325         goto end;
326     }
327     rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
328                   buf_in, (size_t)buf_inlen);
329     if (rv > 0 && buf_outlen != 0) {
330         buf_out = app_malloc(buf_outlen, "buffer output");
331         rv = do_keyop(ctx, pkey_op,
332                       buf_out, (size_t *)&buf_outlen,
333                       buf_in, (size_t)buf_inlen);
334     }
335     if (rv < 0) {
336         ERR_print_errors(bio_err);
337         goto end;
338     }
339     ret = 0;
340
341     if (asn1parse) {
342         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
343             ERR_print_errors(bio_err);
344     } else if (hexdump)
345         BIO_dump(out, (char *)buf_out, buf_outlen);
346     else
347         BIO_write(out, buf_out, buf_outlen);
348
349  end:
350     EVP_PKEY_CTX_free(ctx);
351     BIO_free(in);
352     BIO_free_all(out);
353     OPENSSL_free(buf_in);
354     OPENSSL_free(buf_out);
355     OPENSSL_free(sig);
356     sk_OPENSSL_STRING_free(pkeyopts);
357     return ret;
358 }
359
360 static EVP_PKEY_CTX *init_ctx(int *pkeysize,
361                               const char *keyfile, int keyform, int key_type,
362                               char *passinarg, int pkey_op, ENGINE *e,
363                               const int engine_impl)
364 {
365     EVP_PKEY *pkey = NULL;
366     EVP_PKEY_CTX *ctx = NULL;
367     ENGINE *impl = NULL;
368     char *passin = NULL;
369     int rv = -1;
370     X509 *x;
371     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
372          || (pkey_op == EVP_PKEY_OP_DERIVE))
373         && (key_type != KEY_PRIVKEY)) {
374         BIO_printf(bio_err, "A private key is needed for this operation\n");
375         goto end;
376     }
377     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
378         BIO_printf(bio_err, "Error getting password\n");
379         goto end;
380     }
381     switch (key_type) {
382     case KEY_PRIVKEY:
383         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
384         break;
385
386     case KEY_PUBKEY:
387         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "Public Key");
388         break;
389
390     case KEY_CERT:
391         x = load_cert(keyfile, keyform, NULL, e, "Certificate");
392         if (x) {
393             pkey = X509_get_pubkey(x);
394             X509_free(x);
395         }
396         break;
397
398     }
399
400     *pkeysize = EVP_PKEY_size(pkey);
401
402     if (!pkey)
403         goto end;
404
405 #ifndef OPENSSL_NO_ENGINE
406     if (engine_impl)
407         impl = e;
408 #endif
409     
410     ctx = EVP_PKEY_CTX_new(pkey, impl);
411
412     EVP_PKEY_free(pkey);
413
414     if (ctx == NULL)
415         goto end;
416
417     switch (pkey_op) {
418     case EVP_PKEY_OP_SIGN:
419         rv = EVP_PKEY_sign_init(ctx);
420         break;
421
422     case EVP_PKEY_OP_VERIFY:
423         rv = EVP_PKEY_verify_init(ctx);
424         break;
425
426     case EVP_PKEY_OP_VERIFYRECOVER:
427         rv = EVP_PKEY_verify_recover_init(ctx);
428         break;
429
430     case EVP_PKEY_OP_ENCRYPT:
431         rv = EVP_PKEY_encrypt_init(ctx);
432         break;
433
434     case EVP_PKEY_OP_DECRYPT:
435         rv = EVP_PKEY_decrypt_init(ctx);
436         break;
437
438     case EVP_PKEY_OP_DERIVE:
439         rv = EVP_PKEY_derive_init(ctx);
440         break;
441     }
442
443     if (rv <= 0) {
444         EVP_PKEY_CTX_free(ctx);
445         ctx = NULL;
446     }
447
448  end:
449     OPENSSL_free(passin);
450     return ctx;
451
452 }
453
454 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
455                       ENGINE* e)
456 {
457     EVP_PKEY *peer = NULL;
458     ENGINE* engine = NULL;
459     int ret;
460
461     if (peerform == FORMAT_ENGINE)
462         engine = e;
463     peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key");
464     if (!peer) {
465         BIO_printf(bio_err, "Error reading peer key %s\n", file);
466         ERR_print_errors(bio_err);
467         return 0;
468     }
469
470     ret = EVP_PKEY_derive_set_peer(ctx, peer);
471
472     EVP_PKEY_free(peer);
473     if (ret <= 0)
474         ERR_print_errors(bio_err);
475     return ret;
476 }
477
478 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
479                     unsigned char *out, size_t *poutlen,
480                     unsigned char *in, size_t inlen)
481 {
482     int rv = 0;
483     switch (pkey_op) {
484     case EVP_PKEY_OP_VERIFYRECOVER:
485         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
486         break;
487
488     case EVP_PKEY_OP_SIGN:
489         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
490         break;
491
492     case EVP_PKEY_OP_ENCRYPT:
493         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
494         break;
495
496     case EVP_PKEY_OP_DECRYPT:
497         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
498         break;
499
500     case EVP_PKEY_OP_DERIVE:
501         rv = EVP_PKEY_derive(ctx, out, poutlen);
502         break;
503
504     }
505     return rv;
506 }