SM4 optimization for ARM by HW instruction
[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_COMMON,
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;
115     int keyform = FORMAT_UNDEF, peerform = FORMAT_UNDEF;
116     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
117     int engine_impl = 0;
118     int ret = 1, rv = -1;
119     size_t buf_outlen;
120     const char *inkey = NULL;
121     const char *peerkey = NULL;
122     const char *kdfalg = NULL, *digestname = NULL;
123     int kdflen = 0;
124     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
125     STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
126     int rawin = 0;
127     EVP_MD_CTX *mctx = NULL;
128     EVP_MD *md = NULL;
129     int filesize = -1;
130     OSSL_LIB_CTX *libctx = app_get0_libctx();
131
132     prog = opt_init(argc, argv, pkeyutl_options);
133     while ((o = opt_next()) != OPT_EOF) {
134         switch (o) {
135         case OPT_EOF:
136         case OPT_ERR:
137  opthelp:
138             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
139             goto end;
140         case OPT_HELP:
141             opt_help(pkeyutl_options);
142             ret = 0;
143             goto end;
144         case OPT_IN:
145             infile = opt_arg();
146             break;
147         case OPT_OUT:
148             outfile = opt_arg();
149             break;
150         case OPT_SIGFILE:
151             sigfile = opt_arg();
152             break;
153         case OPT_ENGINE_IMPL:
154             engine_impl = 1;
155             break;
156         case OPT_INKEY:
157             inkey = opt_arg();
158             break;
159         case OPT_PEERKEY:
160             peerkey = opt_arg();
161             break;
162         case OPT_PASSIN:
163             passinarg = opt_arg();
164             break;
165         case OPT_PEERFORM:
166             if (!opt_format(opt_arg(), OPT_FMT_ANY, &peerform))
167                 goto opthelp;
168             break;
169         case OPT_KEYFORM:
170             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
171                 goto opthelp;
172             break;
173         case OPT_R_CASES:
174             if (!opt_rand(o))
175                 goto end;
176             break;
177         case OPT_CONFIG:
178             conf = app_load_config_modules(opt_arg());
179             if (conf == NULL)
180                 goto end;
181             break;
182         case OPT_PROV_CASES:
183             if (!opt_provider(o))
184                 goto end;
185             break;
186         case OPT_ENGINE:
187             e = setup_engine(opt_arg(), 0);
188             break;
189         case OPT_PUBIN:
190             key_type = KEY_PUBKEY;
191             break;
192         case OPT_CERTIN:
193             key_type = KEY_CERT;
194             break;
195         case OPT_ASN1PARSE:
196             asn1parse = 1;
197             break;
198         case OPT_HEXDUMP:
199             hexdump = 1;
200             break;
201         case OPT_SIGN:
202             pkey_op = EVP_PKEY_OP_SIGN;
203             break;
204         case OPT_VERIFY:
205             pkey_op = EVP_PKEY_OP_VERIFY;
206             break;
207         case OPT_VERIFYRECOVER:
208             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
209             break;
210         case OPT_ENCRYPT:
211             pkey_op = EVP_PKEY_OP_ENCRYPT;
212             break;
213         case OPT_DECRYPT:
214             pkey_op = EVP_PKEY_OP_DECRYPT;
215             break;
216         case OPT_DERIVE:
217             pkey_op = EVP_PKEY_OP_DERIVE;
218             break;
219         case OPT_KDF:
220             pkey_op = EVP_PKEY_OP_DERIVE;
221             key_type = KEY_NONE;
222             kdfalg = opt_arg();
223             break;
224         case OPT_KDFLEN:
225             kdflen = atoi(opt_arg());
226             break;
227         case OPT_REV:
228             rev = 1;
229             break;
230         case OPT_PKEYOPT:
231             if ((pkeyopts == NULL &&
232                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
233                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
234                 BIO_puts(bio_err, "out of memory\n");
235                 goto end;
236             }
237             break;
238         case OPT_PKEYOPT_PASSIN:
239             if ((pkeyopts_passin == NULL &&
240                  (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
241                 sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
242                 BIO_puts(bio_err, "out of memory\n");
243                 goto end;
244             }
245             break;
246         case OPT_RAWIN:
247             rawin = 1;
248             break;
249         case OPT_DIGEST:
250             digestname = opt_arg();
251             break;
252         }
253     }
254
255     /* No extra arguments. */
256     if (!opt_check_rest_arg(NULL))
257         goto opthelp;
258
259     if (!app_RAND_load())
260         goto end;
261
262     if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) {
263         BIO_printf(bio_err,
264                    "%s: -rawin can only be used with -sign or -verify\n",
265                    prog);
266         goto opthelp;
267     }
268
269     if (digestname != NULL && !rawin) {
270         BIO_printf(bio_err,
271                    "%s: -digest can only be used with -rawin\n",
272                    prog);
273         goto opthelp;
274     }
275
276     if (rawin && rev) {
277         BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n",
278                    prog);
279         goto opthelp;
280     }
281
282     if (kdfalg != NULL) {
283         if (kdflen == 0) {
284             BIO_printf(bio_err,
285                        "%s: no KDF length given (-kdflen parameter).\n", prog);
286             goto opthelp;
287         }
288     } else if (inkey == NULL) {
289         BIO_printf(bio_err,
290                    "%s: no private key given (-inkey parameter).\n", prog);
291         goto opthelp;
292     } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
293         BIO_printf(bio_err,
294                    "%s: no peer key given (-peerkey parameter).\n", prog);
295         goto opthelp;
296     }
297
298     if (rawin) {
299         if ((mctx = EVP_MD_CTX_new()) == NULL) {
300             BIO_printf(bio_err, "Error: out of memory\n");
301             goto end;
302         }
303     }
304     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
305                    passinarg, pkey_op, e, engine_impl, rawin, &pkey,
306                    mctx, digestname, libctx, app_get0_propq());
307     if (ctx == NULL) {
308         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
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         goto end;
314     }
315     if (pkeyopts != NULL) {
316         int num = sk_OPENSSL_STRING_num(pkeyopts);
317         int i;
318
319         for (i = 0; i < num; ++i) {
320             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
321
322             if (pkey_ctrl_string(ctx, opt) <= 0) {
323                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
324                            prog, opt);
325                 goto end;
326             }
327         }
328     }
329     if (pkeyopts_passin != NULL) {
330         int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
331         int i;
332
333         for (i = 0; i < num; i++) {
334             char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
335             char *passin = strchr(opt, ':');
336             char *passwd;
337
338             if (passin == NULL) {
339                 /* Get password interactively */
340                 char passwd_buf[4096];
341                 int r;
342
343                 BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
344                 r = EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
345                                        passwd_buf, 0);
346                 if (r < 0) {
347                     if (r == -2)
348                         BIO_puts(bio_err, "user abort\n");
349                     else
350                         BIO_puts(bio_err, "entry failed\n");
351                     goto end;
352                 }
353                 passwd = OPENSSL_strdup(passwd_buf);
354                 if (passwd == NULL) {
355                     BIO_puts(bio_err, "out of memory\n");
356                     goto end;
357                 }
358             } else {
359                 /* Get password as a passin argument: First split option name
360                  * and passphrase argument into two strings */
361                 *passin = 0;
362                 passin++;
363                 if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
364                     BIO_printf(bio_err, "failed to get '%s'\n", opt);
365                     goto end;
366                 }
367             }
368
369             if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
370                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
371                            prog, opt);
372                 goto end;
373             }
374             OPENSSL_free(passwd);
375         }
376     }
377
378     if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
379         BIO_printf(bio_err,
380                    "%s: Signature file specified for non verify\n", prog);
381         goto end;
382     }
383
384     if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
385         BIO_printf(bio_err,
386                    "%s: No signature file specified for verify\n", prog);
387         goto end;
388     }
389
390     if (pkey_op != EVP_PKEY_OP_DERIVE) {
391         in = bio_open_default(infile, 'r', FORMAT_BINARY);
392         if (infile != NULL) {
393             struct stat st;
394
395             if (stat(infile, &st) == 0 && st.st_size <= INT_MAX)
396                 filesize = (int)st.st_size;
397         }
398         if (in == NULL)
399             goto end;
400     }
401     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
402     if (out == NULL)
403         goto end;
404
405     if (sigfile != NULL) {
406         BIO *sigbio = BIO_new_file(sigfile, "rb");
407
408         if (sigbio == NULL) {
409             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
410             goto end;
411         }
412         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
413         BIO_free(sigbio);
414         if (siglen < 0) {
415             BIO_printf(bio_err, "Error reading signature data\n");
416             goto end;
417         }
418     }
419
420     /* Raw input data is handled elsewhere */
421     if (in != NULL && !rawin) {
422         /* Read the input data */
423         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
424         if (buf_inlen < 0) {
425             BIO_printf(bio_err, "Error reading input Data\n");
426             goto end;
427         }
428         if (rev) {
429             size_t i;
430             unsigned char ctmp;
431             size_t l = (size_t)buf_inlen;
432             for (i = 0; i < l / 2; i++) {
433                 ctmp = buf_in[i];
434                 buf_in[i] = buf_in[l - 1 - i];
435                 buf_in[l - 1 - i] = ctmp;
436             }
437         }
438     }
439
440     /* Sanity check the input if the input is not raw */
441     if (!rawin
442             && buf_inlen > EVP_MAX_MD_SIZE
443             && (pkey_op == EVP_PKEY_OP_SIGN
444                 || pkey_op == EVP_PKEY_OP_VERIFY)) {
445         BIO_printf(bio_err,
446                    "Error: The input data looks too long to be a hash\n");
447         goto end;
448     }
449
450     if (pkey_op == EVP_PKEY_OP_VERIFY) {
451         if (rawin) {
452             rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, sig, siglen,
453                               NULL, 0);
454         } else {
455             rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
456                                  buf_in, (size_t)buf_inlen);
457         }
458         if (rv == 1) {
459             BIO_puts(out, "Signature Verified Successfully\n");
460             ret = 0;
461         } else {
462             BIO_puts(out, "Signature Verification Failure\n");
463         }
464         goto end;
465     }
466     if (rawin) {
467         /* rawin allocates the buffer in do_raw_keyop() */
468         rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, NULL, 0,
469                           &buf_out, (size_t *)&buf_outlen);
470     } else {
471         if (kdflen != 0) {
472             buf_outlen = kdflen;
473             rv = 1;
474         } else {
475             rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
476                           buf_in, (size_t)buf_inlen);
477         }
478         if (rv > 0 && buf_outlen != 0) {
479             buf_out = app_malloc(buf_outlen, "buffer output");
480             rv = do_keyop(ctx, pkey_op,
481                           buf_out, (size_t *)&buf_outlen,
482                           buf_in, (size_t)buf_inlen);
483         }
484     }
485     if (rv <= 0) {
486         if (pkey_op != EVP_PKEY_OP_DERIVE) {
487             BIO_puts(bio_err, "Public Key operation error\n");
488         } else {
489             BIO_puts(bio_err, "Key derivation failed\n");
490         }
491         goto end;
492     }
493     ret = 0;
494
495     if (asn1parse) {
496         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
497             ERR_print_errors(bio_err); /* but still return success */
498     } else if (hexdump) {
499         BIO_dump(out, (char *)buf_out, buf_outlen);
500     } else {
501         BIO_write(out, buf_out, buf_outlen);
502     }
503
504  end:
505     if (ret != 0)
506         ERR_print_errors(bio_err);
507     EVP_MD_CTX_free(mctx);
508     EVP_PKEY_CTX_free(ctx);
509     EVP_MD_free(md);
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, keyform, "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_get_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         return 0;
672     }
673
674     ret = EVP_PKEY_derive_set_peer(ctx, peer) > 0;
675
676     EVP_PKEY_free(peer);
677     return ret;
678 }
679
680 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
681                     unsigned char *out, size_t *poutlen,
682                     const unsigned char *in, size_t inlen)
683 {
684     int rv = 0;
685     switch (pkey_op) {
686     case EVP_PKEY_OP_VERIFYRECOVER:
687         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
688         break;
689
690     case EVP_PKEY_OP_SIGN:
691         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
692         break;
693
694     case EVP_PKEY_OP_ENCRYPT:
695         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
696         break;
697
698     case EVP_PKEY_OP_DECRYPT:
699         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
700         break;
701
702     case EVP_PKEY_OP_DERIVE:
703         rv = EVP_PKEY_derive(ctx, out, poutlen);
704         break;
705
706     }
707     return rv;
708 }
709
710 #define TBUF_MAXSIZE 2048
711
712 static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx,
713                         EVP_PKEY *pkey, BIO *in,
714                         int filesize, unsigned char *sig, int siglen,
715                         unsigned char **out, size_t *poutlen)
716 {
717     int rv = 0;
718     unsigned char tbuf[TBUF_MAXSIZE];
719     unsigned char *mbuf = NULL;
720     int buf_len = 0;
721
722     /* Some algorithms only support oneshot digests */
723     if (EVP_PKEY_get_id(pkey) == EVP_PKEY_ED25519
724             || EVP_PKEY_get_id(pkey) == EVP_PKEY_ED448) {
725         if (filesize < 0) {
726             BIO_printf(bio_err,
727                        "Error: unable to determine file size for oneshot operation\n");
728             goto end;
729         }
730         mbuf = app_malloc(filesize, "oneshot sign/verify buffer");
731         switch (pkey_op) {
732         case EVP_PKEY_OP_VERIFY:
733             buf_len = BIO_read(in, mbuf, filesize);
734             if (buf_len != filesize) {
735                 BIO_printf(bio_err, "Error reading raw input data\n");
736                 goto end;
737             }
738             rv = EVP_DigestVerify(mctx, sig, (size_t)siglen, mbuf, buf_len);
739             break;
740         case EVP_PKEY_OP_SIGN:
741             buf_len = BIO_read(in, mbuf, filesize);
742             if (buf_len != filesize) {
743                 BIO_printf(bio_err, "Error reading raw input data\n");
744                 goto end;
745             }
746             rv = EVP_DigestSign(mctx, NULL, poutlen, mbuf, buf_len);
747             if (rv == 1 && out != NULL) {
748                 *out = app_malloc(*poutlen, "buffer output");
749                 rv = EVP_DigestSign(mctx, *out, poutlen, mbuf, buf_len);
750             }
751             break;
752         }
753         goto end;
754     }
755
756     switch (pkey_op) {
757     case EVP_PKEY_OP_VERIFY:
758         for (;;) {
759             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
760             if (buf_len == 0)
761                 break;
762             if (buf_len < 0) {
763                 BIO_printf(bio_err, "Error reading raw input data\n");
764                 goto end;
765             }
766             rv = EVP_DigestVerifyUpdate(mctx, tbuf, (size_t)buf_len);
767             if (rv != 1) {
768                 BIO_printf(bio_err, "Error verifying raw input data\n");
769                 goto end;
770             }
771         }
772         rv = EVP_DigestVerifyFinal(mctx, sig, (size_t)siglen);
773         break;
774     case EVP_PKEY_OP_SIGN:
775         for (;;) {
776             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
777             if (buf_len == 0)
778                 break;
779             if (buf_len < 0) {
780                 BIO_printf(bio_err, "Error reading raw input data\n");
781                 goto end;
782             }
783             rv = EVP_DigestSignUpdate(mctx, tbuf, (size_t)buf_len);
784             if (rv != 1) {
785                 BIO_printf(bio_err, "Error signing raw input data\n");
786                 goto end;
787             }
788         }
789         rv = EVP_DigestSignFinal(mctx, NULL, poutlen);
790         if (rv == 1 && out != NULL) {
791             *out = app_malloc(*poutlen, "buffer output");
792             rv = EVP_DigestSignFinal(mctx, *out, poutlen);
793         }
794         break;
795     }
796
797  end:
798     OPENSSL_free(mbuf);
799     return rv;
800 }