EVP_ENCRYPTINIT(3ossl)
๐ EVP_ENCRYPTINIT(3ossl) ๐
okay bestie. deep breath. you just typed man on EVP_ENCRYPTINIT(3ossl) โ yes, that's the OpenSSL manual, section 3ossl โ and it is not a little page. it's a whole page. an iconic, sprawling, main-character page.
this is where OpenSSL keeps basically everything about EVP ciphers: fetching them, holding them, wrapping them in a context, feeding them your bytes, and asking them nosy questions about themselves. we're starting with the roll call, because the NAME section here is giving โจthe entire ensemble castโจ.
๐ NAME ๐
not me about to name-drop ninety-eight functions like it's nothing. iykyk. here's the whole squad, in order, no cap:
- the fetch + context lifecycle girlies:
EVP_CIPHER_fetch,EVP_CIPHER_up_ref,EVP_CIPHER_free,EVP_CIPHER_CTX_new,EVP_CIPHER_CTX_reset,EVP_CIPHER_CTX_free,EVP_CIPHER_CTX_dup,EVP_CIPHER_CTX_copy - the init/update/final crowd (the
_exand_ex2girlies plus their friends):EVP_EncryptInit_ex,EVP_EncryptInit_ex2,EVP_EncryptUpdate,EVP_EncryptFinal_ex,EVP_DecryptInit_ex,EVP_DecryptInit_ex2,EVP_DecryptUpdate,EVP_DecryptFinal_ex,EVP_CipherInit_ex,EVP_CipherInit_ex2,EVP_CipherInit_SKEY,EVP_CipherUpdate,EVP_CipherFinal_ex,EVP_CIPHER_CTX_set_key_length,EVP_CIPHER_CTX_ctrl - the no-
_exclassics:EVP_EncryptInit,EVP_EncryptFinal,EVP_DecryptInit,EVP_DecryptFinal,EVP_CipherInit,EVP_CipherFinal,EVP_Cipher - the pipeline crew ๐:
EVP_CIPHER_can_pipeline,EVP_CipherPipelineEncryptInit,EVP_CipherPipelineDecryptInit,EVP_CipherPipelineUpdate,EVP_CipherPipelineFinal - the "find me a cipher" lookups:
EVP_get_cipherbyname,EVP_get_cipherbynid,EVP_get_cipherbyobj - asking a cipher to introduce itself:
EVP_CIPHER_is_a,EVP_CIPHER_get0_name,EVP_CIPHER_get0_description,EVP_CIPHER_names_do_all,EVP_CIPHER_get0_provider,EVP_CIPHER_get_nid,EVP_CIPHER_get_params,EVP_CIPHER_gettable_params,EVP_CIPHER_get_block_size,EVP_CIPHER_get_key_length,EVP_CIPHER_get_iv_length,EVP_CIPHER_get_flags,EVP_CIPHER_get_mode,EVP_CIPHER_get_type - asking the context the same nosy questions:
EVP_CIPHER_CTX_cipher,EVP_CIPHER_CTX_get0_cipher,EVP_CIPHER_CTX_get1_cipher,EVP_CIPHER_CTX_get0_name,EVP_CIPHER_CTX_get_nid,EVP_CIPHER_CTX_get_params,EVP_CIPHER_gettable_ctx_params,EVP_CIPHER_CTX_gettable_params,EVP_CIPHER_CTX_set_params,EVP_CIPHER_settable_ctx_params,EVP_CIPHER_CTX_settable_params,EVP_CIPHER_CTX_get_block_size,EVP_CIPHER_CTX_get_key_length,EVP_CIPHER_CTX_get_iv_length,EVP_CIPHER_CTX_get_tag_length,EVP_CIPHER_CTX_flags,EVP_CIPHER_CTX_set_flags,EVP_CIPHER_CTX_clear_flags,EVP_CIPHER_CTX_test_flags,EVP_CIPHER_CTX_get_type,EVP_CIPHER_CTX_get_mode,EVP_CIPHER_CTX_get_num,EVP_CIPHER_CTX_set_num,EVP_CIPHER_CTX_is_encrypting - the ASN.1 + padding + null corner ๐ซถ:
EVP_CIPHER_param_to_asn1,EVP_CIPHER_asn1_to_param,EVP_CIPHER_CTX_set_padding,EVP_enc_null - and the do-all-the-things one:
EVP_CIPHER_do_all_provided - plus the
EVP_CIPHER_*andEVP_CIPHER_CTX_*name squad:EVP_CIPHER_nid,EVP_CIPHER_name,EVP_CIPHER_block_size,EVP_CIPHER_key_length,EVP_CIPHER_iv_length,EVP_CIPHER_flags,EVP_CIPHER_mode,EVP_CIPHER_type,EVP_CIPHER_CTX_encrypting,EVP_CIPHER_CTX_nid,EVP_CIPHER_CTX_block_size,EVP_CIPHER_CTX_key_length,EVP_CIPHER_CTX_iv_length,EVP_CIPHER_CTX_tag_length,EVP_CIPHER_CTX_num,EVP_CIPHER_CTX_type,EVP_CIPHER_CTX_mode
and the one-line vibe of the whole thing? EVP cipher routines. that's the tea. ๐
like i said, bestie, this page is long โ and we are nowhere near done. ๐
๐ SYNOPSIS ๐
okay bestie, deep breath, this is the whole shopping list of functions this page covers. it's a lot. it's giving "the entire Sephora aisle". but it's all here, untouched, exactly as it lives in the header ๐
#include <openssl/evp.h>
first up, the fetch / refcount / context-management girlies ๐:
EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
int EVP_CIPHER_up_ref(EVP_CIPHER *cipher);
void EVP_CIPHER_free(EVP_CIPHER *cipher);
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void);
int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx);
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx);
EVP_CIPHER_CTX *EVP_CIPHER_CTX_dup(const EVP_CIPHER_CTX *in);
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in);
the encrypt and decrypt duos โ _ex versions first because they're the main characters ๐:
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
const OSSL_PARAM params[]);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv);
int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
const OSSL_PARAM params[]);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
now the generic ones that can do either direction, plus the pipeline icons ๐ :
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc);
int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv,
int enc, const OSSL_PARAM params[]);
int EVP_CipherInit_SKEY(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
EVP_SKEY *skey, const unsigned char *iv, size_t iv_len,
int enc, const OSSL_PARAM params[]);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
and the legacy era versions, still living here rent-free ๐ซถ:
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv);
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv);
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *key, const unsigned char *iv, int enc);
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_Cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, unsigned int inl);
pipeline mode โ because doing one buffer at a time is so last season โจ:
int EVP_CIPHER_can_pipeline(const EVP_CIPHER *cipher, int enc);
int EVP_CipherPipelineEncryptInit(EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *cipher,
const unsigned char *key, size_t keylen,
size_t numpipes,
const unsigned char **iv, size_t ivlen);
int EVP_CipherPipelineDecryptInit(EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *cipher,
const unsigned char *key, size_t keylen,
size_t numpipes,
const unsigned char **iv, size_t ivlen);
int EVP_CipherPipelineUpdate(EVP_CIPHER_CTX *ctx,
unsigned char **out, size_t *outl,
const size_t *outsize,
const unsigned char **in, const size_t *inl);
int EVP_CipherPipelineFinal(EVP_CIPHER_CTX *ctx,
unsigned char **outm, size_t *outl,
const size_t *outsize);
knobs, dials and flags โ the control panel ๐๏ธ:
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *x, int padding);
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int cmd, int p1, void *p2);
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key);
void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags);
void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags);
int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags);
looking things up by name, nid or object ๐:
const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
const EVP_CIPHER *EVP_get_cipherbynid(int nid);
const EVP_CIPHER *EVP_get_cipherbyobj(const ASN1_OBJECT *a);
all the little getters for an EVP_CIPHER (nid, name, provider, sizes, flags, mode, type):
int EVP_CIPHER_get_nid(const EVP_CIPHER *e);
int EVP_CIPHER_is_a(const EVP_CIPHER *cipher, const char *name);
int EVP_CIPHER_names_do_all(const EVP_CIPHER *cipher,
void (*fn)(const char *name, void *data),
void *data);
const char *EVP_CIPHER_get0_name(const EVP_CIPHER *cipher);
const char *EVP_CIPHER_get0_description(const EVP_CIPHER *cipher);
const OSSL_PROVIDER *EVP_CIPHER_get0_provider(const EVP_CIPHER *cipher);
int EVP_CIPHER_get_block_size(const EVP_CIPHER *e);
int EVP_CIPHER_get_key_length(const EVP_CIPHER *e);
int EVP_CIPHER_get_iv_length(const EVP_CIPHER *e);
unsigned long EVP_CIPHER_get_flags(const EVP_CIPHER *e);
unsigned long EVP_CIPHER_get_mode(const EVP_CIPHER *e);
int EVP_CIPHER_get_type(const EVP_CIPHER *cipher);
and the same energy but for a context instead ๐:
const EVP_CIPHER *EVP_CIPHER_CTX_get0_cipher(const EVP_CIPHER_CTX *ctx);
EVP_CIPHER *EVP_CIPHER_CTX_get1_cipher(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_nid(const EVP_CIPHER_CTX *ctx);
const char *EVP_CIPHER_CTX_get0_name(const EVP_CIPHER_CTX *ctx);
params!! the OSSL_PARAM squad, settable/gettable and all ๐ฆ:
int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[]);
int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[]);
int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[]);
const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher);
const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *ctx);
const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_block_size(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_key_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_iv_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_tag_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_type(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_mode(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_get_num(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num);
int EVP_CIPHER_CTX_is_encrypting(const EVP_CIPHER_CTX *ctx);
the ASN.1 glue and the "list every cipher a provider has" walker ๐ถโโ๏ธ:
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_CIPHER *cipher, void *arg),
void *arg);
and finally, the macros โ lil aliases that just forward to the real functions, so don't be confused when you see both names in the wild ๐:
#define EVP_CIPHER_nid EVP_CIPHER_get_nid
#define EVP_CIPHER_name EVP_CIPHER_get0_name
#define EVP_CIPHER_block_size EVP_CIPHER_get_block_size
#define EVP_CIPHER_key_length EVP_CIPHER_get_key_length
#define EVP_CIPHER_iv_length EVP_CIPHER_get_iv_length
#define EVP_CIPHER_flags EVP_CIPHER_get_flags
#define EVP_CIPHER_mode EVP_CIPHER_get_mode
#define EVP_CIPHER_type EVP_CIPHER_get_type
#define EVP_CIPHER_CTX_encrypting EVP_CIPHER_CTX_is_encrypting
#define EVP_CIPHER_CTX_nid EVP_CIPHER_CTX_get_nid
#define EVP_CIPHER_CTX_block_size EVP_CIPHER_CTX_get_block_size
#define EVP_CIPHER_CTX_key_length EVP_CIPHER_CTX_get_key_length
#define EVP_CIPHER_CTX_iv_length EVP_CIPHER_CTX_get_iv_length
#define EVP_CIPHER_CTX_tag_length EVP_CIPHER_CTX_get_tag_length
#define EVP_CIPHER_CTX_num EVP_CIPHER_CTX_get_num
#define EVP_CIPHER_CTX_type EVP_CIPHER_CTX_get_type
#define EVP_CIPHER_CTX_mode EVP_CIPHER_CTX_get_mode
heads up bestie ๐ the next function is deprecated since OpenSSL 3.0, and you can hide it entirely by definingOPENSSL_API_COMPATwith a suitable version value, seeopenssl_user_macros(7):
const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx);
and this one? deprecated since OpenSSL 1.1.0 โ same deal, hide it entirely by definingOPENSSL_API_COMPATwith a suitable version value, seeopenssl_user_macros(7):
int EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx);
โจ DESCRIPTION โจ
so the EVP cipher routines are a high-level interface to certain symmetric ciphers. that's the whole vibe. they hold your hand so you don't have to rawdog the provider layer yourself ๐
the EVP_CIPHER type is a structure for cipher method implementation.
๐ซ EVP_CIPHER_fetch()
Fetches the cipher implementation for the given algorithm from any provider offering it, within the criteria given by the properties. See "ALGORITHM FETCHING" in crypto(7) for further information.
The returned value must eventually be freed with EVP_CIPHER_free().
Fetched EVP_CIPHER structures are reference counted. periodt.
๐ซ EVP_CIPHER_up_ref()
Increments the reference count for an EVP_CIPHER structure.
๐ซ EVP_CIPHER_free()
Decrements the reference count for the fetched EVP_CIPHER structure. If the reference count drops to 0 then the structure is freed. If the argument is NULL, nothing is done. (chill. no drama. it just vibes ๐ซถ)
๐ซ EVP_CIPHER_CTX_new()
Allocates and returns a cipher context.
๐ซ EVP_CIPHER_CTX_free()
Clears all information from a cipher context and frees any allocated memory associated with it, including ctx itself. This function should be called after all operations using a cipher are complete so sensitive information does not remain in memory. If the argument is NULL, nothing is done.
fr fr bestie, call this one. your keys don't need to be haunting the heap after the party's over ๐ญ
๐ซ EVP_CIPHER_CTX_dup()
Can be used to duplicate the cipher state from in. This is useful to avoid multiple EVP_CIPHER_fetch() calls or if large amounts of data are to be fed which only differ in the last few bytes.
๐ซ EVP_CIPHER_CTX_copy()
Can be used to copy the cipher state from in to out.
๐ซ EVP_CIPHER_CTX_ctrl()
This is a legacy method. EVP_CIPHER_CTX_set_params() and EVP_CIPHER_CTX_get_params() is the mechanism that should be used to set and get parameters that are used by providers.
So EVP_CIPHER_CTX_ctrl() does cipher-specific control actions on the context ctx. The control command is indicated in cmd, and any additional arguments are in p1 and p2. EVP_CIPHER_CTX_ctrl() must be called after EVP_CipherInit_ex2(). Other restrictions may apply depending on the control type and cipher implementation. No cap, that's the vibe. ๐
If this function happens to be used with a fetched EVP_CIPHER, it will translate the controls that are known to OpenSSL into OSSL_PARAM(3) parameters with keys defined by OpenSSL, and call EVP_CIPHER_CTX_get_params() or EVP_CIPHER_CTX_set_params() as is appropriate for each control command. It's giving translation era, lowkey iconic. โจ
See "CONTROLS" below for more information, including what translations are being done. ๐
EVP_CIPHER_get_params() ๐
Retrieves the requested list of algorithm params from a CIPHER cipher. See "PARAMETERS" below for more information. Params, but make it algorithm-level. ๐
EVP_CIPHER_CTX_get_params() ๐ฆ
Retrieves the requested list of params from CIPHER context ctx. See "PARAMETERS" below for more information. Context said gimme the params. ๐ธ
EVP_CIPHER_CTX_set_params() ๐
Sets the list of params into a CIPHER context ctx. See "PARAMETERS" below for more information. Set it and forget it, bestie. โจ
EVP_CIPHER_gettable_params() ๐ฅ
Get a constant OSSL_PARAM(3) array that describes the retrievable parameters that can be used with EVP_CIPHER_get_params(). It's the menu of what you can get. ๐
EVP_CIPHER_gettable_ctx_params() and EVP_CIPHER_CTX_gettable_params() ๐
Get a constant OSSL_PARAM(3) array that describes the retrievable parameters that can be used with EVP_CIPHER_CTX_get_params(). EVP_CIPHER_gettable_ctx_params() returns the parameters that can be retrieved from the algorithm, whereas EVP_CIPHER_CTX_gettable_params() returns the parameters that can be retrieved in the context's current state. Algorithm vs. context, they're different fr fr. ๐
EVP_CIPHER_settable_ctx_params() and EVP_CIPHER_CTX_settable_params() ๐ซถ
Get a constant OSSL_PARAM(3) array that describes the settable parameters that can be used with EVP_CIPHER_CTX_set_params(). EVP_CIPHER_settable_ctx_params() returns the parameters that can be set from the algorithm, whereas EVP_CIPHER_CTX_settable_params() returns the parameters that can be set in the context's current state. Same energy, but for setting. ๐
EVP_EncryptInit_ex2() ๐
Sets up cipher context ctx for encryption with cipher type. ctx MUST NOT be NULL. type is typically supplied by calling EVP_CIPHER_fetch(). type may also be set using legacy functions such as EVP_aes_256_cbc(), but this is not recommended for new applications. key is the symmetric key to use, and iv is the IV to use (if necessary); the actual number of bytes used for the key and IV depends on the cipher. The parameters params will be set on the context after initialisation. It is possible to set all parameters to NULL except type in an initial call and supply the remaining parameters in subsequent calls, all of which have type set to NULL. This is done when the default cipher parameters are not appropriate. For EVP_CIPH_GCM_MODE the IV will be generated internally if it is not specified. Encryption setup, but make it flexible. โจ
EVP_EncryptInit_ex() ๐
This legacy function is similar to EVP_EncryptInit_ex2() when impl is NULL. The implementation of the type from the impl engine will be used if it exists. Legacy, but still showing up. ๐
EVP_EncryptUpdate() ๐ฅ
Encrypts inl bytes from the buffer in and writes the encrypted version to out. The pointers out and in may point to the same location, in which case the encryption will be done in-place. However, in-place encryption is guaranteed to work only if the encryption context (ctx) has processed data in multiples of the block size. If the context contains an incomplete data block from previous operations, in-place encryption will fail. ctx MUST NOT be NULL. In-place is not always it, bestie. ๐ญ
If out and in point to different locations, the two buffers must be disjoint, otherwise the operation might fail or the outcome might be undefined. No overlapping, periodt. ๐
This function can be called multiple times to encrypt successive blocks of data. The amount of data written depends on the block alignment of the encrypted data. For most ciphers and modes, the amount of data written can be anything from zero bytes to (inl + cipher_block_size - 1) bytes. For wrap cipher modes, the amount of data written can be anything from zero bytes to (inl rounded up to cipher_block_size + cipher_block_size) bytes. For stream ciphers, the amount of data written can be anything from zero bytes to inl bytes. Thus, the buffer pointed to by out must contain sufficient room for the operation being performed. The actual number of bytes written is placed in outl. Buffer math is real, so leave room. ๐ง
If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts the "final" data, that is any data that remains in a partial block. It uses standard block padding (aka PKCS padding) as described in the NOTES section, below. The encrypted final data is written to out which should have sufficient space for one cipher block. The number of bytes written is placed in outl. After this function is called the encryption operation is finished and no further calls to EVP_EncryptUpdate() should be made. Final block era, don't touch it after. ๐
If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more data and it will return an error if any data remains in a partial block: that is if the total data length is not a multiple of the block size. No padding? Then partial blocks are a whole problem. โ ๏ธ
EVP_DecryptInit_ex2(), EVP_DecryptInit_ex(), EVP_DecryptUpdate() and EVP_DecryptFinal_ex() ๐
These functions are the corresponding decryption operations. EVP_DecryptFinal() will return an error code if padding is enabled and the final block is not correctly formatted. The parameters and restrictions are identical to the encryption operations. ctx MUST NOT be NULL. Decryption squad, same rules. ๐ซถ
EVP_CipherInit_ex2(), EVP_CipherInit_ex(), EVP_CipherUpdate() and EVP_CipherFinal_ex() ๐
These functions can be used for decryption or encryption. The operation performed depends on the value of the enc parameter. It should be set to 1 for encryption, 0 for decryption and -1 to leave the value unchanged (the actual value of enc being supplied in a previous call). enc is the switch, bestie. ๐
EVP_CipherInit_SKEY() ๐๏ธ
This function is similar to EVP_CipherInit_ex2() but accepts a symmetric key object of type EVP_SKEY as a key. SKEY key? Slay. โจ
EVP_CIPHER_CTX_reset() ๐งผ
Clears all information from a cipher context and free up any allocated memory associated with it, except the ctx itself. This function should be called anytime ctx is reused by another EVP_CipherInit() / EVP_CipherUpdate() / EVP_CipherFinal() series of calls. Reset before reuse, no cap. ๐ธ
EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit() ๐ฆ
Behave in a similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex() and EVP_CipherInit_ex() except if the type is not a fetched cipher they use the default implementation of the type. Not fetched? Default implementation steps in. ๐
EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal() ๐
Identical to EVP_EncryptFinal_ex(), EVP_DecryptFinal_ex() and EVP_CipherFinal_ex(). In previous releases they also cleaned up the ctx, but this is no longer done and EVP_CIPHER_CTX_cleanup() must be called to free any context resources. They used to clean up, but not anymore. Iconic behavior change. ๐
EVP_Cipher() ๐
Encrypts or decrypts a maximum inl amount of bytes from in and leaves the result in out. Max bytes, in to out. โจ
For legacy ciphers - If the cipher doesn't have the flag EVP_CIPH_FLAG_CUSTOM_CIPHER set, then inl must be a multiple of EVP_CIPHER_get_block_size(). If it isn't, the result is undefined. If the cipher has that flag set, then inl can be any size. Undefined behavior warning, bestie. ๐
Due to the constraints of the API contract of this function it shouldn't be used in applications, please consider using EVP_CipherUpdate() and EVP_CipherFinal_ex() instead. Don't use this in apps, fr fr. ๐
EVP_CIPHER_can_pipeline() ๐ฐ
This function checks if a EVP_CIPHER fetched using EVP_CIPHER_fetch() supports cipher pipelining. If the cipher supports pipelining, it returns 1, otherwise 0. This function will return 0 for non-fetched ciphers such as EVP_aes_128_gcm(). There are currently no built-in ciphers that support pipelining. Pipeline check: 1 if yes, 0 if no. ๐ฅ
Cipher pipelining support allows an application to submit multiple chunks of data in one set of EVP_CipherUpdate()/EVP_CipherFinal calls, thereby allowing the provided implementation to take advantage of parallel computing. This is beneficial for hardware accelerators as pipeline amortizes the latency over multiple chunks. Parallel chunks, hardware go brrr. โก
For non-fetched ciphers, EVP_CipherPipelineEncryptInit() or EVP_CipherPipelineDecryptInit() may be directly called, which will perform a fetch and return an error if a pipeline supported implementation is not found. Direct call will fetch for you. ๐
EVP_CipherPipelineEncryptInit(), EVP_CipherPipelineDecryptInit(), EVP_CipherPipelineUpdate() and EVP_CipherPipelineFinal() ๐
These functions can be used to perform multiple encryption or decryption operations in parallel. EVP_CIPHER_can_pipeline() may be called to check if the cipher supports pipelining. These functions are analogous to EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2(), EVP_CipherUpdate() and EVP_CipherFinal() but take an array of pointers for iv, input and output buffers. Pipeline squad, assemble. ๐
The key, of length keylen, is the symmetric key to use. The numpipes parameter specifies the number of parallel operations to perform. The numpipes cannot exceed EVP_MAX_PIPES. The iv parameter is an array of buffer pointers, containing IVs. The array size must be equal to numpipes. The size of each IV buffer must be equal to ivlen. When IV is not provided, iv must be NULL, rather than an array of NULL pointers. The in parameters takes an array of buffer pointers, each pointing to a buffer containing the input data. The buffers can be of different sizes. The inl parameter is an array of size_t, each specifying the size of the corresponding input buffer. The out and outm parameters are arrays of buffer pointers, each pointing to a buffer where the output data will be written. The outsize parameter is an array of size_t, each specifying the size of the corresponding output buffer. The outl parameter is an array of size_t which will be updated with the size of the output data written to the corresponding output buffer. For size requirement of the output buffers, see the description of EVP_CipherUpdate(). Arrays on arrays, but make it parallel. ๐
The EVP_CipherPipelineUpdate() function can be called multiple times to encrypt successive blocks of data. For AAD data, the out, and outsize parameter should be NULL, rather than an array of NULL pointers. AAD? Then NULL those out buffers. โจ
๐ EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj()
Bestie, these three are your little lookup besties. Pass one a cipher name, a cipher NID, or an ASN1_OBJECT structure respectively, and it hands you back an EVP_CIPHER structure. That's the whole vibe. ๐
Heads up:EVP_get_cipherbyname()will straight up returnNULLfor algorithms like"AES-128-SIV","AES-128-CBC-CTS"and"CAMELLIA-128-CBC-CTS"โ the ones that used to only be reachable through low level interfaces. Not a bug, just how it is. ๐ญ
The way that EVP_get_cipherbyname() exists is purely for backwards compatibility with OpenSSL prior to version 3, and it is different from the EVP_CIPHER_fetch() function because it does not attempt to "fetch" an implementation of the cipher. Also, it only knows about ciphers that are built-in to OpenSSL and that have an associated NID. Same energy for EVP_get_cipherbynid() and EVP_get_cipherbyobj() โ they also return objects without an associated implementation. ๐
So when you actually use the cipher objects these functions return (like, say, in a call to EVP_EncryptInit_ex()), an implementation of the cipher gets implicitly fetched from the loaded providers. And that fetch could fail if no suitable implementation is available. So instead, use EVP_CIPHER_fetch() to explicitly fetch the algorithm and an associated implementation from a provider. Do it on purpose, bestie, not by accident. โจ
Peep "ALGORITHM FETCHING" in crypto(7) for more info about fetching.
Good news: the cipher objects returned from these functions do not need to be freed with EVP_CIPHER_free(). Free real estate, no cleanup required. ๐ฆ
๐ EVP_CIPHER_get_nid() and EVP_CIPHER_CTX_get_nid()
These return the NID of a cipher when you pass them an EVP_CIPHER or EVP_CIPHER_CTX structure. The actual NID value is an internal value which may not have a corresponding OBJECT IDENTIFIER. And NID_undef gets returned in the event that the nid is unknown, or if the cipher has not been properly initialized via a call to EVP_CipherInit. ๐
๐ฉ EVP_CIPHER_CTX_set_flags(), EVP_CIPHER_CTX_clear_flags() and EVP_CIPHER_CTX_test_flags()
Sets, clears and tests ctx flags. See "FLAGS" below for more info, bestie. ๐
For provided ciphers,EVP_CIPHER_CTX_set_flags()should be called only after the fetched cipher has been assigned to thectx. And honestly, it is recommended to use "PARAMETERS" instead. ๐
๐๏ธ EVP_CIPHER_CTX_set_padding()
Enables or disables padding. This one should be called after the context is set up for encryption or decryption with EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2(), EVP_CipherInit_ex2(), or EVP_CipherInit_SKEY(). By default, encryption operations are padded using standard block padding, and that padding is checked and removed when decrypting. ๐ธ
If the pad parameter is zero then no padding is performed, and the total amount of data encrypted or decrypted must then be a multiple of the block size โ otherwise an error will occur. Also, x MUST NOT be NULL. No cap. ๐ซถ
๐ EVP_CIPHER_get_key_length() and EVP_CIPHER_CTX_get_key_length()
Return the key length of a cipher when you pass an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant EVP_MAX_KEY_LENGTH is the maximum key length for all ciphers. โจ
Note: althoughEVP_CIPHER_get_key_length()is fixed for a given cipher, the value ofEVP_CIPHER_CTX_get_key_length()may be different for variable key length ciphers. Variable length means variable, bestie. ๐ฆ
๐ง EVP_CIPHER_CTX_set_key_length()
Sets the key length of the cipher context. If the cipher is a fixed length cipher, then attempting to set the key length to any value other than the fixed value is an error. Periodt. ๐
๐ EVP_CIPHER_get_iv_length() and EVP_CIPHER_CTX_get_iv_length()
Return the IV length of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX. It will return zero if the cipher does not use an IV, if the cipher has not yet been initialized within the EVP_CIPHER_CTX, or if the passed cipher is NULL. The constant EVP_MAX_IV_LENGTH is the maximum IV length for all ciphers. ๐
๐ท๏ธ EVP_CIPHER_CTX_get_tag_length()
Returns the tag length of an AEAD cipher when passed a EVP_CIPHER_CTX. It will return zero if the cipher does not support a tag. And it returns a default value if the tag length has not been set. Default era, we love her. ๐
๐งฑ EVP_CIPHER_get_block_size() and EVP_CIPHER_CTX_get_block_size()
Return the block size of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant EVP_MAX_BLOCK_LENGTH is also the maximum block length for all ciphers. A value of 0 is returned if โ with EVP_CIPHER_get_block_size() โ the cipher e is NULL, or, with EVP_CIPHER_CTX_get_block_size(), the context ctx is NULL or has not been properly initialized with a call to EVP_CipherInit. ๐ซถ
๐ฎ EVP_CIPHER_get_type() and EVP_CIPHER_CTX_get_type()
Return the type of the passed cipher or context. This "type" is the actual NID of the cipher OBJECT IDENTIFIER, and as such it ignores the cipher parameters โ meaning 40 bit RC2 and 128 bit RC2 have the same NID, which is giving "same NID, different cipher" energy fr fr. ๐ If the cipher does not have an object identifier, or does not have ASN1 support, this function will return NID_undef.
๐งฌ EVP_CIPHER_is_a()
Returns 1 if cipher is an implementation of an algorithm that's identifiable with name, otherwise 0. If cipher is a legacy cipher (i.e. it's the return value from the likes of EVP_aes128() rather than the result of an EVP_CIPHER_fetch()), only cipher names registered with the default library context (see OSSL_LIB_CTX(3)) will be considered. iykyk. ๐ธ
๐ EVP_CIPHER_get0_name() and EVP_CIPHER_CTX_get0_name()
Return the name of the passed cipher or context. For fetched ciphers with multiple names, only one of them is returned. See also EVP_CIPHER_names_do_all(). And cipher MUST NOT be NULL. ๐
๐๏ธ EVP_CIPHER_names_do_all()
Traverses all names for the cipher, and calls fn with each name and data. This is only useful with fetched EVP_CIPHERs. All the names, one by one, iconic behaviour honestly. ๐
๐ EVP_CIPHER_get0_description()
Returns a description of the cipher, meant for display and human consumption. The description is at the discretion of the cipher implementation โ so whatever the implementation feels like saying, bestie. โจ
๐ EVP_CIPHER_get0_provider()
Returns an OSSL_PROVIDER pointer to the provider that implements the given EVP_CIPHER. Gotta know where your cipher lives. ๐ฆ
๐ EVP_CIPHER_CTX_get0_cipher()
Returns the EVP_CIPHER structure when passed an EVP_CIPHER_CTX structure. EVP_CIPHER_CTX_get1_cipher() is the same except the ownership is passed to the caller. Both functions return NULL on error. ๐ซถ
๐๏ธ EVP_CIPHER_get_mode() and EVP_CIPHER_CTX_get_mode()
Return the block cipher mode: EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE, EVP_CIPH_OFB_MODE, EVP_CIPH_CTR_MODE, EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE, EVP_CIPH_XTS_MODE, EVP_CIPH_WRAP_MODE, EVP_CIPH_OCB_MODE or EVP_CIPH_SIV_MODE. If the cipher is a stream cipher then EVP_CIPH_STREAM_CIPHER is returned. A whole menu of modes, we ate. ๐
๐ฉ EVP_CIPHER_get_flags()
Returns any flags associated with the cipher. See "FLAGS" for a list of currently defined flags. ๐
๐ข EVP_CIPHER_CTX_get_num() and EVP_CIPHER_CTX_set_num()
Gets or sets the cipher specific "num" parameter for the associated ctx. Built-in ciphers typically use this to track how much of the current underlying block has been "used" already. Just keeping count, bestie. โจ
๐ EVP_CIPHER_CTX_is_encrypting()
Reports whether the ctx is being used for encryption or decryption. Simple. Direct. We stan. ๐
๐ EVP_CIPHER_CTX_flags()
A deprecated macro calling "EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))". Do not use. Like, genuinely, do not. ๐
๐งพ EVP_CIPHER_param_to_asn1()
Sets the AlgorithmIdentifier "parameter" based on the passed cipher. This will typically include any parameters and an IV. The cipher IV (if any) must be set when this call is made. And this call should be made before the cipher is actually "used" โ so before any EVP_EncryptUpdate(), EVP_DecryptUpdate() calls, for example. ๐ซถ
This function may fail if the cipher does not have any ASN1 support, or if an uninitialized cipher is passed to it. No ASN1, no service. ๐ญ
๐ฅ EVP_CIPHER_asn1_to_param()
Sets the cipher parameters based on an ASN1 AlgorithmIdentifier "parameter". The precise effect depends on the cipher. In the case of RC2, for example, it will set the IV and effective key length. ๐ธ
This function should be called after the base cipher type is set but before the key is set. For example EVP_CipherInit() will be called with the IV and key set to NULL, EVP_CIPHER_asn1_to_param() will be called, and finally EVP_CipherInit() again with all parameters except the key set to NULL. It is possible for this function to fail if the cipher does not have any ASN1 support or the parameters cannot be set (for example the RC2 effective key length is not supported. ๐
๐ฒ EVP_CIPHER_CTX_rand_key()
Generates a random key of the appropriate length based on the cipher context. The EVP_CIPHER can provide its own random key generation routine to support keys of a specific form. key must point to a buffer at least as big as the value returned by EVP_CIPHER_CTX_get_key_length(). Don't skimp on the buffer, bestie. ๐
๐ EVP_CIPHER_do_all_provided()
Traverses all ciphers implemented by all activated providers in the given library context libctx, and for each of the implementations, calls the given function fn with the implementation method and the given arg as argument. Every single one of them, one by one. ๐
โ๏ธ PARAMETERS โ๏ธ
See OSSL_PARAM(3) for information about passing parameters. That's your homework, bestie. ๐
๐ Gettable EVP_CIPHER parameters ๐
When EVP_CIPHER_fetch() is called, it internally calls EVP_CIPHER_get_params() and caches the results. Sneaky but efficient. โจ
EVP_CIPHER_get_params() can be used with the following OSSL_PARAM(3) keys:
"mode"(OSSL_CIPHER_PARAM_MODE)<unsigned integer>โ Gets the mode for the associated cipher algorithmcipher. See "EVP_CIPHER_get_mode()andEVP_CIPHER_CTX_get_mode()" for a list of valid modes. UseEVP_CIPHER_get_mode()to retrieve the cached value. ๐๏ธ"keylen"(OSSL_CIPHER_PARAM_KEYLEN)<unsigned integer>โ Gets the key length for the associated cipher algorithmcipher. UseEVP_CIPHER_get_key_length()to retrieve the cached value. ๐"ivlen"(OSSL_CIPHER_PARAM_IVLEN)<unsigned integer>โ Gets the IV length for the associated cipher algorithmcipher. UseEVP_CIPHER_get_iv_length()to retrieve the cached value. ๐"blocksize"(OSSL_CIPHER_PARAM_BLOCK_SIZE)<unsigned integer>โ Gets the block size for the associated cipher algorithmcipher. The block size should be1for stream ciphers. Note that the block size for a cipher may be different to the block size for the underlying encryption/decryption primitive. For example AES in CTR mode has a block size of1(because it operates like a stream cipher), even though AES has a block size of16. UseEVP_CIPHER_get_block_size()to retrieve the cached value. ๐งฑ"aead"(OSSL_CIPHER_PARAM_AEAD)** <integer> โ bestie, this one gets you1if the cipher algorithm is an AEAD cipher, and0if it's not ๐ . Wanna grab the cached value yourself? Use(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)."custom-iv"(OSSL_CIPHER_PARAM_CUSTOM_IV)** <integer> โ gets1if the cipher algorithm cipher has a custom IV, otherwise0. When a custom IV is in play, storing and initializing the IV is left entirely to the implementation, no cap ๐ซถ. Cached value lives at(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_CUSTOM_IV)."cts"(OSSL_CIPHER_PARAM_CTS)** <integer> โ gets1if the cipher algorithm cipher uses ciphertext stealing, else0. rn this is used to flag that the cipher is a one shot that only allows a single call toEVP_CipherUpdate()๐. Cached value:(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_CTS)."tls-multi"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK)** <integer> โ gets1if the cipher algorithm cipher supports interleaving of crypto blocks, otherwise0. The interleaving is an optimization only, and it only applies to certain TLS ciphers โจ. Cached value:(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)."has-randkey"(OSSL_CIPHER_PARAM_HAS_RANDKEY)** <integer> โ gets1if the cipher algorithm cipher supports the gettableEVP_CIPHER_CTXparameterOSSL_CIPHER_PARAM_RANDOM_KEY. Heads up: only DES and 3DES set this to1, every other OpenSSL cipher returns0๐."decrypt-only"(OSSL_CIPHER_PARAM_DECRYPT_ONLY)** <integer> โ gets1if the cipher algorithm cipher implementation supports only the decryption operation, like the 3DES ciphers in the fips provider. Otherwise it gets0โ or the parameter might not be present at all ๐คทโโ๏ธ.
๐ Gettable and Settable EVP_CIPHER_CTX parameters ๐
The following OSSL_PARAM(3) keys can be used with both EVP_CIPHER_CTX_get_params() and EVP_CIPHER_CTX_set_params() ๐.
"padding"(OSSL_CIPHER_PARAM_PADDING)** <unsigned integer> โ gets or sets the padding mode for the cipher context ctx. Padding is enabled if the value is1, and disabled if the value is0๐. See alsoEVP_CIPHER_CTX_set_padding()."num"(OSSL_CIPHER_PARAM_NUM)** <unsigned integer> โ gets or sets the cipher specific"num"parameter for the cipher context ctx. Built-in ciphers typically use this to track how much of the current underlying block has been"used"already ๐ง. See alsoEVP_CIPHER_CTX_get_num()andEVP_CIPHER_CTX_set_num()."keylen"(OSSL_CIPHER_PARAM_KEYLEN)** <unsigned integer> โ gets or sets the key length for the cipher context ctx. The length of the"keylen"parameter should not exceed that of asize_t. See alsoEVP_CIPHER_CTX_get_key_length()andEVP_CIPHER_CTX_set_key_length()."tag"(OSSL_CIPHER_PARAM_AEAD_TAG)** <octet string> โ gets or sets the AEAD tag for the associated cipher context ctx. See"AEAD INTERFACE"inEVP_EncryptInit(3)๐."pipeline-tag"(OSSL_CIPHER_PARAM_PIPELINE_AEAD_TAG)** <octet ptr> โ gets or sets the AEAD tag when you're using cipher pipelining. The pointer must point to an array of buffers, where the aead tag will be read from or written to ๐ฅ๐ค. The array size must be equal to numpipes used inEVP_CipherPipelineEncryptInit()orEVP_CipherPipelineDecryptInit()."keybits"(OSSL_CIPHER_PARAM_RC2_KEYBITS)** <unsigned integer> โ gets or sets the effective keybits used for a RC2 cipher. The length of the"keybits"parameter should not exceed that of asize_t."rounds"(OSSL_CIPHER_PARAM_ROUNDS)** <unsigned integer> โ gets or sets the number of rounds to be used for a cipher. This one is used by the RC5 cipher ๐."algorithm-id"(OSSL_CIPHER_PARAM_ALGORITHM_ID)** <octet string> โ used to get the DER encodedAlgorithmIdentifierfrom the cipher implementation. Functions likeEVP_PKEY_CTX_get_algor(3)use this parameter."algorithm-id-params"(OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS)** <octet string> โ used to pass the DER encodedAlgorithmIdentifierparameter to or from the cipher implementation. Functions likeEVP_CIPHER_CTX_set_algor_params(3)andEVP_CIPHER_CTX_get_algor_params(3)use this parameter โจ."alg_id_params"(OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS_OLD)** <octet string> โ an deprecated alias for"algorithm-id-params", only used byEVP_CIPHER_param_to_asn1(3)andEVP_CIPHER_asn1_to_param(3)โ ๏ธ (yeah bestie, deprecated, tread lightly)."cts_mode"(OSSL_CIPHER_PARAM_CTS_MODE)** <UTF8 string> โ gets or sets the cipher text stealing mode. For all modes the output size is the same as the input size, and the input length must be greater than or equal to the block size ๐. (The block size for AES and CAMELLIA is 16 bytes.)
Valid values for the mode are:
"CS1"โ the NIST variant of cipher text stealing. For input lengths that are multiples of the block size it is equivalent to using a"AES-XXX-CBC"or"CAMELLIA-XXX-CBC"cipher, otherwise the second last cipher text block is a partial block ๐ธ."CS2"โ for input lengths that are multiples of the block size it is equivalent to using a"AES-XXX-CBC"or"CAMELLIA-XXX-CBC"cipher, otherwise it is the same as"CS3"mode."CS3"โ the Kerberos5 variant of cipher text stealing, which always swaps the last cipher text block with the previous block (which may be a partial or full block depending on the input length) ๐. If the input length is exactly one full block then this is equivalent to using a"AES-XXX-CBC"or"CAMELLIA-XXX-CBC"cipher.
The default is "CS1" ๐. This is only supported for "AES-128-CBC-CTS", "AES-192-CBC-CTS", "AES-256-CBC-CTS", "CAMELLIA-128-CBC-CTS", "CAMELLIA-192-CBC-CTS" and "CAMELLIA-256-CBC-CTS".
"tls1multi_interleave"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE)** <unsigned integer> โ sets or gets the number of records being sent in one go for a tls1 multiblock cipher operation (either4or8records) ๐ฆ.
๐ฆ Gettable EVP_CIPHER_CTX parameters ๐ฆ
The following OSSL_PARAM(3) keys can be used with EVP_CIPHER_CTX_get_params():
"ivlen"(OSSL_CIPHER_PARAM_IVLENand<OSSL_CIPHER_PARAM_AEAD_IVLEN)** <unsigned integer> โ gets the IV length for the cipher context ctx. The length of the"ivlen"parameter should not exceed that of asize_t. See alsoEVP_CIPHER_CTX_get_iv_length()."iv"(OSSL_CIPHER_PARAM_IV)** <octet string OR octet ptr> โ gets the IV used to initialize the associated cipher context ctx ๐ . See alsoEVP_CIPHER_CTX_get_original_iv()."updated-iv"(OSSL_CIPHER_PARAM_UPDATED_IV)** <octet string OR octet ptr> โ gets the updated pseudo-IV state for the associated cipher context, e.g., the previous ciphertext block for CBC mode, or the iteratively encrypted IV value for OFB mode ๐. Ngl, octet pointer access is deprecated and is provided only for backwards compatibility with historical libcrypto APIs ๐ฉ. See alsoEVP_CIPHER_CTX_get_updated_iv()."randkey"(OSSL_CIPHER_PARAM_RANDOM_KEY)** <octet string> โ gets an implementation specific randomly generated key for the associated cipher context ctx. rn this is only supported by DES and 3DES (which set the key to odd parity) ๐ฒ."taglen"(OSSL_CIPHER_PARAM_AEAD_TAGLEN)** <unsigned integer> โ gets the tag length to be used for an AEAD cipher for the associated cipher context ctx. It gets a default value if it has not been set. The length of the"taglen"parameter should not exceed that of asize_t. See alsoEVP_CIPHER_CTX_get_tag_length()."tlsaadpad"(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD)** <unsigned integer> โ gets the length of the tag that will be added to a TLS record for the AEAD tag for the associated cipher context ctx. The length of the"tlsaadpad"parameter should not exceed that of asize_t."tlsivgen"(OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN)** <octet string> โ gets the invocation field generated for encryption. Can only be called after"tlsivfixed"is set ๐ซถ. This is only used for GCM mode."tls1multi_enclen"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN)** <unsigned integer> โ get the total length of the record returned from the"tls1multi_enc"operation."tls1multi_maxbufsz"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE)** <unsigned integer> โ gets the maximum record length for a TLS1 multiblock cipher operation. The length of the"tls1multi_maxbufsz"parameter should not exceed that of asize_t."tls1multi_aadpacklen"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN)** <unsigned integer> โ gets the result of running the"tls1multi_aad"operation."tls-mac"(OSSL_CIPHER_PARAM_TLS_MAC)** <octet ptr> โ used to pass the TLS MAC data ๐."fips-indicator"(OSSL_CIPHER_PARAM_FIPS_APPROVED_INDICATOR)** <integer> โ this option is used by the OpenSSL FIPS provider.
It's a getter that returns 1 if the operation is FIPS approved, or 0 otherwise โ
. This may be used after calling a cipher final operation such as EVP_EncryptFinal_ex(). It may return 0 if the "encrypt-check" option is set to 0. For GCM encryption it also returns 0 if the IV was supplied externally instead of being generated by the FIPS provider ๐. The separate "iv-generated" parameter reports the IV source directly, but callers can use "fips-indicator" to determine the overall approval status. For GCM encryption and decryption, tag lengths other than 4, 8, or 12 through 16 bytes also cause this indicator to return 0 ๐.
"iv-generated"(OSSL_CIPHER_PARAM_AEAD_IV_GENERATED)** <unsigned integer> โ an indicator that returns1if an IV was generated internally during encryption, or0otherwise ๐. This may be used by GCM ciphers after calling a cipher final operation such asEVP_EncryptFinal_ex(). GCM should generate an IV internally if the IV is not specified during a cipher initialisation call such asEVP_CipherInit_ex(). See FIPS 140-3 IG C.H for information related to IV requirements ๐.
๐ธ Settable EVP_CIPHER_CTX parameters ๐ธ
The following OSSL_PARAM(3) keys can be used with EVP_CIPHER_CTX_set_params():
"mackey"(OSSL_CIPHER_PARAM_AEAD_MAC_KEY)** <octet string> โ sets the MAC key used by composite AEAD ciphers such asAES-CBC-HMAC-SHA256๐."speed"(OSSL_CIPHER_PARAM_SPEED)** <unsigned integer> โ sets the speed option for the associated cipher context. This is only supported by AES SIV ciphers, which disallow multiple operations by default ๐ซ. Setting"speed"to1allows another encrypt or decrypt operation to be performed. This is used for performance testing โก."use-bits"(OSSL_CIPHER_PARAM_USE_BITS) <unsigned integer> โ okay so this one decides whether thatinlinput length you hand toEVP_EncryptUpdate(),EVP_DecryptUpdate()andEVP_CipherUpdate()is counting bits or bytes. Set"use-bits"to1and you're counting bits. The default is bytes. Heads up: this only does anything for CFB1 ciphers. You can set it withEVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)."tls-version"(OSSL_CIPHER_PARAM_TLS_VERSION) <integer> โ Sets the TLS version. that's it bestie, she's simple ๐"tls-mac-size"(OSSL_CIPHER_PARAM_TLS_MAC_SIZE) <unsigned integer> โ Set the TLS MAC size."tlsaad"(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD) <octet string> โ Sets TLSv1.2 AAD info for the associated cipher contextctx. And ngl, TLSv1.2 AAD information is always 13 bytes in length, defined exactly as the"additional_data"field described in section 6.2.3.3 of RFC5246. โจ"tlsivfixed"(OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED) <octet string> โ Sets the fixed portion of an IV for an AEAD cipher being used in TLS record encryption/decryption for the associated cipher context.
TLS record encryption/decryption always happens "in place", so the input and output buffers are always the same memory location, periodt. AEAD IVs in TLSv1.2 are made of an implicit "fixed" part plus an explicit part that changes with every single record. Setting a TLS fixed IV flips a cipher into encrypt/decrypt-TLS-records mode.
TLS records get encrypted/decrypted using a single OSSL_FUNC_cipher_cipher call per record. For a record decryption, the first bytes of the input buffer will be the explicit part of the IV and the final bytes of the input buffer will be the AEAD tag. How long that explicit IV part is and how long the tag is depends on the cipher in use and gets defined in the RFC for the relevant ciphersuite. To allow for "in place" decryption, the plaintext output should be written to the same location in the output buffer that the ciphertext payload was read from, i.e. immediately after the explicit IV.
When encrypting a record, the first bytes of the input buffer should be empty to leave space for the explicit IV, same for the final bytes where the tag will be written. The length of the input buffer will include the length of the explicit IV, the payload, and the tag bytes. The cipher implementation should generate the explicit IV and write it to the beginning of the output buffer, do "in place" encryption of the payload and write that to the output buffer, and finally add the tag onto the end of the output buffer.
Whether you're encrypting or decrypting, the value written to *outl in the OSSL_FUNC_cipher_cipher call should be the length of the payload excluding the explicit IV length and the tag length. ๐
"tlsivinv"(OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV) <octet string> โ Sets the invocation field used for decryption. Can only be called after"tlsivfixed"is set. And it's only used for GCM mode."tls1multi_enc"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC) <octet string> โ Triggers a multiblock TLS1 encrypt operation for a TLS1-aware cipher that supports sending 4 or 8 records in one go. The cipher does both the MAC and encrypt stages and builds the record headers itself."tls1multi_enc"supplies the output buffer for the encrypt operation, and"tls1multi_encin"&"tls1multi_interleave"must also be set to supply values to the encrypt operation."tls1multi_encin"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN) <octet string> โ Supplies the data to encrypt for a TLS1 multiblock cipher operation."tls1multi_maxsndfrag"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT) <unsigned integer> โ Sets the maximum send fragment size for a TLS1 multiblock cipher operation. It must be set before using"tls1multi_maxbufsz". The length of the"tls1multi_maxsndfrag"parameter should not exceed that of asize_t."tls1multi_aad"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD) <octet string> โ Sets the authenticated additional data used by a TLS1 multiblock cipher operation. The supplied data is 13 bytes of record data containing:- Bytes 0-7: The sequence number of the first record
- Byte 8: The record type
- Bytes 9-10: The protocol version
- Bytes 11-12: Input length (Always 0)
"tls1multi_interleave" must also be set for this operation, don't forget her ๐ซถ
"xts_standard"(OSSL_CIPHER_PARAM_XTS_STANDARD) <UTF8 string> โ Sets the XTS standard to use with the SM4-XTS algorithm. XTS mode has two implementations: one is standardized in IEEE Std. 1619-2007 and has been widely used (e.g., XTS AES), and the other was proposed more recently (GB/T 17964-2021, implemented in May 2022) and is currently only used in SM4.
The main difference between them is the multiplication by the primitive element ฮฑ used to calculate the tweak values. The IEEE Std 1619-2007 noted that the multiplication "is a left shift of each byte by one bit with carry propagating from one byte to the next one", which means that in each byte, the leftmost bit is the most significant bit. But in GB/T 17964-2021, the rightmost bit is the most significant bit, so the multiplication becomes a right shift of each byte by one bit with carry propagating from one byte to the next one. iconic attention to detail tbh ๐ง
Valid values for the mode are:
"GB"โ The GB/T 17964-2021 variant of SM4-XTS algorithm."IEEE"โ The IEEE Std. 1619-2007 variant of SM4-XTS algorithm.
The default value is "GB".
"encrypt-check"(OSSL_CIPHER_PARAM_FIPS_ENCRYPT_CHECK) <integer> โ This option is used by the OpenSSL FIPS provider.
If required, this parameter should be set early via a cipher encrypt init function such as EVP_EncryptInit_ex2(). The default value of 1 causes an error when an encryption operation is triggered. Setting this to 0 will ignore the error and set the approved "fips-indicator" to 0.
โ ๏ธ Careful bestie โ this option breaks FIPS compliance if it causes the approved"fips-indicator"to return0. ๐
๐๏ธ CONTROLS ๐๏ธ
The mappings from EVP_CIPHER_CTX_ctrl() identifiers over to PARAMETERS are listed in the section below, so like, peek at the "PARAMETERS" section for more deets. โจ
EVP_CIPHER_CTX_ctrl() can be used to send the following standard controls:
EVP_CTRL_AEAD_SET_IVLENandEVP_CTRL_GET_IVLENโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()andEVP_CIPHER_CTX_get_params()get called with anOSSL_PARAM(3)item whose key is"ivlen"(OSSL_CIPHER_PARAM_IVLEN).EVP_CTRL_AEAD_SET_IV_FIXEDโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"tlsivfixed"(OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED).EVP_CTRL_AEAD_SET_MAC_KEYโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"mackey"(OSSL_CIPHER_PARAM_AEAD_MAC_KEY).EVP_CTRL_AEAD_SET_TAGandEVP_CTRL_AEAD_GET_TAGโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()andEVP_CIPHER_CTX_get_params()get called with anOSSL_PARAM(3)item whose key is"tag"(OSSL_CIPHER_PARAM_AEAD_TAG).EVP_CTRL_CCM_SET_Lโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"ivlen"(OSSL_CIPHER_PARAM_IVLEN) with a value of(15 - L).EVP_CTRL_COPYโ there is noOSSL_PARAMmapping for this one. UseEVP_CIPHER_CTX_copy()instead. ๐ซถEVP_CTRL_GCM_SET_IV_INVโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"tlsivinv"(OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV).EVP_CTRL_RAND_KEYโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"randkey"(OSSL_CIPHER_PARAM_RANDOM_KEY).EVP_CTRL_SET_KEY_LENGTHโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"keylen"(OSSL_CIPHER_PARAM_KEYLEN).EVP_CTRL_SET_RC2_KEY_BITSandEVP_CTRL_GET_RC2_KEY_BITSโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()andEVP_CIPHER_CTX_get_params()get called with anOSSL_PARAM(3)item whose key is"keybits"(OSSL_CIPHER_PARAM_RC2_KEYBITS).EVP_CTRL_SET_RC5_ROUNDSandEVP_CTRL_GET_RC5_ROUNDSโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()andEVP_CIPHER_CTX_get_params()get called with anOSSL_PARAM(3)item whose key is"rounds"(OSSL_CIPHER_PARAM_ROUNDS).EVP_CTRL_SET_SPEEDโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"speed"(OSSL_CIPHER_PARAM_SPEED).EVP_CTRL_GCM_IV_GENโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_get_params()gets called with anOSSL_PARAM(3)item whose key is"tlsivgen"(OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN).EVP_CTRL_AEAD_TLS1_AADโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key is"tlsaad"(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD) followed byEVP_CIPHER_CTX_get_params()with a key of"tlsaadpad"(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD).EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZEโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called with anOSSL_PARAM(3)item whose key isOSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT, followed byEVP_CIPHER_CTX_get_params()with a key of"tls1multi_maxbufsz"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE).EVP_CTRL_TLS1_1_MULTIBLOCK_AADโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called withOSSL_PARAM(3)items whose keys are"tls1multi_aad"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD) and"tls1multi_interleave"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE), followed byEVP_CIPHER_CTX_get_params()with keys of"tls1multi_aadpacklen"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN) and"tls1multi_interleave"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE).EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPTโ when used with a fetchedEVP_CIPHER,EVP_CIPHER_CTX_set_params()gets called withOSSL_PARAM(3)items whose keys are"tls1multi_enc"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC),"tls1multi_encin"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN) and"tls1multi_interleave"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE), followed byEVP_CIPHER_CTX_get_params()with a key of"tls1multi_enclen"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN).
๐ฉ FLAGS ๐ฉ
okay so EVP_CIPHER_CTX_set_flags(), EVP_CIPHER_CTX_clear_flags() and EVP_CIPHER_CTX_test_flags() are the trio that let you set, unset, and vibe-check these EVP_CIPHER_CTX flags ๐
EVP_CIPH_NO_PADDINGโ used byEVP_CIPHER_CTX_set_padding().
Also peep "Gettable and Settable EVP_CIPHER_CTX parameters" โ "padding" ๐
EVP_CIPH_FLAG_LENGTH_BITSโ see "Settable EVP_CIPHER_CTX parameters" โ "use-bits".EVP_CIPHER_CTX_FLAG_WRAP_ALLOWโ used for Legacy purposes only, fr. This flag needed to be set to indicate the cipher handled wrapping.
Then EVP_CIPHER_flags() uses the following flags, and these ones have mappings to "Gettable EVP_CIPHER parameters":
EVP_CIPH_FLAG_AEAD_CIPHERโ see "Gettable EVP_CIPHER parameters" โ "aead".EVP_CIPH_CUSTOM_IVโ see "Gettable EVP_CIPHER parameters" โ "custom-iv".EVP_CIPH_FLAG_CTSโ see "Gettable EVP_CIPHER parameters" โ "cts".EVP_CIPH_FLAG_TLS1_1_MULTIBLOCKโ see "Gettable EVP_CIPHER parameters" โ "tls-multi".EVP_CIPH_RAND_KEYโ see "Gettable EVP_CIPHER parameters" โ "has-randkey".
And EVP_CIPHER_flags() uses these next ones for legacy purposes only, so like, don't be building your whole personality on them ๐
EVP_CIPH_VARIABLE_LENGTHEVP_CIPH_FLAG_CUSTOM_CIPHEREVP_CIPH_ALWAYS_CALL_INITEVP_CIPH_CTRL_INITEVP_CIPH_CUSTOM_KEY_LENGTHEVP_CIPH_CUSTOM_COPYEVP_CIPH_FLAG_DEFAULT_ASN1
See EVP_CIPHER_meth_set_flags(3) for further information related to the above flags ๐ซถ
๐ซ RETURN VALUES ๐ซ
okay this bit is the receipts, bestie โ literally every single thing these functions hand back, no skips ๐งพ
EVP_CIPHER_fetch()returns a pointer to aEVP_CIPHERfor success andNULLfor failure.EVP_CIPHER_up_ref()returns 1 for success or 0 otherwise.EVP_CIPHER_CTX_new()returns a pointer to a newly createdEVP_CIPHER_CTXfor success andNULLfor failure.EVP_CIPHER_CTX_dup()returns a newEVP_CIPHER_CTXif successful orNULLon failure.EVP_CIPHER_CTX_copy()returns 1 if successful or 0 for failure.EVP_EncryptInit_ex2(),EVP_EncryptUpdate()andEVP_EncryptFinal_ex()return 1 for success and 0 for failure.EVP_DecryptInit_ex2()andEVP_DecryptUpdate()return 1 for success and 0 for failure.EVP_DecryptFinal_ex()returns 0 if the decrypt failed or 1 for success.EVP_CipherInit_ex2(),EVP_CipherInit_SKEY()andEVP_CipherUpdate()return 1 for success and 0 for failure.EVP_CipherFinal_ex()returns 0 for an encryption/decryption failure or 1 for success.EVP_Cipher()returns 1 on success and <= 0 on failure, if the flagEVP_CIPH_FLAG_CUSTOM_CIPHERis not set for the cipher, or if the cipher has not been initialized via a call toEVP_CipherInit_ex2.EVP_Cipher()returns the number of bytes written to out for encryption/decryption, or the number of bytes authenticated in a call specifying AAD for an AEAD cipher, if the flagEVP_CIPH_FLAG_CUSTOM_CIPHERis set for the cipher. ๐EVP_CIPHER_can_pipeline()returns 1 if the cipher can be used in a pipeline, 0 otherwise.EVP_CipherPipelineEncryptInit()andEVP_CipherPipelineDecryptInit()return 1 for success and 0 for failure.EVP_CipherPipelineUpdate()andEVP_CipherPipelineFinal()return 1 for success and 0 for failure.EVP_CIPHER_CTX_reset()returns 1 for success and 0 for failure.EVP_get_cipherbyname(),EVP_get_cipherbynid()andEVP_get_cipherbyobj()return anEVP_CIPHERstructure orNULLon error.EVP_CIPHER_get_nid()andEVP_CIPHER_CTX_get_nid()return a NID.EVP_CIPHER_get_block_size()andEVP_CIPHER_CTX_get_block_size()return the block size, or 0 on error.EVP_CIPHER_get_key_length()andEVP_CIPHER_CTX_get_key_length()return the key length.EVP_CIPHER_CTX_set_padding()always returns 1. (iconic, no notes โจ)EVP_CIPHER_get_iv_length()andEVP_CIPHER_CTX_get_iv_length()return the IV length, zero if the cipher does not use an IV and a negative value on error.EVP_CIPHER_CTX_get_tag_length()return the tag length or zero if the cipher does not use a tag.EVP_CIPHER_get_type()andEVP_CIPHER_CTX_get_type()return the NID of the cipher's OBJECT IDENTIFIER orNID_undefif it has no defined OBJECT IDENTIFIER.EVP_CIPHER_CTX_cipher()returns anEVP_CIPHERstructure.EVP_CIPHER_CTX_get_num()returns a nonnegative num value orEVP_CTRL_RET_UNSUPPORTEDif the implementation does not support the call or on any other error.EVP_CIPHER_CTX_set_num()returns 1 on success and 0 if the implementation does not support the call or on any other error.EVP_CIPHER_CTX_is_encrypting()returns 1 if the ctx is set up for encryption 0 otherwise.EVP_CIPHER_param_to_asn1()andEVP_CIPHER_asn1_to_param()return greater than zero for success and zero or a negative number on failure.EVP_CIPHER_CTX_rand_key()returns 1 for success and zero or a negative number for failure.EVP_CIPHER_names_do_all()returns 1 if the callback was called for all names. A return value of 0 means that the callback was not called for any names.EVP_CIPHER_get_params(),EVP_CIPHER_CTX_get_params()andEVP_CIPHER_CTX_set_params()return 1 for success and 0 for failure.
๐ CIPHER LISTING ๐
All algorithms have a fixed key length unless otherwise stated, okay? ๐
Refer to "SEE ALSO" for the full list of ciphers available through the EVP interface ๐
EVP_enc_null()โ Null cipher: does nothing. Literally nothing. It's the "I'm just here to exist" of ciphers ๐
๐ธ ๐ฆ ๐ ๐ซถ ๐
๐ฆ AEAD INTERFACE ๐ฆ
okay bestie so this is where it gets spicy ๐ Authenticated Encryption with Associated Data (AEAD) modes? The EVP interface for those is subtly altered, and there are several extra ctrl operations you get depending on which mode you picked. no cap.
So to hand over some additional authenticated data (AAD), you call EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() and set the output parameter out to NULL. When that works, the parameter outl gets set to the number of AAD bytes processed in that call โ literally just the value of inl โ and it does not include any plaintext or ciphertext bytes processed by other calls. slay.
If you're not using any AAD, you can just skip this call entirely, no biggie. (Check the mode-specific notes below for any exceptions tho ๐)
When you're decrypting, the return value of EVP_DecryptFinal() or EVP_CipherFinal() is what tells you if it actually worked. If it doesn't say success? the authentication operation has FAILED and any output data MUST NOT be used, because it is corrupted. periodt. do not touch it. ๐
Also pls note that the number of authenticated bytes returned by EVP_CipherUpdate() depends on the cipher you're using. Stream ciphers, like ChaCha20 or ciphers in GCM mode, can handle 1 byte at a time, which gives you an effective "block" size of 1. Meanwhile ciphers in OCB mode have to process data one block at a time, and that block size is what gets returned.
Regardless of whatever size comes back, it is safe to pass unpadded data to an EVP_CipherUpdate() call in a single operation. ๐ซถ
โจ GCM and OCB Modes โจ
These ctrls are supported in GCM and OCB modes:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)โ sets the IV length. You can only make this call before specifying an IV. If you don't call it, a default IV length gets used instead. For GCM AES and OCB AES the default is12(i.e. 96 bits). For OCB mode the maximum is15.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)โ writestaglenbytes of the tag value into the buffer thattagpoints at. You can only make this call when encrypting data and after all the data has been processed (like, after anEVP_EncryptFinal()call). For OCB,taglenmust either be16or the value you previously set viaEVP_CTRL_AEAD_SET_TAG.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)โ when decrypting, this sets the expected tag totaglenbytes fromtag.taglenmust be between1and16inclusive. The tag has to be set before any call toEVP_DecryptFinal()orEVP_DecryptFinal_ex(). For GCM, this call is only valid when decrypting data. For OCB, this call is valid when decrypting data (to set the expected tag) and when encrypting (to set the desired tag length). In OCB mode, calling this withtagset toNULLsets the tag length. The tag length can only be set before specifying an IV. If you don't call this before setting the IV, a default tag length is used. For OCB AES, the default tag length is16(i.e. 128 bits). That's also the maximum tag length for OCB.
๐ธ CCM Mode ๐ธ
The EVP interface for CCM mode is similar to the one for GCM mode, except it has a few extra requirements and different ctrl values. lowkey more demanding, highkey worth it.
For CCM mode, the total plaintext or ciphertext length MUST be passed to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output and input parameters (in and out) set to NULL, and the length passed in the inl parameter.
The following ctrls are supported in CCM mode:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)โ you make this call to set the expected CCM tag value when decrypting, or to set the length of the tag (with thetagparameter set toNULL) when encrypting. The tag length is often calledM. If you don't set it, a default value is used (12for AES). When decrypting, the tag needs to be set before passing in data to be decrypted, but just like in GCM and OCB mode, it can be set after passing additional authenticated data (see "AEAD INTERFACE" above ๐).EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, ivlen, NULL)โ sets the CCMLvalue. If you don't set it, a default is used (8for AES).EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)โ sets the CCM nonce (IV) length. You can only make this call before specifying a nonce value. The nonce length is given by15 - L, so it's7by default for AES.
๐ SIV Mode ๐
Both the AES-SIV and AES-GCM-SIV ciphers fall under this mode, bestie. ๐
For SIV mode ciphers, the behaviour of the EVP interface is subtly altered and several additional ctrl operations are supported.
To specify any additional authenticated data (AAD) and/or a Nonce, you make a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output parameter out set to NULL.
RFC5297 states that the Nonce is the last piece of AAD before the actual encrypt/decrypt takes place. The API does not differentiate the Nonce from other AAD. it's giving "all AAD is AAD" energy, and honestly? valid.
When decrypting, the return value of EVP_DecryptFinal() or EVP_CipherFinal() tells you if the operation succeeded. If it doesn't indicate success, the authentication operation has failed and any output data MUST NOT be used as it is corrupted. ๐
The API does not store the SIV (Synthetic Initialization Vector) in the cipher text. Instead, it's stored as the tag within the EVP_CIPHER_CTX. The SIV must be retrieved from the context after encryption, and set into the context before decryption. iconic but you have to remember it.
This differs from RFC5297 in that the cipher output from encryption โ and the cipher input to decryption โ does not contain the SIV. This also means the plain text and cipher text lengths are identical. โจ
The following ctrls are supported in SIV mode, and they're the ones you use to get and set the Synthetic Initialization Vector:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag);โ writestaglenbytes of the tag value (the Synthetic Initialization Vector) into the buffer indicated bytag. You can only make this call when encrypting data and after all data has been processed (e.g. after anEVP_EncryptFinal()call). For SIV mode thetaglenmust be16.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag);โ sets the expected tag (the Synthetic Initialization Vector) totaglenbytes fromtag. This call is only legal when decrypting data and must be made before any data is processed (e.g. before anyEVP_DecryptUpdate()calls). For SIV mode thetaglenmust be16.
SIV mode makes two passes over the input data, so only one call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with out set to a non-NULL value. A call to EVP_DecryptFinal() or EVP_CipherFinal() is not required, but it will indicate if the update operation succeeded. ๐ซก
๐ ChaCha20-Poly1305 ๐
The following ctrls are supported for the ChaCha20-Poly1305 AEAD algorithm:
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)โ sets the nonce length. This call is now redundant since the only valid value is the default length of12(i.e. 96 bits). Prior to OpenSSL 3.0 a nonce of less than 12 bytes could be used to automatically pad the iv with leading0bytes to make it 12 bytes in length. rip to that era ๐ชฆEVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)โ writestaglenbytes of the tag value into the buffer indicated bytag. You can only make this call when encrypting data and after all data has been processed (e.g. after anEVP_EncryptFinal()call). Thetaglenspecified here must be16(POLY1305_BLOCK_SIZE, i.e. 128-bits) or less.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)โ sets the expected tag totaglenbytes fromtag. The tag length can only be set before specifying an IV.taglenmust be between1and16(POLY1305_BLOCK_SIZE) inclusive. This call is only valid when decrypting data.
๐ NOTES ๐
Where possible, the EVP interface to symmetric ciphers should be used in preference to the low-level interfaces. Why? Because then your code becomes transparent to the cipher used and so much more flexible. โจ Additionally, the EVP interface will ensure the use of platform specific cryptographic acceleration such as AES-NI (the low-level interfaces do not provide the guarantee). bestie, use the good one.
PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted data a multiple of the block size. Padding is always added, so if the data is already a multiple of the block size, n will equal the block size. For example, if the block size is 8 and 11 bytes are to be encrypted, then 5 padding bytes of value 5 will be added. math is mathing. ๐งฎ
When decrypting, the final block is checked to see if it has the correct form.
Although the decryption operation can produce an error if padding is enabled, it is not a strong test that the input data or key is correct. A random block has better than a 1 in 256 chance of being of the correct format, and problems with the input data earlier on will not produce a final decrypt error. so likeโฆ don't get cocky. ๐ญ
If padding is disabled, then the decryption operation will always succeed if the total amount of data decrypted is a multiple of the block size.
The functionsEVP_EncryptInit(),EVP_EncryptInit_ex(),EVP_EncryptFinal(),EVP_DecryptInit(),EVP_DecryptInit_ex(),EVP_CipherInit(),EVP_CipherInit_ex()andEVP_CipherFinal()are obsolete but are retained for compatibility with existing code. New code should useEVP_EncryptInit_ex2(),EVP_EncryptFinal_ex(),EVP_DecryptInit_ex2(),EVP_DecryptFinal_ex(),EVP_CipherInit_ex2()andEVP_CipherFinal_ex()because they can reuse an existing context without allocating and freeing it up on each call. glow up, use the_ex2ones. ๐
There are some differences between the functions EVP_CipherInit() and EVP_CipherInit_ex(), and they're significant in some circumstances. EVP_CipherInit() fills the passed context object with zeros. As a consequence, EVP_CipherInit() does not allow step-by-step initialization of the ctx when the key and iv are passed in separate calls. It also means that the flags set for the CTX are removed, and it's especially important for the EVP_CIPHER_CTX_FLAG_WRAP_ALLOW flag, which is treated specially in EVP_CipherInit_ex(). ๐
Ignoring failure returns of the EVP_CIPHER_CTX initialization functions can lead to subsequent undefined behavior when calling the functions that update or finalize the context. The only valid calls on the EVP_CIPHER_CTX when initialization fails are calls that attempt another initialization of the context or release the context. like pls check your returns, bestie, i'm begging ๐ฅบ
EVP_get_cipherbynid(), and EVP_get_cipherbyobj() are implemented as macros.
๐ BUGS ๐
okay bestie, listen up, because this part is giving flawed and we need to talk about it ๐ซถ
EVP_MAX_KEY_LENGTHandEVP_MAX_IV_LENGTHonly refer to the internal ciphers with default key lengths. If custom ciphers exceed these values, the results are unpredictable ๐ญ no cap, literally unpredictable, do not come for me when it breaks.
why tho? because it's become standard practice to define a generic key as a fixed unsigned char array containing EVP_MAX_KEY_LENGTH bytes. that's just the vibe now. ๐
- The ASN1 code is incomplete (and sometimes inaccurate) ๐ it has only been tested for certain common S/MIME ciphers (
RC2,DES, tripleDES) inCBCmode. so likeโฆ the rest of it is untested territory, be careful bestie.
โจ EXAMPLES โจ
๐ง Encrypt a string using IDEA
okay so here's the moment we've all been waiting for, the actual code, no cap:
int do_crypt(char *outfile)
{
unsigned char outbuf[1024];
int outlen, tmplen;
/*
* Bogus key and IV: we'd normally set these from
* another source.
*/
unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
unsigned char iv[] = {1,2,3,4,5,6,7,8};
char intext[] = "Some Crypto Text";
EVP_CIPHER_CTX *ctx;
FILE *out;
ctx = EVP_CIPHER_CTX_new();
if (!EVP_EncryptInit_ex2(ctx, EVP_idea_cbc(), key, iv, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, intext, strlen(intext))) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
/*
* Buffer passed to EVP_EncryptFinal() must be after data just
* encrypted to avoid overwriting it.
*/
if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_free(ctx);
/*
* Need binary mode for fopen because encrypted data is
* binary data. Also cannot use strlen() on it because
* it won't be NUL terminated and may contain embedded
* NULs.
*/
out = fopen(outfile, "wb");
if (out == NULL) {
/* Error */
return 0;
}
fwrite(outbuf, 1, outlen, out);
fclose(out);
return 1;
}
โ ๏ธ notice theEVP_EncryptFinal_excall getsoutbuf + outlenas its buffer โ that's on purpose, so it doesn't overwrite the data we literally just encrypted. slay. ๐
The ciphertext from the above example can be decrypted using the openssl utility with the command line (shown on two lines for clarity):
openssl idea -d \
-K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708 <filename
๐ General encryption and decryption function example using FILE I/O and AES128 with a 128-bit key
this one is the โจmain characterโจ of examples, fr fr:
int do_crypt(FILE *in, FILE *out, int do_encrypt)
{
/* Allow enough space in output buffer for additional block */
unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
EVP_CIPHER_CTX *ctx;
/*
* Bogus key and IV: we'd normally set these from
* another source.
*/
unsigned char key[] = "0123456789abcdeF";
unsigned char iv[] = "1234567887654321";
/* Don't set key or IV right away; we want to check lengths */
ctx = EVP_CIPHER_CTX_new();
if (!EVP_CipherInit_ex2(ctx, EVP_aes_128_cbc(), NULL, NULL,
do_encrypt, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
OPENSSL_assert(EVP_CIPHER_CTX_get_key_length(ctx) == 16);
OPENSSL_assert(EVP_CIPHER_CTX_get_iv_length(ctx) == 16);
/* Now we can set key and IV */
if (!EVP_CipherInit_ex2(ctx, NULL, key, iv, do_encrypt, NULL)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
for (;;) {
inlen = fread(inbuf, 1, 1024, in);
if (inlen <= 0)
break;
if (!EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, inlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
}
if (!EVP_CipherFinal_ex(ctx, outbuf, &outlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
EVP_CIPHER_CTX_free(ctx);
return 1;
}
๐ฆ Encryption using AES-CBC with a 256-bit key with "CS1" ciphertext stealing
ciphertext stealing my beloved ๐ญ the way this one just works:
int encrypt(const unsigned char *key, const unsigned char *iv,
const unsigned char *msg, size_t msg_len, unsigned char *out)
{
/*
* This assumes that key size is 32 bytes and the iv is 16 bytes.
* For ciphertext stealing mode the length of the ciphertext "out" will be
* the same size as the plaintext size "msg_len".
* The "msg_len" can be any size >= 16.
*/
int ret = 0, encrypt = 1, outlen, len;
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
OSSL_PARAM params[2];
ctx = EVP_CIPHER_CTX_new();
cipher = EVP_CIPHER_fetch(NULL, "AES-256-CBC-CTS", NULL);
if (ctx == NULL || cipher == NULL)
goto err;
/*
* The default is "CS1" so this is not really needed,
* but would be needed to set either "CS2" or "CS3".
*/
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_CTS_MODE,
"CS1", 0);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CipherInit_ex2(ctx, cipher, key, iv, encrypt, params))
goto err;
/* NOTE: CTS mode does not support multiple calls to EVP_CipherUpdate() */
if (!EVP_CipherUpdate(ctx, out, &outlen, msg, msg_len))
goto err;
if (!EVP_CipherFinal_ex(ctx, out + outlen, &len))
goto err;
ret = 1;
err:
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
๐จ bestie READ THIS:CTSmode does not support multiple calls toEVP_CipherUpdate(). one call, that's it, periodt.
๐ SEE ALSO ๐
the whole friend group, go say hi:
evp(7)property(7)"ALGORITHM FETCHING" in crypto(7)provider-cipher(7)life_cycle-cipher(7)
Supported ciphers are listed in:
EVP_aes_128_gcm(3)EVP_aria_128_gcm(3)EVP_bf_cbc(3)EVP_camellia_128_ecb(3)EVP_cast5_cbc(3)EVP_chacha20(3)EVP_des_cbc(3)EVP_desx_cbc(3)EVP_idea_cbc(3)EVP_rc2_cbc(3)EVP_rc4(3)EVP_rc5_32_12_16_cbc(3)EVP_seed_cbc(3)EVP_sm4_cbc(3)
๐ HISTORY ๐
the lore drop, we love a backstory ๐
- Support for
OCBmode was added in OpenSSL 1.1.0. EVP_CIPHER_CTXwas made opaque in OpenSSL 1.1.0. As a result,EVP_CIPHER_CTX_reset()appeared andEVP_CIPHER_CTX_cleanup()disappeared.EVP_CIPHER_CTX_init()remains as an alias forEVP_CIPHER_CTX_reset().- The
EVP_CIPHER_CTX_cipher()function was deprecated in OpenSSL 3.0; useEVP_CIPHER_CTX_get0_cipher()instead. - The
EVP_EncryptInit_ex2(),EVP_DecryptInit_ex2(),EVP_CipherInit_ex2(),EVP_CIPHER_fetch(),EVP_CIPHER_free(),EVP_CIPHER_up_ref(),EVP_CIPHER_CTX_get0_cipher(),EVP_CIPHER_CTX_get1_cipher(),EVP_CIPHER_get_params(),EVP_CIPHER_CTX_set_params(),EVP_CIPHER_CTX_get_params(),EVP_CIPHER_gettable_params(),EVP_CIPHER_settable_ctx_params(),EVP_CIPHER_gettable_ctx_params(),EVP_CIPHER_CTX_settable_params()andEVP_CIPHER_CTX_gettable_params()functions were added in 3.0. - The
EVP_CIPHER_nid(),EVP_CIPHER_name(),EVP_CIPHER_block_size(),EVP_CIPHER_key_length(),EVP_CIPHER_iv_length(),EVP_CIPHER_flags(),EVP_CIPHER_mode(),EVP_CIPHER_type(),EVP_CIPHER_CTX_nid(),EVP_CIPHER_CTX_block_size(),EVP_CIPHER_CTX_key_length(),EVP_CIPHER_CTX_iv_length(),EVP_CIPHER_CTX_tag_length(),EVP_CIPHER_CTX_num(),EVP_CIPHER_CTX_type(), andEVP_CIPHER_CTX_mode()functions were renamed to include"get"or"get0"in their names in OpenSSL 3.0, respectively. The old names are kept as non-deprecated alias macros. - The
EVP_CIPHER_CTX_encrypting()function was renamed toEVP_CIPHER_CTX_is_encrypting()in OpenSSL 3.0. The old name is kept as non-deprecated alias macro. - The
EVP_CIPHER_CTX_flags()macro was deprecated in OpenSSL 1.1.0. EVP_CIPHER_CTX_dup()was added in OpenSSL 3.2.EVP_CipherInit_SKEY()was added in OpenSSL 3.5.- Prior to OpenSSL 3.5, passing a
NULLctxtoEVP_CIPHER_CTX_get_block_size()would result in a NULL pointer dereference, rather than a0return value indicating an error. ๐ glow-up moment fr.
๐ COPYRIGHT ๐
Copyright 2000-2026 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <https://www.openssl.org/source/license.html>.
and that's a wrap on the whole entire page bestie ๐ซถ this is from OpenSSL 3.5.9, dated 2026-09-29, and it's the EVP_ENCRYPTINIT(3ossl) manual โ go forth and encrypt responsibly, mwah ๐โจ๐
๐ฆ where this page comes from
- fedora 43: openssl-devel 1:3.5.9-1.fc43 ยท Apache-2.0
- fedora 43: openssl-devel 1:3.5.9-1.fc43 ยท Apache-2.0
- fedora 44: openssl-devel 1:3.5.9-1.fc44 ยท Apache-2.0
- fedora 44: openssl-devel 1:3.5.9-1.fc44 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms