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