Added 'saltlen' option to the OpenSSL enc command line app.
[openssl.git] / apps / enc.c
1 /*
2  * Copyright 1995-2022 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 <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <limits.h>
14 #include "apps.h"
15 #include "progs.h"
16 #include <openssl/bio.h>
17 #include <openssl/err.h>
18 #include <openssl/evp.h>
19 #include <openssl/objects.h>
20 #include <openssl/x509.h>
21 #include <openssl/rand.h>
22 #include <openssl/pem.h>
23 #ifndef OPENSSL_NO_COMP
24 # include <openssl/comp.h>
25 #endif
26 #include <ctype.h>
27
28 #undef SIZE
29 #undef BSIZE
30 #define SIZE    (512)
31 #define BSIZE   (8*1024)
32
33 #define PBKDF2_ITER_DEFAULT     10000
34 #define STR(a) XSTR(a)
35 #define XSTR(a) #a
36
37 static int set_hex(const char *in, unsigned char *out, int size);
38 static void show_ciphers(const OBJ_NAME *name, void *bio_);
39
40 struct doall_enc_ciphers {
41     BIO *bio;
42     int n;
43 };
44
45 typedef enum OPTION_choice {
46     OPT_COMMON,
47     OPT_LIST,
48     OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V,
49     OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A,
50     OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE,
51     OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_PBKDF2, OPT_CIPHER,
52     OPT_SALTLEN, OPT_R_ENUM, OPT_PROV_ENUM
53 } OPTION_CHOICE;
54
55 const OPTIONS enc_options[] = {
56     OPT_SECTION("General"),
57     {"help", OPT_HELP, '-', "Display this summary"},
58     {"list", OPT_LIST, '-', "List ciphers"},
59 #ifndef OPENSSL_NO_DEPRECATED_3_0
60     {"ciphers", OPT_LIST, '-', "Alias for -list"},
61 #endif
62     {"e", OPT_E, '-', "Encrypt"},
63     {"d", OPT_D, '-', "Decrypt"},
64     {"p", OPT_P, '-', "Print the iv/key"},
65     {"P", OPT_UPPER_P, '-', "Print the iv/key and exit"},
66 #ifndef OPENSSL_NO_ENGINE
67     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
68 #endif
69
70     OPT_SECTION("Input"),
71     {"in", OPT_IN, '<', "Input file"},
72     {"k", OPT_K, 's', "Passphrase"},
73     {"kfile", OPT_KFILE, '<', "Read passphrase from file"},
74
75     OPT_SECTION("Output"),
76     {"out", OPT_OUT, '>', "Output file"},
77     {"pass", OPT_PASS, 's', "Passphrase source"},
78     {"v", OPT_V, '-', "Verbose output"},
79     {"a", OPT_A, '-', "Base64 encode/decode, depending on encryption flag"},
80     {"base64", OPT_A, '-', "Same as option -a"},
81     {"A", OPT_UPPER_A, '-',
82      "Used with -[base64|a] to specify base64 buffer as a single line"},
83
84     OPT_SECTION("Encryption"),
85     {"nopad", OPT_NOPAD, '-', "Disable standard block padding"},
86     {"salt", OPT_SALT, '-', "Use salt in the KDF (default)"},
87     {"nosalt", OPT_NOSALT, '-', "Do not use salt in the KDF"},
88     {"debug", OPT_DEBUG, '-', "Print debug info"},
89
90     {"bufsize", OPT_BUFSIZE, 's', "Buffer size"},
91     {"K", OPT_UPPER_K, 's', "Raw key, in hex"},
92     {"S", OPT_UPPER_S, 's', "Salt, in hex"},
93     {"iv", OPT_IV, 's', "IV in hex"},
94     {"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"},
95     {"iter", OPT_ITER, 'p',
96      "Specify the iteration count and force the use of PBKDF2"},
97     {OPT_MORE_STR, 0, 0, "Default: " STR(PBKDF2_ITER_DEFAULT)},
98     {"pbkdf2", OPT_PBKDF2, '-',
99      "Use password-based key derivation function 2 (PBKDF2)"},
100     {OPT_MORE_STR, 0, 0,
101      "Use -iter to change the iteration count from " STR(PBKDF2_ITER_DEFAULT)},
102     {"none", OPT_NONE, '-', "Don't encrypt"},
103     {"saltlen", OPT_SALTLEN, 'p', "Specify the PBKDF2 salt length (in bytes)"},
104     {OPT_MORE_STR, 0, 0, "Default: 16"},
105 #ifndef OPENSSL_NO_ZLIB
106     {"z", OPT_Z, '-', "Compress or decompress encrypted data using zlib"},
107 #endif
108     {"", OPT_CIPHER, '-', "Any supported cipher"},
109
110     OPT_R_OPTIONS,
111     OPT_PROV_OPTIONS,
112     {NULL}
113 };
114
115 int enc_main(int argc, char **argv)
116 {
117     static char buf[128];
118     static const char magic[] = "Salted__";
119     ENGINE *e = NULL;
120     BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
121         NULL, *wbio = NULL;
122     EVP_CIPHER_CTX *ctx = NULL;
123     EVP_CIPHER *cipher = NULL;
124     EVP_MD *dgst = NULL;
125     const char *digestname = NULL;
126     char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p;
127     char *infile = NULL, *outfile = NULL, *prog;
128     char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL;
129     const char *ciphername = NULL;
130     char mbuf[sizeof(magic) - 1];
131     OPTION_CHOICE o;
132     int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0;
133     int enc = 1, printkey = 0, i, k;
134     int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY;
135     int ret = 1, inl, nopad = 0;
136     unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
137     unsigned char *buff = NULL, salt[EVP_MAX_IV_LENGTH];
138     int saltlen = 0;
139     int pbkdf2 = 0;
140     int iter = 0;
141     long n;
142     int streamable = 1;
143     int wrap = 0;
144     struct doall_enc_ciphers dec;
145 #ifndef OPENSSL_NO_ZLIB
146     int do_zlib = 0;
147     BIO *bzl = NULL;
148 #endif
149     int do_brotli = 0;
150     BIO *bbrot = NULL;
151     int do_zstd = 0;
152     BIO *bzstd = NULL;
153
154     /* first check the command name */
155     if (strcmp(argv[0], "base64") == 0)
156         base64 = 1;
157 #ifndef OPENSSL_NO_ZLIB
158     else if (strcmp(argv[0], "zlib") == 0)
159         do_zlib = 1;
160 #endif
161 #ifndef OPENSSL_NO_BROTLI
162     else if (strcmp(argv[0], "brotli") == 0)
163         do_brotli = 1;
164 #endif
165 #ifndef OPENSSL_NO_ZSTD
166     else if (strcmp(argv[0], "zstd") == 0)
167         do_zstd = 1;
168 #endif
169     else if (strcmp(argv[0], "enc") != 0)
170         ciphername = argv[0];
171
172     opt_set_unknown_name("cipher");
173     prog = opt_init(argc, argv, enc_options);
174     while ((o = opt_next()) != OPT_EOF) {
175         switch (o) {
176         case OPT_EOF:
177         case OPT_ERR:
178  opthelp:
179             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
180             goto end;
181         case OPT_HELP:
182             opt_help(enc_options);
183             ret = 0;
184             goto end;
185         case OPT_LIST:
186             BIO_printf(bio_out, "Supported ciphers:\n");
187             dec.bio = bio_out;
188             dec.n = 0;
189             OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
190                                    show_ciphers, &dec);
191             BIO_printf(bio_out, "\n");
192             ret = 0;
193             goto end;
194         case OPT_E:
195             enc = 1;
196             break;
197         case OPT_IN:
198             infile = opt_arg();
199             break;
200         case OPT_OUT:
201             outfile = opt_arg();
202             break;
203         case OPT_PASS:
204             passarg = opt_arg();
205             break;
206         case OPT_ENGINE:
207             e = setup_engine(opt_arg(), 0);
208             break;
209         case OPT_D:
210             enc = 0;
211             break;
212         case OPT_P:
213             printkey = 1;
214             break;
215         case OPT_V:
216             verbose = 1;
217             break;
218         case OPT_NOPAD:
219             nopad = 1;
220             break;
221         case OPT_SALT:
222             nosalt = 0;
223             break;
224         case OPT_NOSALT:
225             nosalt = 1;
226             break;
227         case OPT_DEBUG:
228             debug = 1;
229             break;
230         case OPT_UPPER_P:
231             printkey = 2;
232             break;
233         case OPT_UPPER_A:
234             olb64 = 1;
235             break;
236         case OPT_A:
237             base64 = 1;
238             break;
239         case OPT_Z:
240 #ifndef OPENSSL_NO_ZLIB
241             do_zlib = 1;
242 #endif
243             break;
244         case OPT_BUFSIZE:
245             p = opt_arg();
246             i = (int)strlen(p) - 1;
247             k = i >= 1 && p[i] == 'k';
248             if (k)
249                 p[i] = '\0';
250             if (!opt_long(opt_arg(), &n)
251                     || n < 0 || (k && n >= LONG_MAX / 1024))
252                 goto opthelp;
253             if (k)
254                 n *= 1024;
255             bsize = (int)n;
256             break;
257         case OPT_K:
258             str = opt_arg();
259             break;
260         case OPT_KFILE:
261             in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT);
262             if (in == NULL)
263                 goto opthelp;
264             i = BIO_gets(in, buf, sizeof(buf));
265             BIO_free(in);
266             in = NULL;
267             if (i <= 0) {
268                 BIO_printf(bio_err,
269                            "%s Can't read key from %s\n", prog, opt_arg());
270                 goto opthelp;
271             }
272             while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n'))
273                 buf[i] = '\0';
274             if (i <= 0) {
275                 BIO_printf(bio_err, "%s: zero length password\n", prog);
276                 goto opthelp;
277             }
278             str = buf;
279             break;
280         case OPT_UPPER_K:
281             hkey = opt_arg();
282             break;
283         case OPT_UPPER_S:
284             hsalt = opt_arg();
285             break;
286         case OPT_IV:
287             hiv = opt_arg();
288             break;
289         case OPT_MD:
290             digestname = opt_arg();
291             break;
292         case OPT_CIPHER:
293             ciphername = opt_unknown();
294             break;
295         case OPT_ITER:
296             iter = opt_int_arg();
297             pbkdf2 = 1;
298             break;
299         case OPT_SALTLEN:
300             if (!opt_int(opt_arg(), &saltlen))
301                 goto opthelp;
302             if (saltlen > (int)sizeof(salt))
303                 saltlen = (int)sizeof(salt);
304             break;
305         case OPT_PBKDF2:
306             pbkdf2 = 1;
307             if (iter == 0)    /* do not overwrite a chosen value */
308                 iter = PBKDF2_ITER_DEFAULT;
309             break;
310         case OPT_NONE:
311             cipher = NULL;
312             break;
313         case OPT_R_CASES:
314             if (!opt_rand(o))
315                 goto end;
316             break;
317         case OPT_PROV_CASES:
318             if (!opt_provider(o))
319                 goto end;
320             break;
321         }
322     }
323
324     /* No extra arguments. */
325     if (!opt_check_rest_arg(NULL))
326         goto opthelp;
327     if (!app_RAND_load())
328         goto end;
329     if (saltlen == 0 || pbkdf2 == 0)
330         saltlen = PKCS5_SALT_LEN;
331
332     /* Get the cipher name, either from progname (if set) or flag. */
333     if (!opt_cipher(ciphername, &cipher))
334         goto opthelp;
335     if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE)) {
336         wrap = 1;
337         streamable = 0;
338     }
339     if (digestname != NULL) {
340         if (!opt_md(digestname, &dgst))
341             goto opthelp;
342     }
343     if (dgst == NULL)
344         dgst = (EVP_MD *)EVP_sha256();
345
346     if (iter == 0)
347         iter = 1;
348
349     /* It must be large enough for a base64 encoded line */
350     if (base64 && bsize < 80)
351         bsize = 80;
352     if (verbose)
353         BIO_printf(bio_err, "bufsize=%d\n", bsize);
354
355 #ifndef OPENSSL_NO_ZLIB
356     if (do_zlib)
357         base64 = 0;
358 #endif
359     if (do_brotli)
360         base64 = 0;
361     if (do_zstd)
362         base64 = 0;
363
364     if (base64) {
365         if (enc)
366             outformat = FORMAT_BASE64;
367         else
368             informat = FORMAT_BASE64;
369     }
370
371     strbuf = app_malloc(SIZE, "strbuf");
372     buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer");
373
374     if (infile == NULL) {
375         if (!streamable && printkey != 2) {  /* if just print key and exit, it's ok */
376             BIO_printf(bio_err, "Unstreamable cipher mode\n");
377             goto end;
378         }
379         in = dup_bio_in(informat);
380     } else {
381         in = bio_open_default(infile, 'r', informat);
382     }
383     if (in == NULL)
384         goto end;
385
386     if (str == NULL && passarg != NULL) {
387         if (!app_passwd(passarg, NULL, &pass, NULL)) {
388             BIO_printf(bio_err, "Error getting password\n");
389             goto end;
390         }
391         str = pass;
392     }
393
394     if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
395         if (1) {
396 #ifndef OPENSSL_NO_UI_CONSOLE
397             for (;;) {
398                 char prompt[200];
399
400                 BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:",
401                         EVP_CIPHER_get0_name(cipher),
402                         (enc) ? "encryption" : "decryption");
403                 strbuf[0] = '\0';
404                 i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc);
405                 if (i == 0) {
406                     if (strbuf[0] == '\0') {
407                         ret = 1;
408                         goto end;
409                     }
410                     str = strbuf;
411                     break;
412                 }
413                 if (i < 0) {
414                     BIO_printf(bio_err, "bad password read\n");
415                     goto end;
416                 }
417             }
418         } else {
419 #endif
420             BIO_printf(bio_err, "password required\n");
421             goto end;
422         }
423     }
424
425     out = bio_open_default(outfile, 'w', outformat);
426     if (out == NULL)
427         goto end;
428
429     if (debug) {
430         BIO_set_callback_ex(in, BIO_debug_callback_ex);
431         BIO_set_callback_ex(out, BIO_debug_callback_ex);
432         BIO_set_callback_arg(in, (char *)bio_err);
433         BIO_set_callback_arg(out, (char *)bio_err);
434     }
435
436     rbio = in;
437     wbio = out;
438
439 #ifndef OPENSSL_NO_COMP
440 # ifndef OPENSSL_NO_ZLIB
441     if (do_zlib) {
442         if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
443             goto end;
444         if (debug) {
445             BIO_set_callback_ex(bzl, BIO_debug_callback_ex);
446             BIO_set_callback_arg(bzl, (char *)bio_err);
447         }
448         if (enc)
449             wbio = BIO_push(bzl, wbio);
450         else
451             rbio = BIO_push(bzl, rbio);
452     }
453 # endif
454
455     if (do_brotli) {
456         if ((bbrot = BIO_new(BIO_f_brotli())) == NULL)
457             goto end;
458         if (debug) {
459             BIO_set_callback_ex(bbrot, BIO_debug_callback_ex);
460             BIO_set_callback_arg(bbrot, (char *)bio_err);
461         }
462         if (enc)
463             wbio = BIO_push(bbrot, wbio);
464         else
465             rbio = BIO_push(bbrot, rbio);
466     }
467
468     if (do_zstd) {
469         if ((bzstd = BIO_new(BIO_f_zstd())) == NULL)
470             goto end;
471         if (debug) {
472             BIO_set_callback_ex(bzstd, BIO_debug_callback_ex);
473             BIO_set_callback_arg(bzstd, (char *)bio_err);
474         }
475         if (enc)
476             wbio = BIO_push(bzstd, wbio);
477         else
478             rbio = BIO_push(bzstd, rbio);
479     }
480 #endif
481
482     if (base64) {
483         if ((b64 = BIO_new(BIO_f_base64())) == NULL)
484             goto end;
485         if (debug) {
486             BIO_set_callback_ex(b64, BIO_debug_callback_ex);
487             BIO_set_callback_arg(b64, (char *)bio_err);
488         }
489         if (olb64)
490             BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
491         if (enc)
492             wbio = BIO_push(b64, wbio);
493         else
494             rbio = BIO_push(b64, rbio);
495     }
496
497     if (cipher != NULL) {
498         if (str != NULL) { /* a passphrase is available */
499             /*
500              * Salt handling: if encrypting generate a salt if not supplied,
501              * and write to output BIO. If decrypting use salt from input BIO
502              * if not given with args
503              */
504             unsigned char *sptr;
505             size_t str_len = strlen(str);
506
507             if (nosalt) {
508                 sptr = NULL;
509             } else {
510                 if (hsalt != NULL && !set_hex(hsalt, salt, saltlen)) {
511                     BIO_printf(bio_err, "invalid hex salt value\n");
512                     goto end;
513                 }
514                 if (enc) {  /* encryption */
515                     if (hsalt == NULL) {
516                         if (RAND_bytes(salt, saltlen) <= 0) {
517                             BIO_printf(bio_err, "RAND_bytes failed\n");
518                             goto end;
519                         }
520                         /*
521                          * If -P option then don't bother writing.
522                          * If salt is given, shouldn't either ?
523                          */
524                         if ((printkey != 2)
525                             && (BIO_write(wbio, magic,
526                                           sizeof(magic) - 1) != sizeof(magic) - 1
527                                 || BIO_write(wbio,
528                                              (char *)salt,
529                                              saltlen) != saltlen)) {
530                             BIO_printf(bio_err, "error writing output file\n");
531                             goto end;
532                         }
533                     }
534                 } else {    /* decryption */
535                     if (hsalt == NULL) {
536                         if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)) {
537                             BIO_printf(bio_err, "error reading input file\n");
538                             goto end;
539                         }
540                         if (memcmp(mbuf, magic, sizeof(mbuf)) == 0) { /* file IS salted */
541                             if (BIO_read(rbio, salt,
542                                          saltlen) != saltlen) {
543                                 BIO_printf(bio_err, "error reading input file\n");
544                                 goto end;
545                             }
546                         } else { /* file is NOT salted, NO salt available */
547                             BIO_printf(bio_err, "bad magic number\n");
548                             goto end;
549                         }
550                     }
551                 }
552                 sptr = salt;
553             }
554
555             if (pbkdf2 == 1) {
556                 /*
557                 * derive key and default iv
558                 * concatenated into a temporary buffer
559                 */
560                 unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH];
561                 int iklen = EVP_CIPHER_get_key_length(cipher);
562                 int ivlen = EVP_CIPHER_get_iv_length(cipher);
563                 /* not needed if HASH_UPDATE() is fixed : */
564                 int islen = (sptr != NULL ? saltlen : 0);
565
566                 if (!PKCS5_PBKDF2_HMAC(str, str_len, sptr, islen,
567                                        iter, dgst, iklen+ivlen, tmpkeyiv)) {
568                     BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n");
569                     goto end;
570                 }
571                 /* split and move data back to global buffer */
572                 memcpy(key, tmpkeyiv, iklen);
573                 memcpy(iv, tmpkeyiv+iklen, ivlen);
574             } else {
575                 BIO_printf(bio_err, "*** WARNING : "
576                                     "deprecated key derivation used.\n"
577                                     "Using -iter or -pbkdf2 would be better.\n");
578                 if (!EVP_BytesToKey(cipher, dgst, sptr,
579                                     (unsigned char *)str, str_len,
580                                     1, key, iv)) {
581                     BIO_printf(bio_err, "EVP_BytesToKey failed\n");
582                     goto end;
583                 }
584             }
585             /*
586              * zero the complete buffer or the string passed from the command
587              * line.
588              */
589             if (str == strbuf)
590                 OPENSSL_cleanse(str, SIZE);
591             else
592                 OPENSSL_cleanse(str, str_len);
593         }
594         if (hiv != NULL) {
595             int siz = EVP_CIPHER_get_iv_length(cipher);
596             if (siz == 0) {
597                 BIO_printf(bio_err, "warning: iv not used by this cipher\n");
598             } else if (!set_hex(hiv, iv, siz)) {
599                 BIO_printf(bio_err, "invalid hex iv value\n");
600                 goto end;
601             }
602         }
603         if ((hiv == NULL) && (str == NULL)
604             && EVP_CIPHER_get_iv_length(cipher) != 0
605             && wrap == 0) {
606             /*
607              * No IV was explicitly set and no IV was generated.
608              * Hence the IV is undefined, making correct decryption impossible.
609              */
610             BIO_printf(bio_err, "iv undefined\n");
611             goto end;
612         }
613         if (hkey != NULL) {
614             if (!set_hex(hkey, key, EVP_CIPHER_get_key_length(cipher))) {
615                 BIO_printf(bio_err, "invalid hex key value\n");
616                 goto end;
617             }
618             /* wiping secret data as we no longer need it */
619             cleanse(hkey);
620         }
621
622         if ((benc = BIO_new(BIO_f_cipher())) == NULL)
623             goto end;
624
625         /*
626          * Since we may be changing parameters work on the encryption context
627          * rather than calling BIO_set_cipher().
628          */
629
630         BIO_get_cipher_ctx(benc, &ctx);
631
632         if (wrap == 1)
633             EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
634
635         if (!EVP_CipherInit_ex(ctx, cipher, e, NULL, NULL, enc)) {
636             BIO_printf(bio_err, "Error setting cipher %s\n",
637                        EVP_CIPHER_get0_name(cipher));
638             ERR_print_errors(bio_err);
639             goto end;
640         }
641
642         if (nopad)
643             EVP_CIPHER_CTX_set_padding(ctx, 0);
644
645         if (!EVP_CipherInit_ex(ctx, NULL, NULL, key,
646                                (hiv == NULL && wrap == 1 ? NULL : iv), enc)) {
647             BIO_printf(bio_err, "Error setting cipher %s\n",
648                        EVP_CIPHER_get0_name(cipher));
649             ERR_print_errors(bio_err);
650             goto end;
651         }
652
653         if (debug) {
654             BIO_set_callback_ex(benc, BIO_debug_callback_ex);
655             BIO_set_callback_arg(benc, (char *)bio_err);
656         }
657
658         if (printkey) {
659             if (!nosalt) {
660                 printf("salt=");
661                 for (i = 0; i < (int)saltlen; i++)
662                     printf("%02X", salt[i]);
663                 printf("\n");
664             }
665             if (EVP_CIPHER_get_key_length(cipher) > 0) {
666                 printf("key=");
667                 for (i = 0; i < EVP_CIPHER_get_key_length(cipher); i++)
668                     printf("%02X", key[i]);
669                 printf("\n");
670             }
671             if (EVP_CIPHER_get_iv_length(cipher) > 0) {
672                 printf("iv =");
673                 for (i = 0; i < EVP_CIPHER_get_iv_length(cipher); i++)
674                     printf("%02X", iv[i]);
675                 printf("\n");
676             }
677             if (printkey == 2) {
678                 ret = 0;
679                 goto end;
680             }
681         }
682     }
683
684     /* Only encrypt/decrypt as we write the file */
685     if (benc != NULL)
686         wbio = BIO_push(benc, wbio);
687
688     while (BIO_pending(rbio) || !BIO_eof(rbio)) {
689         inl = BIO_read(rbio, (char *)buff, bsize);
690         if (inl <= 0)
691             break;
692         if (!streamable && !BIO_eof(rbio)) {    /* do not output data */
693             BIO_printf(bio_err, "Unstreamable cipher mode\n");
694             goto end;
695         }
696         if (BIO_write(wbio, (char *)buff, inl) != inl) {
697             BIO_printf(bio_err, "error writing output file\n");
698             goto end;
699         }
700         if (!streamable)
701             break;
702     }
703     if (!BIO_flush(wbio)) {
704         BIO_printf(bio_err, "bad decrypt\n");
705         goto end;
706     }
707
708     ret = 0;
709     if (verbose) {
710         BIO_printf(bio_err, "bytes read   : %8ju\n", BIO_number_read(in));
711         BIO_printf(bio_err, "bytes written: %8ju\n", BIO_number_written(out));
712     }
713  end:
714     ERR_print_errors(bio_err);
715     OPENSSL_free(strbuf);
716     OPENSSL_free(buff);
717     BIO_free(in);
718     BIO_free_all(out);
719     BIO_free(benc);
720     BIO_free(b64);
721     EVP_MD_free(dgst);
722     EVP_CIPHER_free(cipher);
723 #ifndef OPENSSL_NO_ZLIB
724     BIO_free(bzl);
725 #endif
726     BIO_free(bbrot);
727     BIO_free(bzstd);
728     release_engine(e);
729     OPENSSL_free(pass);
730     return ret;
731 }
732
733 static void show_ciphers(const OBJ_NAME *name, void *arg)
734 {
735     struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg;
736     const EVP_CIPHER *cipher;
737
738     if (!islower((unsigned char)*name->name))
739         return;
740
741     /* Filter out ciphers that we cannot use */
742     cipher = EVP_get_cipherbyname(name->name);
743     if (cipher == NULL
744             || (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
745             || EVP_CIPHER_get_mode(cipher) == EVP_CIPH_XTS_MODE)
746         return;
747
748     BIO_printf(dec->bio, "-%-25s", name->name);
749     if (++dec->n == 3) {
750         BIO_printf(dec->bio, "\n");
751         dec->n = 0;
752     } else
753         BIO_printf(dec->bio, " ");
754 }
755
756 static int set_hex(const char *in, unsigned char *out, int size)
757 {
758     int i, n;
759     unsigned char j;
760
761     i = size * 2;
762     n = strlen(in);
763     if (n > i) {
764         BIO_printf(bio_err, "hex string is too long, ignoring excess\n");
765         n = i; /* ignore exceeding part */
766     } else if (n < i) {
767         BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n");
768     }
769
770     memset(out, 0, size);
771     for (i = 0; i < n; i++) {
772         j = (unsigned char)*in++;
773         if (!isxdigit(j)) {
774             BIO_printf(bio_err, "non-hex digit\n");
775             return 0;
776         }
777         j = (unsigned char)OPENSSL_hexchar2int(j);
778         if (i & 1)
779             out[i / 2] |= j;
780         else
781             out[i / 2] = (j << 4);
782     }
783     return 1;
784 }