Crypto module

Cipher

Provides symmetric algorithms for encryption and decryption.

Cipher

#include <icy/crypto/cipher.h>

Provides symmetric algorithms for encryption and decryption. The algorithms that are available depend on the particular version of OpenSSL that is installed.

Public Methods

ReturnNameDescription
CipherConstructs a Cipher with a randomly generated key and IV.
CipherConstructs a Cipher with an explicit key and initialization vector.
CipherConstructs a Cipher and derives a key and IV from a passphrase.
~CipherDestroys the Cipher and resets the OpenSSL context.
voidinitEncryptorInitializes the cipher context for encryption.
voidinitDecryptorInitializes the cipher context for decryption.
ssize_tupdateProcesses a block of data through the cipher (encrypt or decrypt).
ssize_tupdate inlineProcesses a block of data through the cipher using generic buffer types.
ssize_tfinalFinalizes the cipher operation and flushes any remaining buffered data.
ssize_tfinal inlineFinalizes the cipher operation using a generic output buffer type.
ssize_tencryptEncrypts a buffer and writes the result with optional transport encoding.
ssize_tencrypt inlineEncrypts data using generic input/output buffer types.
std::stringencryptString virtualEncrypts a string and returns the result with optional transport encoding.
std::stringdecryptString virtualDecrypts a string that was previously encrypted with optional encoding.
voidencryptStream virtualEncrypts all data from source and writes the result to sink.
voiddecryptStream virtualDecrypts all data from source and writes the result to sink.
voidsetKey inlineSets the encryption key.
voidsetIV inlineSets the initialization vector (IV).
intsetPaddingEnables or disables PKCS block padding.
const ByteVec &getKey constReturns the raw encryption key bytes.
const ByteVec &getIV constReturns the raw initialization vector bytes.
const std::string &name constReturns the OpenSSL cipher name this object was constructed with.
intblockSize constReturns the cipher block size in bytes.
intkeySize constReturns the required key length in bytes for this cipher.
intivSize constReturns the required initialization vector length in bytes.
const EVP_CIPHER *cipherReturns the underlying OpenSSL EVP_CIPHER object.

Cipher

Cipher(const std::string & name)

Constructs a Cipher with a randomly generated key and IV.

Parameters

  • name OpenSSL cipher name (e.g. "aes-256-cbc").

Exceptions

  • std::invalid_argument if the cipher name is not recognized.

Cipher

Cipher(const std::string & name, const ByteVec & key, const ByteVec & iv)

Constructs a Cipher with an explicit key and initialization vector.

Parameters

  • name OpenSSL cipher name (e.g. "aes-256-cbc").

  • key Encryption key; must match the cipher's required key length.

  • iv Initialization vector; must match the cipher's IV length.

Exceptions

  • std::invalid_argument if the cipher name is not recognized.

Cipher

Cipher(const std::string & name, std::string_view passphrase, std::string_view salt, int iterationCount)

Constructs a Cipher and derives a key and IV from a passphrase.

Uses EVP_BytesToKey with SHA-256 to derive the key material.

Parameters

  • name OpenSSL cipher name (e.g. "aes-256-cbc").

  • passphrase Secret passphrase for key derivation.

  • salt Optional salt string; empty string means no salt. Values longer than 8 bytes are folded via XOR.

  • iterationCount Number of key-derivation iterations.

Exceptions

  • std::invalid_argument if the cipher name is not recognized.

~Cipher

~Cipher()

Destroys the Cipher and resets the OpenSSL context.


initEncryptor

void initEncryptor()

Initializes the cipher context for encryption.

Must be called before using update() and final() in encrypt mode. Calling this resets any prior context state.


initDecryptor

void initDecryptor()

Initializes the cipher context for decryption.

Must be called before using update() and final() in decrypt mode. Calling this resets any prior context state.


update

ssize_t update(const unsigned char * input, size_t inputLength, unsigned char * output, size_t outputLength)

Processes a block of data through the cipher (encrypt or decrypt).

Hand consecutive blocks of data to this method for streaming operation. The output buffer must be at least inputLength + [blockSize()](#blocksize) - 1 bytes. After all input is processed, call final() to flush any remaining buffered data from the cipher context.

Parameters

  • input Pointer to the input data buffer.

  • inputLength Number of bytes to process from input.

  • output Pointer to the output buffer.

  • outputLength Size of the output buffer in bytes.

Returns

Number of bytes written to output.

Exceptions

  • std::runtime_error if the output buffer is too small.

update

inline

template<typename I, typename O> inline ssize_t update(const I & input, O & output)

Processes a block of data through the cipher using generic buffer types.

Convenience wrapper around update(const unsigned char*, size_t, unsigned char*, size_t). Accepts any type supported by internal::Raw.

Parameters

  • input Input buffer (std::string, ByteVec, etc.).

  • output Output buffer; must be large enough for the result.

Returns

Number of bytes written to output.


final

ssize_t final(unsigned char * output, size_t length)

Finalizes the cipher operation and flushes any remaining buffered data.

Must be called after the last update() call to retrieve any trailing cipher block. Further calls to update() or final() after this point produce undefined results; call initEncryptor() / initDecryptor() to reset. The output buffer must be at least blockSize() bytes.

See EVP_CipherFinal_ex for further information.

Parameters

  • output Pointer to the output buffer; must be at least blockSize() bytes.

  • length Size of the output buffer in bytes.

Returns

Number of bytes written to output.

Exceptions

  • std::runtime_error if the output buffer is smaller than blockSize().

final

inline

template<typename O> inline ssize_t final(O & output)

Finalizes the cipher operation using a generic output buffer type.

Convenience wrapper around final(unsigned char*, size_t). Accepts any type supported by internal::Raw.

Parameters

  • output Output buffer; must hold at least blockSize() bytes.

Returns

Number of bytes written to output.


encrypt

ssize_t encrypt(const unsigned char * inbuf, size_t inlen, unsigned char * outbuf, size_t outlen, Encoding encoding)

Encrypts a buffer and writes the result with optional transport encoding.

Calls initEncryptor(), update(), and final() internally; the cipher does not need to be pre-initialized. The output buffer must be large enough to hold the encrypted and encoded result.

Parameters

  • inbuf Pointer to the plaintext input buffer.

  • inlen Number of bytes to encrypt from inbuf.

  • outbuf Pointer to the output buffer.

  • outlen Size of the output buffer in bytes.

  • encoding Transport encoding applied to the ciphertext (default: Binary).

Returns

Total number of bytes written to outbuf.


encrypt

inline

template<typename I, typename O> inline ssize_t encrypt(const I & input, O & output, Encoding encoding)

Encrypts data using generic input/output buffer types.

Convenience wrapper around encrypt(const unsigned char*, size_t, unsigned char*, size_t, Encoding). Accepts any type supported by internal::Raw.

Parameters

  • input Input buffer containing plaintext.

  • output Output buffer; must be large enough for the result.

  • encoding Transport encoding applied to the ciphertext (default: Binary).

Returns

Total number of bytes written to output.


encryptString

virtual

virtual std::string encryptString(const std::string & str, Encoding encoding)

Encrypts a string and returns the result with optional transport encoding.

Internally streams through encryptStream(); the cipher is re-initialized on each call.

Parameters

  • str Plaintext string to encrypt.

  • encoding Transport encoding for the output (default: Binary).

Returns

Encrypted (and optionally encoded) result as a std::string.


decryptString

virtual

virtual std::string decryptString(const std::string & str, Encoding encoding)

Decrypts a string that was previously encrypted with optional encoding.

Internally streams through decryptStream(); the cipher is re-initialized on each call.

Parameters

  • str Ciphertext string to decrypt, in the format given by encoding.

  • encoding Transport encoding of the input (default: Binary).

Returns

Decrypted plaintext as a std::string.


encryptStream

virtual

virtual void encryptStream(std::istream & source, std::ostream & sink, Encoding encoding)

Encrypts all data from source and writes the result to sink.

Reads in chunks of [blockSize()](#blocksize) * 128 bytes. Calls initEncryptor() internally; no prior initialization is required.

Parameters

  • source Input stream containing plaintext.

  • sink Output stream to receive the encrypted (and encoded) data.

  • encoding Transport encoding applied to the output (default: Binary).


decryptStream

virtual

virtual void decryptStream(std::istream & source, std::ostream & sink, Encoding encoding)

Decrypts all data from source and writes the result to sink.

Reads in chunks of [blockSize()](#blocksize) * 128 bytes. Calls initDecryptor() internally; no prior initialization is required.

Parameters

  • source Input stream containing ciphertext (in the given encoding).

  • sink Output stream to receive the decrypted plaintext.

  • encoding Transport encoding of the input data (default: Binary).


setKey

inline

template<typename T> inline void setKey(const T & key)

Sets the encryption key.

Parameters

  • key Container whose size must exactly match keySize().

Exceptions

  • std::logic_error if key.size() != keySize().

setIV

inline

template<typename T> inline void setIV(const T & iv)

Sets the initialization vector (IV).

Parameters

  • iv Container whose size must exactly match ivSize().

Exceptions

  • std::logic_error if iv.size() != ivSize().

setPadding

int setPadding(int padding)

Enables or disables PKCS block padding.

By default, encryption pads input to a block boundary and decryption strips and validates the padding. If padding is zero, no padding is applied; the total data length must then be an exact multiple of blockSize() or the operation will fail.

See EVP_CIPHER_CTX_set_padding for further information.

Parameters

  • padding Non-zero to enable padding (default), zero to disable.

Returns

The return value from EVP_CIPHER_CTX_set_padding.


getKey

const

const ByteVec & getKey() const

Returns the raw encryption key bytes.

Returns

Reference to the internal key byte vector.


getIV

const

const ByteVec & getIV() const

Returns the raw initialization vector bytes.

Returns

Reference to the internal IV byte vector.


name

const

const std::string & name() const

Returns the OpenSSL cipher name this object was constructed with.

Returns

Cipher name string (e.g. "aes-256-cbc").


blockSize

const

int blockSize() const

Returns the cipher block size in bytes.

Returns

Block size as reported by EVP_CIPHER_block_size.


keySize

const

int keySize() const

Returns the required key length in bytes for this cipher.

Returns

Key length as reported by EVP_CIPHER_key_length.


ivSize

const

int ivSize() const

Returns the required initialization vector length in bytes.

Returns

IV length as reported by EVP_CIPHER_iv_length.


cipher

const EVP_CIPHER * cipher()

Returns the underlying OpenSSL EVP_CIPHER object.

Returns

Pointer to the OpenSSL cipher descriptor; valid for the lifetime of this Cipher object.

Protected Attributes

ReturnNameDescription
bool_initialized
bool_encrypt
const EVP_CIPHER *_cipher
EvpCipherCtxPtr_ctx
std::string_name
ByteVec_key
ByteVec_iv

_initialized

bool _initialized

_encrypt

bool _encrypt

_cipher

const EVP_CIPHER * _cipher

_ctx

EvpCipherCtxPtr _ctx

_name

std::string _name

_key

ByteVec _key

_iv

ByteVec _iv

Protected Methods

ReturnNameDescription
CipherDeleted constructor.
CipherDeleted constructor.
CipherDeleted constructor.
voidgenerateKeyDerives and sets the key and IV from a passphrase using EVP_BytesToKey.
voidsetRandomKeyFills the key buffer with cryptographically random bytes.
voidsetRandomIVFills the IV buffer with cryptographically random bytes.
voidinitInitializes or resets the OpenSSL cipher context for the given direction.

Cipher

Cipher() = delete

Deleted constructor.


Cipher

Cipher(const Cipher &) = delete

Deleted constructor.


Cipher

Cipher(Cipher &&) = delete

Deleted constructor.


generateKey

void generateKey(std::string_view passphrase, std::string_view salt, int iterationCount)

Derives and sets the key and IV from a passphrase using EVP_BytesToKey.

Uses SHA-256 as the digest. Salt values longer than 8 bytes are folded by XOR into an 8-byte array as required by OpenSSL.

Parameters

  • passphrase Secret passphrase for key derivation.

  • salt Salt string (may be empty for no salt).

  • iterationCount Number of digest iterations.


setRandomKey

void setRandomKey()

Fills the key buffer with cryptographically random bytes.


setRandomIV

void setRandomIV()

Fills the IV buffer with cryptographically random bytes.


init

void init(bool encrypt)

Initializes or resets the OpenSSL cipher context for the given direction.

Parameters

  • encrypt true to initialize for encryption, false for decryption.

Public Types

NameDescription
EncodingTransport encoding to use for encrypt() and decrypt().

Encoding

enum Encoding

Transport encoding to use for encrypt() and decrypt().

ValueDescription
BinaryPlain binary output.
Base64Base64-encoded output.
BinHexBinHex-encoded output.
Base64_NoLFBase64-encoded output, no linefeeds.
BinHex_NoLFBinHex-encoded output, no linefeeds.