2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
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
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>
31 #define BSIZE (8*1024)
33 #define PBKDF2_ITER_DEFAULT 10000
34 #define STR(a) XSTR(a)
37 static int set_hex(const char *in, unsigned char *out, int size);
38 static void show_ciphers(const OBJ_NAME *name, void *bio_);
40 struct doall_enc_ciphers {
45 typedef enum OPTION_choice {
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
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"},
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"},
71 {"in", OPT_IN, '<', "Input file"},
72 {"k", OPT_K, 's', "Passphrase"},
73 {"kfile", OPT_KFILE, '<', "Read passphrase from file"},
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"},
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"},
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)"},
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"},
108 {"", OPT_CIPHER, '-', "Any supported cipher"},
115 int enc_main(int argc, char **argv)
117 static char buf[128];
118 static const char magic[] = "Salted__";
120 BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
122 EVP_CIPHER_CTX *ctx = NULL;
123 EVP_CIPHER *cipher = 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];
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];
144 struct doall_enc_ciphers dec;
145 #ifndef OPENSSL_NO_ZLIB
154 /* first check the command name */
155 if (strcmp(argv[0], "base64") == 0)
157 #ifndef OPENSSL_NO_ZLIB
158 else if (strcmp(argv[0], "zlib") == 0)
161 #ifndef OPENSSL_NO_BROTLI
162 else if (strcmp(argv[0], "brotli") == 0)
165 #ifndef OPENSSL_NO_ZSTD
166 else if (strcmp(argv[0], "zstd") == 0)
169 else if (strcmp(argv[0], "enc") != 0)
170 ciphername = argv[0];
172 opt_set_unknown_name("cipher");
173 prog = opt_init(argc, argv, enc_options);
174 while ((o = opt_next()) != OPT_EOF) {
179 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
182 opt_help(enc_options);
186 BIO_printf(bio_out, "Supported ciphers:\n");
189 OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
191 BIO_printf(bio_out, "\n");
207 e = setup_engine(opt_arg(), 0);
240 #ifndef OPENSSL_NO_ZLIB
246 i = (int)strlen(p) - 1;
247 k = i >= 1 && p[i] == 'k';
250 if (!opt_long(opt_arg(), &n)
251 || n < 0 || (k && n >= LONG_MAX / 1024))
261 in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT);
264 i = BIO_gets(in, buf, sizeof(buf));
269 "%s Can't read key from %s\n", prog, opt_arg());
272 while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n'))
275 BIO_printf(bio_err, "%s: zero length password\n", prog);
290 digestname = opt_arg();
293 ciphername = opt_unknown();
296 iter = opt_int_arg();
300 if (!opt_int(opt_arg(), &saltlen))
302 if (saltlen > (int)sizeof(salt))
303 saltlen = (int)sizeof(salt);
307 if (iter == 0) /* do not overwrite a chosen value */
308 iter = PBKDF2_ITER_DEFAULT;
318 if (!opt_provider(o))
324 /* No extra arguments. */
325 if (!opt_check_rest_arg(NULL))
327 if (!app_RAND_load())
329 if (saltlen == 0 || pbkdf2 == 0)
330 saltlen = PKCS5_SALT_LEN;
332 /* Get the cipher name, either from progname (if set) or flag. */
333 if (!opt_cipher(ciphername, &cipher))
335 if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE)) {
339 if (digestname != NULL) {
340 if (!opt_md(digestname, &dgst))
344 dgst = (EVP_MD *)EVP_sha256();
349 /* It must be large enough for a base64 encoded line */
350 if (base64 && bsize < 80)
353 BIO_printf(bio_err, "bufsize=%d\n", bsize);
355 #ifndef OPENSSL_NO_ZLIB
366 outformat = FORMAT_BASE64;
368 informat = FORMAT_BASE64;
371 strbuf = app_malloc(SIZE, "strbuf");
372 buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer");
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");
379 in = dup_bio_in(informat);
381 in = bio_open_default(infile, 'r', informat);
386 if (str == NULL && passarg != NULL) {
387 if (!app_passwd(passarg, NULL, &pass, NULL)) {
388 BIO_printf(bio_err, "Error getting password\n");
394 if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
396 #ifndef OPENSSL_NO_UI_CONSOLE
400 BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:",
401 EVP_CIPHER_get0_name(cipher),
402 (enc) ? "encryption" : "decryption");
404 i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc);
406 if (strbuf[0] == '\0') {
414 BIO_printf(bio_err, "bad password read\n");
420 BIO_printf(bio_err, "password required\n");
425 out = bio_open_default(outfile, 'w', outformat);
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);
439 #ifndef OPENSSL_NO_COMP
440 # ifndef OPENSSL_NO_ZLIB
442 if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
445 BIO_set_callback_ex(bzl, BIO_debug_callback_ex);
446 BIO_set_callback_arg(bzl, (char *)bio_err);
449 wbio = BIO_push(bzl, wbio);
451 rbio = BIO_push(bzl, rbio);
456 if ((bbrot = BIO_new(BIO_f_brotli())) == NULL)
459 BIO_set_callback_ex(bbrot, BIO_debug_callback_ex);
460 BIO_set_callback_arg(bbrot, (char *)bio_err);
463 wbio = BIO_push(bbrot, wbio);
465 rbio = BIO_push(bbrot, rbio);
469 if ((bzstd = BIO_new(BIO_f_zstd())) == NULL)
472 BIO_set_callback_ex(bzstd, BIO_debug_callback_ex);
473 BIO_set_callback_arg(bzstd, (char *)bio_err);
476 wbio = BIO_push(bzstd, wbio);
478 rbio = BIO_push(bzstd, rbio);
483 if ((b64 = BIO_new(BIO_f_base64())) == NULL)
486 BIO_set_callback_ex(b64, BIO_debug_callback_ex);
487 BIO_set_callback_arg(b64, (char *)bio_err);
490 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
492 wbio = BIO_push(b64, wbio);
494 rbio = BIO_push(b64, rbio);
497 if (cipher != NULL) {
498 if (str != NULL) { /* a passphrase is available */
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
505 size_t str_len = strlen(str);
510 if (hsalt != NULL && !set_hex(hsalt, salt, saltlen)) {
511 BIO_printf(bio_err, "invalid hex salt value\n");
514 if (enc) { /* encryption */
516 if (RAND_bytes(salt, saltlen) <= 0) {
517 BIO_printf(bio_err, "RAND_bytes failed\n");
521 * If -P option then don't bother writing.
522 * If salt is given, shouldn't either ?
525 && (BIO_write(wbio, magic,
526 sizeof(magic) - 1) != sizeof(magic) - 1
529 saltlen) != saltlen)) {
530 BIO_printf(bio_err, "error writing output file\n");
534 } else { /* decryption */
536 if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)) {
537 BIO_printf(bio_err, "error reading input file\n");
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");
546 } else { /* file is NOT salted, NO salt available */
547 BIO_printf(bio_err, "bad magic number\n");
557 * derive key and default iv
558 * concatenated into a temporary buffer
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);
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");
571 /* split and move data back to global buffer */
572 memcpy(key, tmpkeyiv, iklen);
573 memcpy(iv, tmpkeyiv+iklen, ivlen);
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,
581 BIO_printf(bio_err, "EVP_BytesToKey failed\n");
586 * zero the complete buffer or the string passed from the command
590 OPENSSL_cleanse(str, SIZE);
592 OPENSSL_cleanse(str, str_len);
595 int siz = EVP_CIPHER_get_iv_length(cipher);
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");
603 if ((hiv == NULL) && (str == NULL)
604 && EVP_CIPHER_get_iv_length(cipher) != 0
607 * No IV was explicitly set and no IV was generated.
608 * Hence the IV is undefined, making correct decryption impossible.
610 BIO_printf(bio_err, "iv undefined\n");
614 if (!set_hex(hkey, key, EVP_CIPHER_get_key_length(cipher))) {
615 BIO_printf(bio_err, "invalid hex key value\n");
618 /* wiping secret data as we no longer need it */
622 if ((benc = BIO_new(BIO_f_cipher())) == NULL)
626 * Since we may be changing parameters work on the encryption context
627 * rather than calling BIO_set_cipher().
630 BIO_get_cipher_ctx(benc, &ctx);
633 EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
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);
643 EVP_CIPHER_CTX_set_padding(ctx, 0);
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);
654 BIO_set_callback_ex(benc, BIO_debug_callback_ex);
655 BIO_set_callback_arg(benc, (char *)bio_err);
661 for (i = 0; i < (int)saltlen; i++)
662 printf("%02X", salt[i]);
665 if (EVP_CIPHER_get_key_length(cipher) > 0) {
667 for (i = 0; i < EVP_CIPHER_get_key_length(cipher); i++)
668 printf("%02X", key[i]);
671 if (EVP_CIPHER_get_iv_length(cipher) > 0) {
673 for (i = 0; i < EVP_CIPHER_get_iv_length(cipher); i++)
674 printf("%02X", iv[i]);
684 /* Only encrypt/decrypt as we write the file */
686 wbio = BIO_push(benc, wbio);
688 while (BIO_pending(rbio) || !BIO_eof(rbio)) {
689 inl = BIO_read(rbio, (char *)buff, bsize);
692 if (!streamable && !BIO_eof(rbio)) { /* do not output data */
693 BIO_printf(bio_err, "Unstreamable cipher mode\n");
696 if (BIO_write(wbio, (char *)buff, inl) != inl) {
697 BIO_printf(bio_err, "error writing output file\n");
703 if (!BIO_flush(wbio)) {
705 BIO_printf(bio_err, "bad encrypt\n");
707 BIO_printf(bio_err, "bad decrypt\n");
713 BIO_printf(bio_err, "bytes read : %8ju\n", BIO_number_read(in));
714 BIO_printf(bio_err, "bytes written: %8ju\n", BIO_number_written(out));
717 ERR_print_errors(bio_err);
718 OPENSSL_free(strbuf);
725 EVP_CIPHER_free(cipher);
726 #ifndef OPENSSL_NO_ZLIB
736 static void show_ciphers(const OBJ_NAME *name, void *arg)
738 struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg;
739 const EVP_CIPHER *cipher;
741 if (!islower((unsigned char)*name->name))
744 /* Filter out ciphers that we cannot use */
745 cipher = EVP_get_cipherbyname(name->name);
747 || (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
748 || EVP_CIPHER_get_mode(cipher) == EVP_CIPH_XTS_MODE)
751 BIO_printf(dec->bio, "-%-25s", name->name);
753 BIO_printf(dec->bio, "\n");
756 BIO_printf(dec->bio, " ");
759 static int set_hex(const char *in, unsigned char *out, int size)
767 BIO_printf(bio_err, "hex string is too long, ignoring excess\n");
768 n = i; /* ignore exceeding part */
770 BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n");
773 memset(out, 0, size);
774 for (i = 0; i < n; i++) {
775 j = (unsigned char)*in++;
777 BIO_printf(bio_err, "non-hex digit\n");
780 j = (unsigned char)OPENSSL_hexchar2int(j);
784 out[i / 2] = (j << 4);