1 /* SPDX-License-Identifier: GPL-2.0-or-later
2 * Copyright (C) 2022-2023 Eneas Ulir de Queiroz
11 const cipher_t
*get_default_cipher(void)
13 return EVP_aes_128_cbc();
17 static void print_ciphers(const OBJ_NAME
*name
,void *arg
) {
18 fprintf(arg
, "\t%s\n", name
->name
);
22 const cipher_t
*get_cipher_or_print_error(char *name
)
24 const EVP_CIPHER
*cipher
;
26 if ((cipher
= EVP_get_cipherbyname(name
)))
29 fprintf(stderr
, "Error: invalid cipher: %s.\n", name
);
31 fprintf(stderr
, "Supported ciphers: \n");
32 OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH
, print_ciphers
, stderr
);
37 int get_cipher_ivsize(const cipher_t
*cipher
)
39 return EVP_CIPHER_iv_length(cipher
);
42 int get_cipher_keysize(const cipher_t
*cipher
)
44 return EVP_CIPHER_key_length(cipher
);
47 ctx_t
*create_ctx(const cipher_t
*cipher
, const unsigned char *key
,
48 const unsigned char *iv
, int enc
, int padding
)
53 ctx
= EVP_CIPHER_CTX_new();
55 fprintf (stderr
, "Error: create_ctx: out of memory.\n");
58 ret
= EVP_CipherInit_ex(ctx
, cipher
, NULL
, key
, iv
, enc
);
60 fprintf(stderr
, "Error:EVP_CipherInit_ex: %d\n", ret
);
63 ret
= EVP_CIPHER_CTX_set_padding(ctx
, padding
);
65 fprintf(stderr
, "Error:EVP_CIPHER_CTX_set_padding: %d\n", ret
);
77 int do_crypt(FILE *infile
, FILE *outfile
, ctx_t
*ctx
)
79 unsigned char inbuf
[CRYPT_BUF_SIZE
];
80 unsigned char outbuf
[CRYPT_BUF_SIZE
+ EVP_MAX_BLOCK_LENGTH
];
85 inlen
= fread(inbuf
, 1, CRYPT_BUF_SIZE
, infile
);
88 ret
= EVP_CipherUpdate(ctx
, outbuf
, &outlen
, inbuf
, inlen
);
90 fprintf(stderr
, "Error: EVP_CipherUpdate: %d\n", ret
);
93 ret
= fwrite(outbuf
, 1, outlen
, outfile
);
95 fprintf(stderr
, "Error: CipherUpdate short write.\n");
99 ret
= EVP_CipherFinal_ex(ctx
, outbuf
, &outlen
);
101 fprintf(stderr
, "Error: EVP_CipherFinal: %d\n", ret
);
104 ret
= fwrite(outbuf
, 1, outlen
, outfile
);
106 fprintf(stderr
, "Error: CipherFinal short write.\n");
113 void free_ctx(ctx_t
*ctx
)
115 EVP_CIPHER_CTX_free(ctx
);