Cipher
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
| Return | Name | Description |
|---|---|---|
Cipher | Constructs a Cipher with a randomly generated key and IV. | |
Cipher | Constructs a Cipher with an explicit key and initialization vector. | |
Cipher | Constructs a Cipher and derives a key and IV from a passphrase. | |
~Cipher | Destroys the Cipher and resets the OpenSSL context. | |
void | initEncryptor | Initializes the cipher context for encryption. |
void | initDecryptor | Initializes the cipher context for decryption. |
ssize_t | update | Processes a block of data through the cipher (encrypt or decrypt). |
ssize_t | update inline | Processes a block of data through the cipher using generic buffer types. |
ssize_t | final | Finalizes the cipher operation and flushes any remaining buffered data. |
ssize_t | final inline | Finalizes the cipher operation using a generic output buffer type. |
ssize_t | encrypt | Encrypts a buffer and writes the result with optional transport encoding. |
ssize_t | encrypt inline | Encrypts data using generic input/output buffer types. |
std::string | encryptString virtual | Encrypts a string and returns the result with optional transport encoding. |
std::string | decryptString virtual | Decrypts a string that was previously encrypted with optional encoding. |
void | encryptStream virtual | Encrypts all data from source and writes the result to sink. |
void | decryptStream virtual | Decrypts all data from source and writes the result to sink. |
void | setKey inline | Sets the encryption key. |
void | setIV inline | Sets the initialization vector (IV). |
int | setPadding | Enables or disables PKCS block padding. |
const ByteVec & | getKey const | Returns the raw encryption key bytes. |
const ByteVec & | getIV const | Returns the raw initialization vector bytes. |
const std::string & | name const | Returns the OpenSSL cipher name this object was constructed with. |
int | blockSize const | Returns the cipher block size in bytes. |
int | keySize const | Returns the required key length in bytes for this cipher. |
int | ivSize const | Returns the required initialization vector length in bytes. |
const EVP_CIPHER * | cipher | Returns the underlying OpenSSL EVP_CIPHER object. |
Cipher
Cipher(const std::string & name)Constructs a Cipher with a randomly generated key and IV.
Parameters
nameOpenSSL cipher name (e.g. "aes-256-cbc").
Exceptions
std::invalid_argumentif 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
nameOpenSSL cipher name (e.g. "aes-256-cbc").keyEncryption key; must match the cipher's required key length.ivInitialization vector; must match the cipher's IV length.
Exceptions
std::invalid_argumentif 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
nameOpenSSL cipher name (e.g. "aes-256-cbc").passphraseSecret passphrase for key derivation.saltOptional salt string; empty string means no salt. Values longer than 8 bytes are folded via XOR.iterationCountNumber of key-derivation iterations.
Exceptions
std::invalid_argumentif 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
inputPointer to the input data buffer.inputLengthNumber of bytes to process frominput.outputPointer to the output buffer.outputLengthSize of the output buffer in bytes.
Returns
Number of bytes written to output.
Exceptions
std::runtime_errorif 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
inputInput buffer (std::string, ByteVec, etc.).outputOutput 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
outputPointer to the output buffer; must be at least blockSize() bytes.lengthSize of the output buffer in bytes.
Returns
Number of bytes written to output.
Exceptions
std::runtime_errorif 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
outputOutput 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
inbufPointer to the plaintext input buffer.inlenNumber of bytes to encrypt frominbuf.outbufPointer to the output buffer.outlenSize of the output buffer in bytes.encodingTransport 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
inputInput buffer containing plaintext.outputOutput buffer; must be large enough for the result.encodingTransport 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
strPlaintext string to encrypt.encodingTransport 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
strCiphertext string to decrypt, in the format given byencoding.encodingTransport 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
sourceInput stream containing plaintext.sinkOutput stream to receive the encrypted (and encoded) data.encodingTransport 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
sourceInput stream containing ciphertext (in the given encoding).sinkOutput stream to receive the decrypted plaintext.encodingTransport encoding of the input data (default: Binary).
setKey
inline
template<typename T> inline void setKey(const T & key)Sets the encryption key.
Parameters
keyContainer whose size must exactly match keySize().
Exceptions
std::logic_errorif key.size() != keySize().
setIV
inline
template<typename T> inline void setIV(const T & iv)Sets the initialization vector (IV).
Parameters
ivContainer whose size must exactly match ivSize().
Exceptions
std::logic_errorif 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
paddingNon-zero to enable padding (default), zero to disable.
Returns
The return value from EVP_CIPHER_CTX_set_padding.
getKey
const
const ByteVec & getKey() constReturns the raw encryption key bytes.
Returns
Reference to the internal key byte vector.
getIV
const
const ByteVec & getIV() constReturns the raw initialization vector bytes.
Returns
Reference to the internal IV byte vector.
name
const
const std::string & name() constReturns the OpenSSL cipher name this object was constructed with.
Returns
Cipher name string (e.g. "aes-256-cbc").
blockSize
const
int blockSize() constReturns the cipher block size in bytes.
Returns
Block size as reported by EVP_CIPHER_block_size.
keySize
const
int keySize() constReturns the required key length in bytes for this cipher.
Returns
Key length as reported by EVP_CIPHER_key_length.
ivSize
const
int ivSize() constReturns 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
| Return | Name | Description |
|---|---|---|
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 _ivProtected Methods
| Return | Name | Description |
|---|---|---|
Cipher | Deleted constructor. | |
Cipher | Deleted constructor. | |
Cipher | Deleted constructor. | |
void | generateKey | Derives and sets the key and IV from a passphrase using EVP_BytesToKey. |
void | setRandomKey | Fills the key buffer with cryptographically random bytes. |
void | setRandomIV | Fills the IV buffer with cryptographically random bytes. |
void | init | Initializes or resets the OpenSSL cipher context for the given direction. |
Cipher
Cipher() = deleteDeleted constructor.
Cipher
Cipher(const Cipher &) = deleteDeleted constructor.
Cipher
Cipher(Cipher &&) = deleteDeleted 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
passphraseSecret passphrase for key derivation.saltSalt string (may be empty for no salt).iterationCountNumber 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
encrypttrue to initialize for encryption, false for decryption.
Public Types
Encoding
enum EncodingTransport encoding to use for encrypt() and decrypt().
| Value | Description |
|---|---|
Binary | Plain binary output. |
Base64 | Base64-encoded output. |
BinHex | BinHex-encoded output. |
Base64_NoLF | Base64-encoded output, no linefeeds. |
BinHex_NoLF | BinHex-encoded output, no linefeeds. |
