1 /* SPDX-License-Identifier: GPL-2.0-or-later
2 * Copyright (C) 2022-2023 Eneas Ulir de Queiroz
12 # include <wolfssl/options.h>
13 # include <wolfssl/openssl/evp.h>
15 # include <openssl/evp.h>
18 int do_crypt(FILE *infile
, FILE *outfile
, const EVP_CIPHER
*cipher
, const unsigned char *key
,
19 const unsigned char *iv
, int enc
, int padding
)
22 unsigned char inbuf
[1024], outbuf
[1024 + EVP_MAX_BLOCK_LENGTH
];
25 ctx
= EVP_CIPHER_CTX_new();
26 EVP_CipherInit_ex(ctx
, cipher
, NULL
, key
, iv
, enc
);
27 EVP_CIPHER_CTX_set_padding(ctx
, padding
);
30 inlen
= fread(inbuf
, 1, 1024, infile
);
33 if (!EVP_CipherUpdate(ctx
, outbuf
, &outlen
, inbuf
, inlen
)) {
34 EVP_CIPHER_CTX_free(ctx
);
37 fwrite(outbuf
, 1, outlen
, outfile
);
39 if (!EVP_CipherFinal_ex(ctx
, outbuf
, &outlen
)) {
40 EVP_CIPHER_CTX_free(ctx
);
43 fwrite(outbuf
, 1, outlen
, outfile
);
45 EVP_CIPHER_CTX_free(ctx
);
49 static void check_enc_dec(const int enc
)
53 fprintf(stderr
, "Error: both -d and -e were specified.\n");
58 static void print_ciphers(const OBJ_NAME
*name
,void *arg
) {
59 fprintf(arg
, "\t%s\n", name
->name
);
63 static void check_cipher(const EVP_CIPHER
*cipher
)
66 fprintf(stderr
, "Error: invalid cipher: %s.\n", optarg
);
68 fprintf(stderr
, "Supported ciphers: \n");
69 OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH
, print_ciphers
, stderr
);
75 static void show_usage(const char* name
)
77 fprintf(stderr
, "Usage: %s: [-d | -e] [-n] -k key [-i iv] [-c cipher]\n"
78 "-d = decrypt; -e = encrypt; -n = no padding\n", name
);
81 int main(int argc
, char *argv
[])
84 unsigned char *iv
= NULL
;
85 unsigned char *key
= NULL
;
86 long ivlen
= 0, keylen
= 0;
87 int cipher_ivlen
, cipher_keylen
;
90 const EVP_CIPHER
*cipher
= EVP_aes_128_cbc();
93 while ((opt
= getopt(argc
, argv
, "c:dei:k:n")) != -1) {
96 cipher
= EVP_get_cipherbyname(optarg
);
108 iv
= OPENSSL_hexstr2buf((const char *)optarg
, &ivlen
);
110 fprintf(stderr
, "Error setting IV to %s. The IV should be encoded in hex.\n",
116 key
= OPENSSL_hexstr2buf((const char *)optarg
, &keylen
);
118 fprintf(stderr
, "Error setting key to %s. The key should be encoded in hex.\n",
132 fprintf(stderr
, "Error: key not set.\n");
136 if ((cipher_keylen
= EVP_CIPHER_key_length(cipher
)) != keylen
) {
137 fprintf(stderr
, "Error: key must be %d bytes; given key is %ld bytes.\n",
138 cipher_keylen
, keylen
);
141 if ((cipher_ivlen
= EVP_CIPHER_iv_length(cipher
))) {
143 fprintf(stderr
, "Error: IV not set.\n");
147 if (cipher_ivlen
!= ivlen
) {
148 fprintf(stderr
, "Error: IV must be %d bytes; given IV is %ld bytes.\n",
149 cipher_ivlen
, ivlen
);
153 ret
= do_crypt(stdin
, stdout
, cipher
, key
, iv
, !!enc
, padding
);
155 fprintf(stderr
, "Error during crypt operation.\n");