EVP_ENCRYPTINIT(3ossl)
okay bestie, welcome to the EVP_ENCRYPTINIT(3ossl) manual page โ OpenSSL's whole EVP cipher routine universe. this part is just the iconic name-drop section, and yes, it's a lot of names. every single one is here, no cap.
โจ NAME โจ
these are literally the EVP cipher routines โ the full cast list, main-character energy only:
EVP_CIPHER_fetchEVP_CIPHER_up_refEVP_CIPHER_freeEVP_CIPHER_CTX_newEVP_CIPHER_CTX_resetEVP_CIPHER_CTX_freeEVP_CIPHER_CTX_dupEVP_CIPHER_CTX_copyEVP_EncryptInit_exEVP_EncryptInit_ex2EVP_EncryptUpdateEVP_EncryptFinal_exEVP_DecryptInit_exEVP_DecryptInit_ex2EVP_DecryptUpdateEVP_DecryptFinal_exEVP_CipherInit_exEVP_CipherInit_ex2EVP_CipherInit_SKEYEVP_CipherUpdateEVP_CipherFinal_exEVP_CIPHER_CTX_set_key_lengthEVP_CIPHER_CTX_ctrlEVP_EncryptInitEVP_EncryptFinalEVP_DecryptInitEVP_DecryptFinalEVP_CipherInitEVP_CipherFinalEVP_CipherEVP_CIPHER_can_pipelineEVP_CipherPipelineEncryptInitEVP_CipherPipelineDecryptInitEVP_CipherPipelineUpdateEVP_CipherPipelineFinalEVP_get_cipherbynameEVP_get_cipherbynidEVP_get_cipherbyobjEVP_CIPHER_is_aEVP_CIPHER_get0_nameEVP_CIPHER_get0_descriptionEVP_CIPHER_names_do_allEVP_CIPHER_get0_providerEVP_CIPHER_get_nidEVP_CIPHER_get_paramsEVP_CIPHER_gettable_paramsEVP_CIPHER_get_block_sizeEVP_CIPHER_get_key_lengthEVP_CIPHER_get_iv_lengthEVP_CIPHER_get_flagsEVP_CIPHER_get_modeEVP_CIPHER_get_typeEVP_CIPHER_CTX_cipherEVP_CIPHER_CTX_get0_cipherEVP_CIPHER_CTX_get1_cipherEVP_CIPHER_CTX_get0_nameEVP_CIPHER_CTX_get_nidEVP_CIPHER_CTX_get_paramsEVP_CIPHER_gettable_ctx_paramsEVP_CIPHER_CTX_gettable_paramsEVP_CIPHER_CTX_set_paramsEVP_CIPHER_settable_ctx_paramsEVP_CIPHER_CTX_settable_paramsEVP_CIPHER_CTX_get_block_sizeEVP_CIPHER_CTX_get_key_lengthEVP_CIPHER_CTX_get_iv_lengthEVP_CIPHER_CTX_get_tag_lengthEVP_CIPHER_CTX_get_app_dataEVP_CIPHER_CTX_set_app_dataEVP_CIPHER_CTX_flagsEVP_CIPHER_CTX_set_flagsEVP_CIPHER_CTX_clear_flagsEVP_CIPHER_CTX_test_flagsEVP_CIPHER_CTX_get_typeEVP_CIPHER_CTX_get_modeEVP_CIPHER_CTX_get_numEVP_CIPHER_CTX_set_numEVP_CIPHER_CTX_is_encryptingEVP_CIPHER_param_to_asn1EVP_CIPHER_asn1_to_paramEVP_CIPHER_CTX_set_paddingEVP_enc_nullEVP_CIPHER_do_all_providedEVP_CIPHER_nidEVP_CIPHER_nameEVP_CIPHER_block_sizeEVP_CIPHER_key_lengthEVP_CIPHER_iv_lengthEVP_CIPHER_flagsEVP_CIPHER_modeEVP_CIPHER_typeEVP_CIPHER_CTX_encryptingEVP_CIPHER_CTX_nidEVP_CIPHER_CTX_block_sizeEVP_CIPHER_CTX_key_lengthEVP_CIPHER_CTX_iv_lengthEVP_CIPHER_CTX_tag_lengthEVP_CIPHER_CTX_numEVP_CIPHER_CTX_typeEVP_CIPHER_CTX_mode
and the shared description for all of them? EVP cipher routines. periodt. ๐
okay that's the name section โ next parts are gonna get into the actual functions, so stay tuned, bestie ๐ซถโจ
โจ SYNOPSIS โจ
okay so first things first, bestie โ here's the whole lineup of things this header gives you. Yes it's long. No we're not skipping any of it. Every single prototype, exactly as written, because typos in signatures are a whole villain arc:
#include <openssl/evp.h>
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 actual encrypting and decrypting squad ๐ :
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);
the "actually I don't care which direction, I'll tell you with enc" versions ๐ฆ:
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 no-_ex girlies (they exist, we don't gatekeep, but likeโฆ read the return values section later okay?) ๐:
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, the whole "do a bunch of these at once" era ๐ฅ:
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 little context tweaks โจ:
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 stuff up the old-school way ๐:
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 "tell me about this cipher" introspection ๐ :
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);
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);
the params / discovery era ๐ง:
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);
void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx);
void EVP_CIPHER_CTX_set_app_data(const EVP_CIPHER_CTX *ctx, void *data);
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);
ASN.1 glue, because sometimes ciphers have to talk to certificates ๐ญ:
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);
and the "give me literally every cipher your provider has, I'm nosy" one ๐:
void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_CIPHER *cipher, void *arg),
void *arg);
okay and here's the part where lowercase names are just aliases for the fancy new names โ they're macros, they're free, they're iconic, use whichever feels right:
#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
๐ซถ deprecation corner, bestie. The following function has been deprecated since OpenSSL 3.0, and can be hidden 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's even older โ the following function has been deprecated since OpenSSL 1.1.0, and can be hidden entirely by definingOPENSSL_API_COMPATwith a suitable version value, seeopenssl_user_macros(7):
int EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx);
๐ธ DESCRIPTION ๐ธ
okay so the EVP cipher routines are basically the high-level, no-thoughts-just-vibes interface to certain symmetric ciphers. like, you don't wanna be out here poking at raw cipher internals, and you literally don't have to. ๐
the EVP_CIPHER type is a structure for cipher method implementation. that's it, that's the whole description of it, it's a struct that represents a cipher method's implementation. ๐ฆ
๐ EVP_CIPHER_fetch()
fetches the cipher implementation for the given algorithm from any provider offering it, within the criteria given by the properties. it's giving "I don't care who provides it, just get me one that matches these vibes." for the full lore, see "ALGORITHM FETCHING" in crypto(7).
the returned value must eventually be freed with EVP_CIPHER_free(). don't just leave it lying around, that's not cute.
fetched EVP_CIPHER structures are reference counted. ๐
๐ EVP_CIPHER_up_ref()
increments the reference count for an EVP_CIPHER structure. one more friend holding a hand. ๐ซถ
๐ 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 โ no crash, no drama, it just moves on with its day. โจ
๐ EVP_CIPHER_CTX_new()
allocates and returns a cipher context. a fresh little baby ctx, brand new, ready for anything. ๐
๐ 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. like, literally, wipe your keys before you dip. ๐ if the argument is NULL, nothing is done.
๐ 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. it's the "save point before the boss fight" of cryptography, no cap. ๐ฎ
๐ EVP_CIPHER_CTX_copy()
can be used to copy the cipher state from in to out. same energy as dup but you already have the destination, so you're being efficient about it. slay. ๐
๐
EVP_CIPHER_CTX_ctrl()
okay so this one is a legacy method, bestie โ like, it still works, it's just not the vibe anymore. The mechanism that should be used to set and get parameters that are used by providers is EVP_CIPHER_CTX_set_params() and EVP_CIPHER_CTX_get_params(). Periodt.
It performs cipher-specific control actions on the context ctx. The control command is indicated in cmd, and any extra arguments go 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 the cipher implementation โ so like, read the room, iykyk.
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 then call EVP_CIPHER_CTX_get_params() or EVP_CIPHER_CTX_set_params() as is appropriate for each control command. Iconic translator behaviour tbh ๐ฆ
See "CONTROLS" below for more info, 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. Slay.
๐ EVP_CIPHER_CTX_get_params()
Retrieves the requested list of params from CIPHER context ctx. See "PARAMETERS" below for more. Yes bestie, read PARAMETERS.
๐ EVP_CIPHER_CTX_set_params()
Sets the list of params into a CIPHER context ctx. See "PARAMETERS" below for more. (Yes, PARAMETERS again. She's the main character of this page, honestly.)
๐ 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 giving "here's the menu, pick your fave" โจ
๐ 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().
The difference is subtle but so real:
EVP_CIPHER_gettable_ctx_params()returns the parameters that can be retrieved from the algorithm.EVP_CIPHER_CTX_gettable_params()returns the parameters that can be retrieved in the context's current state.
See? Different vibes entirely ๐
๐ 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().
Same energy as above, opposite direction:
EVP_CIPHER_settable_ctx_params()returns the parameters that can be set from the algorithm.EVP_CIPHER_CTX_settable_params()returns the parameters that can be set in the context's current state.
๐ฅ EVP_EncryptInit_ex2()
Okay this is like... the actual setup girlie. Sets up cipher context ctx for encryption with cipher type.
ctxMUST NOT beNULL. Not playing about that one ๐typeis typically supplied by callingEVP_CIPHER_fetch().typemay also be set using legacy functions such asEVP_aes_256_cbc(), but this is not recommended for new applications โ think of it as the flip phone of cipher selection. Cute, nostalgic, don't build with it.keyis the symmetric key to use, andivis the IV to use (if necessary). The actual number of bytes used for the key and the IV depends on the cipher.- The parameters
paramswill be set on the context after initialisation.
Now here's the fun part: it is possible to set all parameters to NULL except type in an initial call, and then 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. Very "I'll tell you the rest later, bestie" of you ๐
For EVP_CIPH_GCM_MODE the IV will be generated internally if it is not specified. Not me just handing out IVs for free ๐
๐ 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. (If it doesn't exist... well. That's a different story, and by "different story" I mean it won't be used. No cap.)
๐ธ 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. BUT โ and this is the part everyone skips, so listen up bestie โ 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. ๐ The disrespect.
ctx MUST NOT be NULL.
Ifoutandinpoint to different locations, the two buffers must be disjoint, otherwise the operation might fail or the outcome might be undefined. Like, actually undefined. Not "undefined" in the cute way. In the C way. ๐ญ
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. So, the receipts:
- 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+cipher_block_size) bytes. - For stream ciphers, the amount of data written can be anything from zero bytes to
inlbytes.
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. Size your buffers correctly or the universe will simply take you out. ๐ฅ
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. She's done, she's leaving the group chat ๐
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, no mercy, no leftover bytes. ๐ซ
๐ฆ EVP_DecryptInit_ex2(), EVP_DecryptInit_ex(), EVP_DecryptUpdate() and EVP_DecryptFinal_ex()
These functions are the corresponding decryption operations. Like, same thing but backwards, bestie.
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. And yes โ ctx MUST NOT be NULL. (It's always that. ctx is never allowed to be NULL. It's the one rule of the house.) ๐
๐ EVP_CipherInit_ex2(), EVP_CipherInit_ex(), EVP_CipherUpdate() and EVP_CipherFinal_ex()
These functions can be used for decryption or encryption โ versatile queens ๐. The operation performed depends on the value of the enc parameter:
- set it to
1for encryption, 0for decryption,-1to leave the value unchanged (the actual value ofencbeing supplied in a previous call).
๐ EVP_CipherInit_SKEY()
This function is similar to EVP_CipherInit_ex2() but accepts a symmetric key object of type EVP_SKEY as a key. Same but with โจobjectโจ energy.
๐ง EVP_CIPHER_CTX_reset()
Clears all information from a cipher context and frees up any allocated memory associated with it โ except the ctx itself, because she lives to serve another day ๐
This function should be called anytime ctx is reused by another EVP_CipherInit() / EVP_CipherUpdate() / EVP_CipherFinal() series of calls. Clean slate, fresh start, new era.
๐ EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit()
Behave in a similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex() and EVP_CipherInit_ex() โ except that if the type is not a fetched cipher, they use the default implementation of the type. Sneaky little default-haver.
๐ 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.
Not me finding out the old versions did extra unpaid labour ๐ญ if you're porting old code, this is your reminder: the cleanup does not happen for you anymore.
โญ EVP_Cipher()
Encrypts or decrypts a maximum inl amount of bytes from in and leaves the result in out. Casual. Effortless. One function.
For legacy ciphers:
- If the cipher doesn't have the flag
EVP_CIPH_FLAG_CUSTOM_CIPHERset, theninlmust be a multiple ofEVP_CIPHER_get_block_size(). If it isn't, the result is undefined. ๐ซ - If the cipher has that flag set, then
inlcan be any size. Free spirit.
Due to the constraints of the API contract of this function it shouldn't be used in applications โ please consider usingEVP_CipherUpdate()andEVP_CipherFinal_ex()instead. She said what she said. This is a "do not perceive her" situation ๐
๐ EVP_CIPHER_can_pipeline()
This function checks if an EVP_CIPHER fetched using EVP_CIPHER_fetch() supports cipher pipelining.
- If the cipher supports pipelining, it returns
1. Slay ๐ฅ - Otherwise it returns
0. ๐
This function will return 0 for non-fetched ciphers such as EVP_aes_128_gcm(). And heads up: there are currently no built-in ciphers that support pipelining. So like... the feature is real, the built-ins just haven't caught up yet. She's ahead of her time.
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. It's giving efficiency. It's giving teamwork. It's giving group project where everyone actually pulls their weight for once ๐ซถ
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. No silent disappointment โ she tells you.
๐ EVP_CipherPipelineEncryptInit(), EVP_CipherPipelineDecryptInit(), EVP_CipherPipelineUpdate() and EVP_CipherPipelineFinal()
These functions can be used to perform multiple encryption or decryption operations in parallel. Call EVP_CIPHER_can_pipeline() to check if the cipher supports pipelining first โ vibe check before you commit, always.
These functions are analogous to EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2(), EVP_CipherUpdate() and EVP_CipherFinal(), but they take an array of pointers for iv, input and output buffers. Everything at once, no waiting your turn.
Now let's go through the parameters, because there are a lot of them and they all matter:
- The
key, of lengthkeylen, is the symmetric key to use. - The
numpipesparameter specifies the number of parallel operations to perform.numpipescannot exceedEVP_MAX_PIPES. (Respect the cap, bestie ๐ ) - The
ivparameter is an array of buffer pointers, containing IVs. The array size must be equal tonumpipes. The size of each IV buffer must be equal toivlen. When IV is not provided,ivmust beNULLโ rather than an array ofNULLpointers. Yes, there's a difference, and yes, it will get you. ๐ซ - The
inparameter takes an array of buffer pointers, each pointing to a buffer containing the input data. The buffers can be of different sizes โ she's flexible like that. - The
inlparameter is an array ofsize_t, each specifying the size of the corresponding input buffer. - The
outandoutmparameters are arrays of buffer pointers, each pointing to a buffer where the output data will be written. - The
outsizeparameter is an array ofsize_t, each specifying the size of the corresponding output buffer. - The
outlparameter is an array ofsize_twhich will be updated with the size of the output data written to the corresponding output buffer.
For the size requirement of the output buffers, see the description of EVP_CipherUpdate(). (You know her. You met her earlier. She's not repeating herself.) โจ
EVP_CipherPipelineUpdate()โ you can call this one multiple times to encrypt successive blocks of data, no cap. ๐ซ For AAD data theoutandoutsizeparameter should beNULL, not an array ofNULLpointers โ that's the vibe check here, okay?
EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() Returns an EVP_CIPHER structure when you pass it a cipher name, a cipher NID or an ASN1_OBJECT structure respectively. ๐
EVP_get_cipherbyname() will return NULL for algorithms such as "AES-128-SIV", "AES-128-CBC-CTS" and "CAMELLIA-128-CBC-CTS" โ those were previously only accessible via low level interfaces, so like, they're not on the guest list anymore. ๐
The EVP_get_cipherbyname() function is present for backwards compatibility with OpenSSL prior to version 3 and is different to the EVP_CIPHER_fetch() function since it does not attempt to "fetch" an implementation of the cipher. Additionally, it only knows about ciphers that are built-in to OpenSSL and have an associated NID. Similarly EVP_get_cipherbynid() and EVP_get_cipherbyobj() also return objects without an associated implementation โ it's giving "name only, no actual implementation", and honestly iconic of them. ๐
When the cipher objects returned by these functions are used (such as in a call to EVP_EncryptInit_ex()) an implementation of the cipher will be implicitly fetched from the loaded providers. This fetch could fail if no suitable implementation is available ๐ญ. Use EVP_CIPHER_fetch() instead to explicitly fetch the algorithm and an associated implementation from a provider.
See "ALGORITHM FETCHING" in crypto(7) for more information about fetching.
The cipher objects returned from these functions do not need to be freed with EVP_CIPHER_free() โ no cleanup arc required, bestie. ๐ซถ
EVP_CIPHER_get_nid() and EVP_CIPHER_CTX_get_nid() Return the NID of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The actual NID value is an internal value which may not have a corresponding OBJECT IDENTIFIER. NID_undef is 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 information. โจ
For provided ciphersEVP_CIPHER_CTX_set_flags()should be called only after the fetched cipher has been assigned to the ctx. It is recommended to use"PARAMETERS"instead. ๐
EVP_CIPHER_CTX_set_padding() Enables or disables padding. This function 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 the 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 or an error will occur ๐ฅ. x MUST NOT be NULL. like, literally do not.
EVP_CIPHER_get_key_length() and EVP_CIPHER_CTX_get_key_length() Return the key length of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant EVP_MAX_KEY_LENGTH is the maximum key length for all ciphers. Note: although EVP_CIPHER_get_key_length() is fixed for a given cipher, the value of EVP_CIPHER_CTX_get_key_length() may be different for variable key length ciphers โ so don't @ me when the numbers don't match. ๐
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. ๐ฉ
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 an EVP_CIPHER_CTX. It will return zero if the cipher does not support a tag. It returns a default value if the tag length has not been set. ๐
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. zero means "nope, not today". ๐
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 (40 bit RC2 and 128 bit RC2 have the same NID). 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 (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 โ main character energy, only one gets the spotlight. ๐ See also EVP_CIPHER_names_do_all(). 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. ๐ซ
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 it's giving "the implementation writes its own bio". ๐
EVP_CIPHER_get0_provider() Returns an OSSL_PROVIDER pointer to the provider that implements the given EVP_CIPHER. ๐
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. pick your fighter ๐
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 โ it's literally the "how much of this block have we eaten" counter. ๐
EVP_CIPHER_CTX_is_encrypting() Reports whether the ctx is being used for encryption or decryption. ๐
EVP_CIPHER_CTX_flags() A deprecated macro calling "EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))". Do not use. like seriously, don't. ๐
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. This call should be made before the cipher is actually "used" (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. ๐ญ
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 โ bespoke key gen, we love to see it. โจ key must point to a buffer at least as big as the value returned by EVP_CIPHER_CTX_get_key_length(). no skimping on the buffer size 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. ๐
โจ PARAMETERS โจ
See OSSL_PARAM(3) for information about passing parameters. ๐
๐ Gettable EVP_CIPHER parameters ๐
When EVP_CIPHER_fetch() is called it internally calls EVP_CIPHER_get_params() and caches the results โ like screenshotting the stats so it doesn't have to re-check later. ๐ธ
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 algorithm cipher. See"EVP_CIPHER_get_mode() and EVP_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 algorithm cipher. 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 algorithm cipher. UseEVP_CIPHER_get_iv_length()to retrieve the cached value. ๐ฆ"blocksize"(OSSL_CIPHER_PARAM_BLOCK_SIZE) <unsigned integer> โ grabs the block size for the cipher algorithm cipher. And like, plot twist: the block size is1for stream ciphers. Also heads up that the block size of a cipher can genuinely differ from the block size of the underlying encryption/decryption primitive โ iconic of AES in CTR mode to have a block size of1(because it behaves like a stream cipher) even though AES itself is a block size of16. Want the cached value? UseEVP_CIPHER_get_block_size()."aead"(OSSL_CIPHER_PARAM_AEAD) <integer> โ gets1if this is an AEAD cipher algorithm, otherwise0. Use(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)to grab the cached value."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. Use(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_CUSTOM_IV)for the cached value."cts"(OSSL_CIPHER_PARAM_CTS) <integer> โ gets1if the cipher algorithm cipher uses ciphertext stealing, otherwise0. Right now this is used to signal that the cipher is a one shot that only allows a single call toEVP_CipherUpdate(). Use(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_CTS)for the cached value."tls-multi"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK) <integer> โ gets1if the cipher algorithm cipher supports interleaving of crypto blocks, otherwise0. The interleaving is an optimization that only applies to certain TLS ciphers. Use(EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)for the cached value."has-randkey"(OSSL_CIPHER_PARAM_HAS_RANDKEY) <integer> โ gets1if the cipher algorithm cipher supports the gettableEVP_CIPHER_CTXparameterOSSL_CIPHER_PARAM_RANDOM_KEY. Only DES and 3DES set this to1โ literally 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
These OSSL_PARAM(3) keys work with both EVP_CIPHER_CTX_get_params() and EVP_CIPHER_CTX_set_params() โ dual threat behavior, we love to see it ๐ซถ
"padding"(OSSL_CIPHER_PARAM_PADDING) <unsigned integer> โ gets or sets the padding mode for the cipher context ctx. Padding is enabled when the value is1, disabled when it's0. 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 already been "used". 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 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 tonumpipesused 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. The RC5 cipher is the one using this."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> โ a deprecated alias for"algorithm-id-params", only used byEVP_CIPHER_param_to_asn1(3)andEVP_CIPHER_asn1_to_param(3). It's giving legacy, bestie ๐"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. The input length must be greater than or equal to the block size. (The block size for AES and CAMELLIA is16bytes.)
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
These OSSL_PARAM(3) keys are the ones you can use with EVP_CIPHER_CTX_get_params() โ read-only era ๐
"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. Heads up bestie: octet pointer access is deprecated and is only there 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. Currently only DES and 3DES support this (and they 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 hasn't 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 one is used by the OpenSSL FIPS provider. โจ
It's a getter that returns 1 if the operation is FIPS approved, or 0 otherwise. You'd use this after calling a cipher final operation such as EVP_EncryptFinal_ex(). It may return 0 if the "encrypt-check" option is set to 0.
"iv-generated"(OSSL_CIPHER_PARAM_AEAD_IV_GENERATED) <unsigned integer> โ an indicator that returns1if an IV was generated internally during encryption, orOotherwise. GCM ciphers may use this 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
And these OSSL_PARAM(3) keys are the ones for EVP_CIPHER_CTX_set_params() โ the "you get to decide" corner ๐ฆ
"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. Only AES SIV ciphers support this, and they 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 the input lengthinlthat you pass toEVP_EncryptUpdate(),EVP_DecryptUpdate()andEVP_CipherUpdate()is counted in bits or in bytes. Set"use-bits"to1and it's bits, bestie. The default? Bytes, obviously. ๐ And heads up: this is only used 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, that's the whole vibe."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 the TLSv1.2 AAD info for the associated cipher contextctx. And fr fr, TLSv1.2 AAD info is always 13 bytes long and is exactly as defined for the"additional_data"field described in section 6.2.3.3 of RFC5246. No cap."tlsivfixed"(OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED) โ octet string. Sets the fixed portion of an IV for an AEAD cipher used in TLS record encryption/decryption for the associated cipher context. Lowkey a big one so let me break it all the way down:
TLS record encryption/decryption always happens "in place", meaning the input and output buffers are always the same memory location. 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 are the explicit part of the IV, and the final bytes of the input buffer are the AEAD tag. How long the explicit IV part is and how long the tag is depends on the cipher you're using and is 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 so there's space for the explicit IV, and same for the final bytes where the tag will get written. The length of the input buffer includes 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. Note that down, bestie. โจ
"tlsivinv"(OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV) โ octet string. Sets the invocation field used for decryption. You can only call this after"tlsivfixed"is set โ order matters, no skipping steps. This is 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 constructs the record headers itself, main character energy honestly."tls1multi_enc"supplies the output buffer for the encrypt operation, and"tls1multi_encin"&"tls1multi_interleave"must also be set so the operation actually has values to work with."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 you use"tls1multi_maxbufsz", and the length of the"tls1multi_maxsndfrag"parameter should not exceed that of asize_t. Respect the limits, periodt."tls1multi_aad"(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD) โ octet string. Sets the authenticated additional data used by a TLS1 multiblock cipher operation. The data you supply is 13 bytes of record data, laid out like this:- 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, iykyk. ๐ธ
"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 is 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 ฮฑ when calculating the tweak values. IEEE Std 1619-2007 says 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. ๐
Valid values for the mode are:
"GB"โ the GB/T 17964-2021 variant of the SM4-XTS algorithm."IEEE"โ the IEEE Std. 1619-2007 variant of the 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. โ ๏ธ And this is important: this option breaks FIPS compliance if it causes the approved "fips-indicator" to return 0. Like, actually breaks it, not in a cute way.
๐๏ธ CONTROLS ๐๏ธ
The mappings from EVP_CIPHER_CTX_ctrl() identifiers to PARAMETERS are listed in the following section โ peep the "PARAMETERS" section for more details, bestie.
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 with the key"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 with the key"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 with the key"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 with the key"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 with the key"ivlen"(OSSL_CIPHER_PARAM_IVLEN) with a value of(15 - L).EVP_CTRL_COPYโ There's 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 with the key"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 with the key"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 with the key"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 with the key"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 with the key"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 with the key"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 with the key"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()get called with anOSSL_PARAM(3)item with the key"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). Two-step, stay with me. โจ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 with the keyOSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENTfollowed 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 with the keys"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 with the keys"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 bestie, so these three little icons โ EVP_CIPHER_CTX_set_flags(), EVP_CIPHER_CTX_clear_flags() and EVP_CIPHER_CTX_test_flags() โ are literally the vibe-check squad for flags. You use them to manipulate and test these EVP_CIPHER_CTX flags:
EVP_CIPH_NO_PADDINGโ this one's used byEVP_CIPHER_CTX_set_padding(). Head over to the "Gettable and Settable EVP_CIPHER_CTX parameters" section, underpadding, for the tea ๐ซEVP_CIPH_FLAG_LENGTH_BITSโ see the "Settable EVP_CIPHER_CTX parameters" section, underuse-bits.EVP_CIPHER_CTX_FLAG_WRAP_ALLOWโ legacy purposes only, no cap. Like, back in the day you had to set this flag to indicate that the cipher handled wrapping. That's it, that's the whole job.
Then there's EVP_CIPHER_flags(), which uses these following flags, and they've got mappings to "Gettable EVP_CIPHER parameters":
EVP_CIPH_FLAG_AEAD_CIPHERโ go see "Gettable EVP_CIPHER parameters",aead.EVP_CIPH_CUSTOM_IVโ go see "Gettable EVP_CIPHER parameters",custom-iv.EVP_CIPH_FLAG_CTSโ go see "Gettable EVP_CIPHER parameters",cts.EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK;โ go see "Gettable EVP_CIPHER parameters",tls-multi.EVP_CIPH_RAND_KEYโ go see "Gettable EVP_CIPHER parameters",has-randkey.
And EVP_CIPHER_flags() also uses these next ones for legacy purposes only (so, vintage era, respectfully ๐):
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
For further information related to all the flags right above, please see EVP_CIPHER_meth_set_flags(3). She's got the lore โจ
๐ RETURN VALUES
Time for the receipts, bestie โ who returns what, and when ๐
EVP_CIPHER_fetch()returns a pointer to aEVP_CIPHERfor success andNULLfor failure.EVP_CIPHER_up_ref()returns1for success or0otherwise.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()returns1if successful or0for failure.EVP_EncryptInit_ex2(),EVP_EncryptUpdate()andEVP_EncryptFinal_ex()return1for success and0for failure.EVP_DecryptInit_ex2()andEVP_DecryptUpdate()return1for success and0for failure.EVP_DecryptFinal_ex()returns0if the decrypt failed or1for success.EVP_CipherInit_ex2(),EVP_CipherInit_SKEY()andEVP_CipherUpdate()return1for success and0for failure.EVP_CipherFinal_ex()returns0for an encryption/decryption failure or1for success.EVP_Cipher()returns1on success and<= 0on failure โ that's 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. But if the flagEVP_CIPH_FLAG_CUSTOM_CIPHERis set for the cipher, thenEVP_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. Two completely different moods, iykyk ๐ญEVP_CIPHER_can_pipeline()returns1if the cipher can be used in a pipeline,0otherwise.EVP_CipherPipelineEncryptInit()andEVP_CipherPipelineDecryptInit()return1for success and0for failure.EVP_CipherPipelineUpdate()andEVP_CipherPipelineFinal()return1for success and0for failure.EVP_CIPHER_CTX_reset()returns1for success and0for 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, or0on error.EVP_CIPHER_get_key_length()andEVP_CIPHER_CTX_get_key_length()return the key length.EVP_CIPHER_CTX_set_padding()always returns1. Iconic. Unbothered. Consistent. ๐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()returns1on success and0if the implementation does not support the call or on any other error.EVP_CIPHER_CTX_is_encrypting()returns1if the ctx is set up for encryption,0otherwise.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()returns1for success and zero or a negative number for failure.EVP_CIPHER_names_do_all()returns1if the callback was called for all names. A return value of0means that the callback was not called for any names.
๐ CIPHER LISTING
Heads up, babe: all algorithms have a fixed key length unless otherwise stated. That's just the rules of the house ๐ โจ
And for the full list of ciphers available through the EVP interface, go peek at "SEE ALSO" โ she's got the directory, bestie.
EVP_enc_null()โ the Null cipher: does literally nothing. Zero thoughts, head empty, no encryption ๐ซง
โจ AEAD INTERFACE โจ
Okay so bestie, the EVP interface for Authenticated Encryption with Associated Data (AEAD) modes is subtly altered, and several additional ctrl operations are supported depending on the mode you specify. ๐
To specify additional authenticated data (AAD), make a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output parameter out set to NULL. In that case, on success, the parameter outl is set to the number of bytes authenticated. โจ
When decrypting, the return value of EVP_DecryptFinal() or EVP_CipherFinal() indicates whether the operation was successful. If it does not indicate success, the authentication operation has failed and any output data MUST NOT be used as it is corrupted. ๐ญ
Please note that the number of authenticated bytes returned by EVP_CipherUpdate() depends on the cipher used. Stream ciphers, such as ChaCha20 or ciphers in GCM mode, can handle 1 byte at a time, resulting in an effective "block" size of 1. Conversely, ciphers in OCB mode must process data one block at a time, and the block size is returned. ๐ฆ
Regardless of the returned size, it is safe to pass unpadded data to an EVP_CipherUpdate() call in a single operation. ๐
๐ GCM and OCB Modes ๐
The following ctrls are supported in GCM and OCB modes.
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)โ sets the IV length. This call can only be made before specifying an IV. If it is not called, a default IV length is used.
For GCM AES and OCB AES the default is 12 (i.e. 96 bits). For OCB mode the maximum is 15.
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)โ writestaglenbytes of the tag value to the buffer indicated bytag. This call can only be made when encrypting data and after all data has been processed (e.g. after anEVP_EncryptFinal()call).
For OCB, taglen must either be 16 or the value previously set via EVP_CTRL_AEAD_SET_TAG.
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)โ when decrypting, this call sets the expected tag totaglenbytes fromtag.taglenmust be between1and16inclusive. The tag must be set prior to 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 with tag set to NULL sets the tag length. The tag length can only be set before specifying an IV. If this is not called prior to setting the IV, then a default tag length is used.
For OCB AES, the default tag length is 16 (i.e. 128 bits). It is also the maximum tag length for OCB. ๐
๐ธ CCM Mode ๐ธ
The EVP interface for CCM mode is similar to that of the GCM mode but with a few additional requirements and different ctrl values.
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)โ this call is made to set the expected CCM tag value when decrypting or the length of the tag (with thetagparameter set toNULL) when encrypting. The tag length is often referred to as M. If not set, a default value is used (12for AES). When decrypting, the tag needs to be set before passing in data to be decrypted, but as in GCM and OCB mode, it can be set after passing additional authenticated data (see "AEAD INTERFACE").EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, ivlen, NULL)โ sets the CCM L value. If not set, a default is used (8for AES).EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)โ sets the CCM nonce (IV) length. This call can only be made before specifying a nonce value. The nonce length is given by15 - Lso it is7by default for AES.
๐ฆ SIV Mode ๐ฆ
Both the AES-SIV and AES-GCM-SIV ciphers fall under this mode. ๐
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, a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made 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.
When decrypting the return value of EVP_DecryptFinal() or EVP_CipherFinal() indicates if the operation was successful. If it does not 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 is 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.
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 that the plain text and cipher text lengths are identical. ๐
The following ctrls are supported in SIV mode, and are used 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) to the buffer indicated bytag. This call can only be made 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, thus, 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 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 than12bytes could be used to automatically pad the iv with leading0bytes to make it12bytes in length.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag)โ writestaglenbytes of the tag value to the buffer indicated bytag. This call can only be made when encrypting data and after all data has been processed (e.g. after anEVP_EncryptFinal()call).
taglen specified here must be 16 (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. This is because the code then becomes transparent to the cipher used and 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). ๐
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.
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 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. ๐
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 functions EVP_EncryptInit(), EVP_EncryptInit_ex(), EVP_EncryptFinal(), EVP_DecryptInit(), EVP_DecryptInit_ex(), EVP_CipherInit(), EVP_CipherInit_ex() and EVP_CipherFinal() are obsolete but are retained for compatibility with existing code. New code should use EVP_EncryptInit_ex2(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex2(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex2() and EVP_CipherFinal_ex() because they can reuse an existing context without allocating and freeing it up on each call.
There are some differences between functions EVP_CipherInit() and EVP_CipherInit_ex(), 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 is especially important for the EVP_CIPHER_CTX_FLAG_WRAP_ALLOW flag 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. ๐
EVP_get_cipherbynid(), and EVP_get_cipherbyobj() are implemented as macros.
๐ BUGS ๐
EVP_MAX_KEY_LENGTH and EVP_MAX_IV_LENGTH only refer to the internal ciphers with default key lengths. If custom ciphers exceed these values the results are unpredictable. This is because it has become standard practice to define a generic key as a fixed unsigned char array containing EVP_MAX_KEY_LENGTH bytes. ๐ญ
The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested for certain common S/MIME ciphers (RC2, DES, triple DES) in CBC mode.
๐ฌ EXAMPLES
Okay bestie, this is the part where it all comes together โ actual code, do not panic, I promise it slaps ๐
Encrypt a string using IDEA
Lowkey a classic. Look at it:
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 the outbuf + outlen in EVP_EncryptFinal_ex? That's the whole "don't overwrite your own freshly-encrypted data" thing โ it's giving main character energy and it matters, bestie ๐ซถ
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
Like, this one does both directions and it's so versatile for it:
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;
}
See the two-step init sitch? First call passes NULL for key and IV so you can peep the lengths, second call actually hands them over. That's the flex ๐
Encryption using AES-CBC with a 256-bit key with "CS1" ciphertext stealing
Ooh, ciphertext stealing, very demure, very mindful, very OSSL_PARAM ๐
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 note or perish:CTSmode does not support multiple calls toEVP_CipherUpdate()โ one call, that's it, that's the whole vibe. And remember the fetchedcipherneedsEVP_CIPHER_free(), no skipping ๐
๐ SEE ALSO
The whole friend group, fr fr:
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
Storytime, gather round, this is the lore ๐ธ
- Support for OCB mode 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 a 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.
โ ๏ธ heads up: that last one is a genuine "please don't do this on old versions" situation โ it's a crash, not a graceful error. Fix your version or fix your NULL ๐
ยฉ๏ธ COPYRIGHT
Copyright 2000-2025 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, bestie!! ๐โจ this whole iconic page is from OpenSSL 3.5.0, dated 2026-09-25, and it lives under the name EVP_ENCRYPTINIT(3ossl) โ go forth and encrypt responsibly, ily, mwah ๐๐ฆ
๐ฆ where this page comes from
- opensuse-leap 16.0: openssl-3-doc 3.5.0-160000.11.1 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms