Build resource files
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "apps.h"
11 #include "progs.h"
12 #include <string.h>
13 #include <openssl/err.h>
14 #include <openssl/pem.h>
15 #include <openssl/evp.h>
16 #include <sys/stat.h>
17
18 #define KEY_NONE        0
19 #define KEY_PRIVKEY     1
20 #define KEY_PUBKEY      2
21 #define KEY_CERT        3
22
23 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
24                               const char *keyfile, int keyform, int key_type,
25                               char *passinarg, int pkey_op, ENGINE *e,
26                               const int impl, int rawin, EVP_PKEY **ppkey,
27                               EVP_MD_CTX *mctx, const char *digestname,
28                               OSSL_LIB_CTX *libctx, const char *propq);
29
30 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
31                       ENGINE *e);
32
33 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
34                     unsigned char *out, size_t *poutlen,
35                     const unsigned char *in, size_t inlen);
36
37 static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx,
38                         EVP_PKEY *pkey, BIO *in,
39                         int filesize, unsigned char *sig, int siglen,
40                         unsigned char **out, size_t *poutlen);
41
42 typedef enum OPTION_choice {
43     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
44     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
45     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
46     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
47     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
48     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_PKEYOPT_PASSIN, OPT_KDF,
49     OPT_KDFLEN, OPT_R_ENUM, OPT_PROV_ENUM,
50     OPT_CONFIG,
51     OPT_RAWIN, OPT_DIGEST
52 } OPTION_CHOICE;
53
54 const OPTIONS pkeyutl_options[] = {
55     OPT_SECTION("General"),
56     {"help", OPT_HELP, '-', "Display this summary"},
57 #ifndef OPENSSL_NO_ENGINE
58     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
59     {"engine_impl", OPT_ENGINE_IMPL, '-',
60      "Also use engine given by -engine for crypto operations"},
61 #endif
62     {"sign", OPT_SIGN, '-', "Sign input data with private key"},
63     {"verify", OPT_VERIFY, '-', "Verify with public key"},
64     {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"},
65     {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"},
66     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
67     OPT_CONFIG_OPTION,
68
69     OPT_SECTION("Input"),
70     {"in", OPT_IN, '<', "Input file - default stdin"},
71     {"rawin", OPT_RAWIN, '-', "Indicate the input data is in raw form"},
72     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
73     {"inkey", OPT_INKEY, 's', "Input private key file"},
74     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
75     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
76     {"peerform", OPT_PEERFORM, 'E', "Peer key format (DER/PEM/P12/ENGINE)"},
77     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
78     {"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
79     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
80     {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"},
81
82     OPT_SECTION("Output"),
83     {"out", OPT_OUT, '>', "Output file - default stdout"},
84     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
85     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
86     {"verifyrecover", OPT_VERIFYRECOVER, '-',
87      "Verify with public key, recover original data"},
88
89     OPT_SECTION("Signing/Derivation"),
90     {"digest", OPT_DIGEST, 's',
91      "Specify the digest algorithm when signing the raw input data"},
92     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
93     {"pkeyopt_passin", OPT_PKEYOPT_PASSIN, 's',
94      "Public key option that is read as a passphrase argument opt:passphrase"},
95     {"kdf", OPT_KDF, 's', "Use KDF algorithm"},
96     {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"},
97
98     OPT_R_OPTIONS,
99     OPT_PROV_OPTIONS,
100     {NULL}
101 };
102
103 int pkeyutl_main(int argc, char **argv)
104 {
105     CONF *conf = NULL;
106     BIO *in = NULL, *out = NULL;
107     ENGINE *e = NULL;
108     EVP_PKEY_CTX *ctx = NULL;
109     EVP_PKEY *pkey = NULL;
110     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
111     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
112     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
113     OPTION_CHOICE o;
114     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM;
115     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
116     int engine_impl = 0;
117     int ret = 1, rv = -1;
118     size_t buf_outlen;
119     const char *inkey = NULL;
120     const char *peerkey = NULL;
121     const char *kdfalg = NULL, *digestname = NULL;
122     int kdflen = 0;
123     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
124     STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
125     int rawin = 0;
126     EVP_MD_CTX *mctx = NULL;
127     int filesize = -1;
128     OSSL_LIB_CTX *libctx = app_get0_libctx();
129
130     prog = opt_init(argc, argv, pkeyutl_options);
131     while ((o = opt_next()) != OPT_EOF) {
132         switch (o) {
133         case OPT_EOF:
134         case OPT_ERR:
135  opthelp:
136             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
137             goto end;
138         case OPT_HELP:
139             opt_help(pkeyutl_options);
140             ret = 0;
141             goto end;
142         case OPT_IN:
143             infile = opt_arg();
144             break;
145         case OPT_OUT:
146             outfile = opt_arg();
147             break;
148         case OPT_SIGFILE:
149             sigfile = opt_arg();
150             break;
151         case OPT_ENGINE_IMPL:
152             engine_impl = 1;
153             break;
154         case OPT_INKEY:
155             inkey = opt_arg();
156             break;
157         case OPT_PEERKEY:
158             peerkey = opt_arg();
159             break;
160         case OPT_PASSIN:
161             passinarg = opt_arg();
162             break;
163         case OPT_PEERFORM:
164             if (!opt_format(opt_arg(), OPT_FMT_ANY, &peerform))
165                 goto opthelp;
166             break;
167         case OPT_KEYFORM:
168             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
169                 goto opthelp;
170             break;
171         case OPT_R_CASES:
172             if (!opt_rand(o))
173                 goto end;
174             break;
175         case OPT_CONFIG:
176             conf = app_load_config_modules(opt_arg());
177             if (conf == NULL)
178                 goto end;
179             break;
180         case OPT_PROV_CASES:
181             if (!opt_provider(o))
182                 goto end;
183             break;
184         case OPT_ENGINE:
185             e = setup_engine(opt_arg(), 0);
186             break;
187         case OPT_PUBIN:
188             key_type = KEY_PUBKEY;
189             break;
190         case OPT_CERTIN:
191             key_type = KEY_CERT;
192             break;
193         case OPT_ASN1PARSE:
194             asn1parse = 1;
195             break;
196         case OPT_HEXDUMP:
197             hexdump = 1;
198             break;
199         case OPT_SIGN:
200             pkey_op = EVP_PKEY_OP_SIGN;
201             break;
202         case OPT_VERIFY:
203             pkey_op = EVP_PKEY_OP_VERIFY;
204             break;
205         case OPT_VERIFYRECOVER:
206             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
207             break;
208         case OPT_ENCRYPT:
209             pkey_op = EVP_PKEY_OP_ENCRYPT;
210             break;
211         case OPT_DECRYPT:
212             pkey_op = EVP_PKEY_OP_DECRYPT;
213             break;
214         case OPT_DERIVE:
215             pkey_op = EVP_PKEY_OP_DERIVE;
216             break;
217         case OPT_KDF:
218             pkey_op = EVP_PKEY_OP_DERIVE;
219             key_type = KEY_NONE;
220             kdfalg = opt_arg();
221             break;
222         case OPT_KDFLEN:
223             kdflen = atoi(opt_arg());
224             break;
225         case OPT_REV:
226             rev = 1;
227             break;
228         case OPT_PKEYOPT:
229             if ((pkeyopts == NULL &&
230                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
231                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
232                 BIO_puts(bio_err, "out of memory\n");
233                 goto end;
234             }
235             break;
236         case OPT_PKEYOPT_PASSIN:
237             if ((pkeyopts_passin == NULL &&
238                  (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
239                 sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
240                 BIO_puts(bio_err, "out of memory\n");
241                 goto end;
242             }
243             break;
244         case OPT_RAWIN:
245             rawin = 1;
246             break;
247         case OPT_DIGEST:
248             digestname = opt_arg();
249             break;
250         }
251     }
252
253     /* No extra arguments. */
254     argc = opt_num_rest();
255     if (argc != 0)
256         goto opthelp;
257
258     if (!app_RAND_load())
259         goto end;
260
261     if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) {
262         BIO_printf(bio_err,
263                    "%s: -rawin can only be used with -sign or -verify\n",
264                    prog);
265         goto opthelp;
266     }
267
268     if (digestname != NULL && !rawin) {
269         BIO_printf(bio_err,
270                    "%s: -digest can only be used with -rawin\n",
271                    prog);
272         goto opthelp;
273     }
274
275     if (rawin && rev) {
276         BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n",
277                    prog);
278         goto opthelp;
279     }
280
281     if (kdfalg != NULL) {
282         if (kdflen == 0) {
283             BIO_printf(bio_err,
284                        "%s: no KDF length given (-kdflen parameter).\n", prog);
285             goto opthelp;
286         }
287     } else if (inkey == NULL) {
288         BIO_printf(bio_err,
289                    "%s: no private key given (-inkey parameter).\n", prog);
290         goto opthelp;
291     } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
292         BIO_printf(bio_err,
293                    "%s: no peer key given (-peerkey parameter).\n", prog);
294         goto opthelp;
295     }
296
297     if (rawin) {
298         if ((mctx = EVP_MD_CTX_new()) == NULL) {
299             BIO_printf(bio_err, "Error: out of memory\n");
300             goto end;
301         }
302     }
303     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
304                    passinarg, pkey_op, e, engine_impl, rawin, &pkey,
305                    mctx, digestname, libctx, app_get0_propq());
306     if (ctx == NULL) {
307         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
308         ERR_print_errors(bio_err);
309         goto end;
310     }
311     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
312         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
313         ERR_print_errors(bio_err);
314         goto end;
315     }
316     if (pkeyopts != NULL) {
317         int num = sk_OPENSSL_STRING_num(pkeyopts);
318         int i;
319
320         for (i = 0; i < num; ++i) {
321             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
322
323             if (pkey_ctrl_string(ctx, opt) <= 0) {
324                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
325                            prog, opt);
326                 ERR_print_errors(bio_err);
327                 goto end;
328             }
329         }
330     }
331     if (pkeyopts_passin != NULL) {
332         int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
333         int i;
334
335         for (i = 0; i < num; i++) {
336             char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
337             char *passin = strchr(opt, ':');
338             char *passwd;
339
340             if (passin == NULL) {
341                 /* Get password interactively */
342                 char passwd_buf[4096];
343                 int r;
344
345                 BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
346                 r = EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
347                                        passwd_buf, 0);
348                 if (r < 0) {
349                     if (r == -2)
350                         BIO_puts(bio_err, "user abort\n");
351                     else
352                         BIO_puts(bio_err, "entry failed\n");
353                     goto end;
354                 }
355                 passwd = OPENSSL_strdup(passwd_buf);
356                 if (passwd == NULL) {
357                     BIO_puts(bio_err, "out of memory\n");
358                     goto end;
359                 }
360             } else {
361                 /* Get password as a passin argument: First split option name
362                  * and passphrase argument into two strings */
363                 *passin = 0;
364                 passin++;
365                 if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
366                     BIO_printf(bio_err, "failed to get '%s'\n", opt);
367                     goto end;
368                 }
369             }
370
371             if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
372                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
373                            prog, opt);
374                 goto end;
375             }
376             OPENSSL_free(passwd);
377         }
378     }
379
380     if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
381         BIO_printf(bio_err,
382                    "%s: Signature file specified for non verify\n", prog);
383         goto end;
384     }
385
386     if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
387         BIO_printf(bio_err,
388                    "%s: No signature file specified for verify\n", prog);
389         goto end;
390     }
391
392     if (pkey_op != EVP_PKEY_OP_DERIVE) {
393         in = bio_open_default(infile, 'r', FORMAT_BINARY);
394         if (infile != NULL) {
395             struct stat st;
396
397             if (stat(infile, &st) == 0 && st.st_size <= INT_MAX)
398                 filesize = (int)st.st_size;
399         }
400         if (in == NULL)
401             goto end;
402     }
403     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
404     if (out == NULL)
405         goto end;
406
407     if (sigfile != NULL) {
408         BIO *sigbio = BIO_new_file(sigfile, "rb");
409
410         if (sigbio == NULL) {
411             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
412             goto end;
413         }
414         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
415         BIO_free(sigbio);
416         if (siglen < 0) {
417             BIO_printf(bio_err, "Error reading signature data\n");
418             goto end;
419         }
420     }
421
422     /* Raw input data is handled elsewhere */
423     if (in != NULL && !rawin) {
424         /* Read the input data */
425         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
426         if (buf_inlen < 0) {
427             BIO_printf(bio_err, "Error reading input Data\n");
428             goto end;
429         }
430         if (rev) {
431             size_t i;
432             unsigned char ctmp;
433             size_t l = (size_t)buf_inlen;
434             for (i = 0; i < l / 2; i++) {
435                 ctmp = buf_in[i];
436                 buf_in[i] = buf_in[l - 1 - i];
437                 buf_in[l - 1 - i] = ctmp;
438             }
439         }
440     }
441
442     /* Sanity check the input if the input is not raw */
443     if (!rawin
444             && buf_inlen > EVP_MAX_MD_SIZE
445             && (pkey_op == EVP_PKEY_OP_SIGN
446                 || pkey_op == EVP_PKEY_OP_VERIFY)) {
447         BIO_printf(bio_err,
448                    "Error: The input data looks too long to be a hash\n");
449         goto end;
450     }
451
452     if (pkey_op == EVP_PKEY_OP_VERIFY) {
453         if (rawin) {
454             rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, sig, siglen,
455                               NULL, 0);
456         } else {
457             rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
458                                  buf_in, (size_t)buf_inlen);
459         }
460         if (rv == 1) {
461             BIO_puts(out, "Signature Verified Successfully\n");
462             ret = 0;
463         } else {
464             BIO_puts(out, "Signature Verification Failure\n");
465         }
466         goto end;
467     }
468     if (kdflen != 0) {
469         buf_outlen = kdflen;
470         rv = 1;
471     } else {
472         if (rawin) {
473             /* rawin allocates the buffer in do_raw_keyop() */
474             rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, NULL, 0,
475                               &buf_out, (size_t *)&buf_outlen);
476         } else {
477             rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
478                           buf_in, (size_t)buf_inlen);
479             if (rv > 0 && buf_outlen != 0) {
480                 buf_out = app_malloc(buf_outlen, "buffer output");
481                 rv = do_keyop(ctx, pkey_op,
482                               buf_out, (size_t *)&buf_outlen,
483                               buf_in, (size_t)buf_inlen);
484             }
485         }
486     }
487     if (rv <= 0) {
488         if (pkey_op != EVP_PKEY_OP_DERIVE) {
489             BIO_puts(bio_err, "Public Key operation error\n");
490         } else {
491             BIO_puts(bio_err, "Key derivation failed\n");
492         }
493         ERR_print_errors(bio_err);
494         goto end;
495     }
496     ret = 0;
497
498     if (asn1parse) {
499         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
500             ERR_print_errors(bio_err);
501     } else if (hexdump) {
502         BIO_dump(out, (char *)buf_out, buf_outlen);
503     } else {
504         BIO_write(out, buf_out, buf_outlen);
505     }
506
507  end:
508     EVP_MD_CTX_free(mctx);
509     EVP_PKEY_CTX_free(ctx);
510     release_engine(e);
511     BIO_free(in);
512     BIO_free_all(out);
513     OPENSSL_free(buf_in);
514     OPENSSL_free(buf_out);
515     OPENSSL_free(sig);
516     sk_OPENSSL_STRING_free(pkeyopts);
517     sk_OPENSSL_STRING_free(pkeyopts_passin);
518     NCONF_free(conf);
519     return ret;
520 }
521
522 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
523                               const char *keyfile, int keyform, int key_type,
524                               char *passinarg, int pkey_op, ENGINE *e,
525                               const int engine_impl, int rawin,
526                               EVP_PKEY **ppkey, EVP_MD_CTX *mctx, const char *digestname,
527                               OSSL_LIB_CTX *libctx, const char *propq)
528 {
529     EVP_PKEY *pkey = NULL;
530     EVP_PKEY_CTX *ctx = NULL;
531     ENGINE *impl = NULL;
532     char *passin = NULL;
533     int rv = -1;
534     X509 *x;
535
536     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
537          || (pkey_op == EVP_PKEY_OP_DERIVE))
538         && (key_type != KEY_PRIVKEY && kdfalg == NULL)) {
539         BIO_printf(bio_err, "A private key is needed for this operation\n");
540         goto end;
541     }
542     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
543         BIO_printf(bio_err, "Error getting password\n");
544         goto end;
545     }
546     switch (key_type) {
547     case KEY_PRIVKEY:
548         pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
549         break;
550
551     case KEY_PUBKEY:
552         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key");
553         break;
554
555     case KEY_CERT:
556         x = load_cert(keyfile, "Certificate");
557         if (x) {
558             pkey = X509_get_pubkey(x);
559             X509_free(x);
560         }
561         break;
562
563     case KEY_NONE:
564         break;
565
566     }
567
568 #ifndef OPENSSL_NO_ENGINE
569     if (engine_impl)
570         impl = e;
571 #endif
572
573     if (kdfalg != NULL) {
574         int kdfnid = OBJ_sn2nid(kdfalg);
575
576         if (kdfnid == NID_undef) {
577             kdfnid = OBJ_ln2nid(kdfalg);
578             if (kdfnid == NID_undef) {
579                 BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n",
580                            kdfalg);
581                 goto end;
582             }
583         }
584         if (impl != NULL)
585             ctx = EVP_PKEY_CTX_new_id(kdfnid, impl);
586         else
587             ctx = EVP_PKEY_CTX_new_from_name(libctx, kdfalg, propq);
588     } else {
589         if (pkey == NULL)
590             goto end;
591
592         *pkeysize = EVP_PKEY_size(pkey);
593         if (impl != NULL)
594             ctx = EVP_PKEY_CTX_new(pkey, impl);
595         else
596             ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
597         if (ppkey != NULL)
598             *ppkey = pkey;
599         EVP_PKEY_free(pkey);
600     }
601
602     if (ctx == NULL)
603         goto end;
604
605     if (rawin) {
606         EVP_MD_CTX_set_pkey_ctx(mctx, ctx);
607
608         switch (pkey_op) {
609         case EVP_PKEY_OP_SIGN:
610             rv = EVP_DigestSignInit_ex(mctx, NULL, digestname, libctx, propq,
611                                        pkey, NULL);
612             break;
613
614         case EVP_PKEY_OP_VERIFY:
615             rv = EVP_DigestVerifyInit_ex(mctx, NULL, digestname, libctx, propq,
616                                          pkey, NULL);
617             break;
618         }
619
620     } else {
621         switch (pkey_op) {
622         case EVP_PKEY_OP_SIGN:
623             rv = EVP_PKEY_sign_init(ctx);
624             break;
625
626         case EVP_PKEY_OP_VERIFY:
627             rv = EVP_PKEY_verify_init(ctx);
628             break;
629
630         case EVP_PKEY_OP_VERIFYRECOVER:
631             rv = EVP_PKEY_verify_recover_init(ctx);
632             break;
633
634         case EVP_PKEY_OP_ENCRYPT:
635             rv = EVP_PKEY_encrypt_init(ctx);
636             break;
637
638         case EVP_PKEY_OP_DECRYPT:
639             rv = EVP_PKEY_decrypt_init(ctx);
640             break;
641
642         case EVP_PKEY_OP_DERIVE:
643             rv = EVP_PKEY_derive_init(ctx);
644             break;
645         }
646     }
647
648     if (rv <= 0) {
649         EVP_PKEY_CTX_free(ctx);
650         ctx = NULL;
651     }
652
653  end:
654     OPENSSL_free(passin);
655     return ctx;
656
657 }
658
659 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
660                       ENGINE *e)
661 {
662     EVP_PKEY *peer = NULL;
663     ENGINE *engine = NULL;
664     int ret;
665
666     if (peerform == FORMAT_ENGINE)
667         engine = e;
668     peer = load_pubkey(file, peerform, 0, NULL, engine, "peer key");
669     if (peer == NULL) {
670         BIO_printf(bio_err, "Error reading peer key %s\n", file);
671         ERR_print_errors(bio_err);
672         return 0;
673     }
674
675     ret = EVP_PKEY_derive_set_peer(ctx, peer);
676
677     EVP_PKEY_free(peer);
678     if (ret <= 0)
679         ERR_print_errors(bio_err);
680     return ret;
681 }
682
683 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
684                     unsigned char *out, size_t *poutlen,
685                     const unsigned char *in, size_t inlen)
686 {
687     int rv = 0;
688     switch (pkey_op) {
689     case EVP_PKEY_OP_VERIFYRECOVER:
690         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
691         break;
692
693     case EVP_PKEY_OP_SIGN:
694         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
695         break;
696
697     case EVP_PKEY_OP_ENCRYPT:
698         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
699         break;
700
701     case EVP_PKEY_OP_DECRYPT:
702         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
703         break;
704
705     case EVP_PKEY_OP_DERIVE:
706         rv = EVP_PKEY_derive(ctx, out, poutlen);
707         break;
708
709     }
710     return rv;
711 }
712
713 #define TBUF_MAXSIZE 2048
714
715 static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx,
716                         EVP_PKEY *pkey, BIO *in,
717                         int filesize, unsigned char *sig, int siglen,
718                         unsigned char **out, size_t *poutlen)
719 {
720     int rv = 0;
721     unsigned char tbuf[TBUF_MAXSIZE];
722     unsigned char *mbuf = NULL;
723     int buf_len = 0;
724
725     /* Some algorithms only support oneshot digests */
726     if (EVP_PKEY_id(pkey) == EVP_PKEY_ED25519
727             || EVP_PKEY_id(pkey) == EVP_PKEY_ED448) {
728         if (filesize < 0) {
729             BIO_printf(bio_err,
730                        "Error: unable to determine file size for oneshot operation\n");
731             goto end;
732         }
733         mbuf = app_malloc(filesize, "oneshot sign/verify buffer");
734         switch(pkey_op) {
735         case EVP_PKEY_OP_VERIFY:
736             buf_len = BIO_read(in, mbuf, filesize);
737             if (buf_len != filesize) {
738                 BIO_printf(bio_err, "Error reading raw input data\n");
739                 goto end;
740             }
741             rv = EVP_DigestVerify(mctx, sig, (size_t)siglen, mbuf, buf_len);
742             break;
743         case EVP_PKEY_OP_SIGN:
744             buf_len = BIO_read(in, mbuf, filesize);
745             if (buf_len != filesize) {
746                 BIO_printf(bio_err, "Error reading raw input data\n");
747                 goto end;
748             }
749             rv = EVP_DigestSign(mctx, NULL, poutlen, mbuf, buf_len);
750             if (rv == 1 && out != NULL) {
751                 *out = app_malloc(*poutlen, "buffer output");
752                 rv = EVP_DigestSign(mctx, *out, poutlen, mbuf, buf_len);
753             }
754             break;
755         }
756         goto end;
757     }
758
759     switch(pkey_op) {
760     case EVP_PKEY_OP_VERIFY:
761         for (;;) {
762             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
763             if (buf_len == 0)
764                 break;
765             if (buf_len < 0) {
766                 BIO_printf(bio_err, "Error reading raw input data\n");
767                 goto end;
768             }
769             rv = EVP_DigestVerifyUpdate(mctx, tbuf, (size_t)buf_len);
770             if (rv != 1) {
771                 BIO_printf(bio_err, "Error verifying raw input data\n");
772                 goto end;
773             }
774         }
775         rv = EVP_DigestVerifyFinal(mctx, sig, (size_t)siglen);
776         break;
777     case EVP_PKEY_OP_SIGN:
778         for (;;) {
779             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
780             if (buf_len == 0)
781                 break;
782             if (buf_len < 0) {
783                 BIO_printf(bio_err, "Error reading raw input data\n");
784                 goto end;
785             }
786             rv = EVP_DigestSignUpdate(mctx, tbuf, (size_t)buf_len);
787             if (rv != 1) {
788                 BIO_printf(bio_err, "Error signing raw input data\n");
789                 goto end;
790             }
791         }
792         rv = EVP_DigestSignFinal(mctx, NULL, poutlen);
793         if (rv == 1 && out != NULL) {
794             *out = app_malloc(*poutlen, "buffer output");
795             rv = EVP_DigestSignFinal(mctx, *out, poutlen);
796         }
797         break;
798     }
799
800  end:
801     OPENSSL_free(mbuf);
802     return rv;
803 }