API Reference#
The public API of pyaescbc consists of the functions, classes and constants listed on this
page (they are the names exported in pyaescbc.__all__). Everything else is internal and may
change in any release.
To learn how to use the package, refer to Usage.
Password mode#
Encryption with a password. The key is derived with PBKDF2-HMAC-SHA256 on every call: slow on
purpose, to resist brute-force attacks. Produces PACB bundles.
- pyaescbc.encrypt(cleardata: bytearray, password: bytearray, *, authdata: bytearray | None = None, iterations: int = 600000, delete_keys: bool = True, delete_data: bool = True) bytearray#
Encrypts the clear data with a password into a password-mode bundle (format version 2).
salt, iv = random aes_key, hmac_key = derive_key(password, salt, iterations) cipherdata = AES-256-CBC(aes_key, iv, cleardata) header = magic | version | iterations | salt | iv hmac = HMAC-SHA256(hmac_key, header, cipherdata, authdata) encrypted_bundle = header | hmac | cipherdata
The number of iterations is stored in the bundle: it is not needed for decryption.
Note
An alias for this function is
encrypt.import pyaescbc cleardata = bytearray("Hello, World!", 'utf-8') password = bytearray("password", 'utf-8') authdata = bytearray("user=toto", 'utf-8') # optional encrypted_bundle = pyaescbc.encrypt(cleardata, password, authdata=authdata)
Note
Memory wiping is best-effort: Python and the underlying libraries may keep immutable copies of sensitive data.
- Parameters:
cleardata (bytearray) – The clear message to encrypt. It may be empty.
password (bytearray) – The user password. It must not be empty.
authdata (Optional[bytearray]) – Optional additional authenticated data (keyword-only). It is authenticated by the HMAC but neither encrypted nor stored in the bundle: the same value must be given for decryption. It is never modified by this function.
iterations (int) – The number of PBKDF2 iterations (keyword-only). Default is 600 000. Must be between 100 000 and 100 000 000.
delete_keys (bool) – Wipe the
passwordat the end of the function, even if an error occurs. Default is True.delete_data (bool) – Wipe the
cleardataat the end of the function, only if the encryption succeeded (the clear data is never destroyed when no encrypted bundle was produced). Default is True.
- Returns:
encrypted_bundle – The encrypted bundle.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If
passwordis empty oriterationsis out of the allowed range.
- pyaescbc.decrypt(encrypted_bundle: bytearray, password: bytearray, *, authdata: bytearray | None = None, delete_keys: bool = True, delete_data: bool = False) bytearray#
Decrypts a password-mode bundle (format version 2) and returns the clear data.
header | hmac | cipherdata = encrypted_bundle (structure checked first) aes_key, hmac_key = derive_key(password, salt, iterations) check HMAC-SHA256(hmac_key, header, cipherdata, authdata) == hmac (constant time) cleardata = AES-256-CBC-decrypt(aes_key, iv, cipherdata)
The number of iterations is read from the bundle. The cipherdata is decrypted only after the HMAC has been verified.
Note
An alias for this function is
decrypt.import pyaescbc password = bytearray("password", 'utf-8') authdata = bytearray("user=toto", 'utf-8') # same value as for encryption cleardata = pyaescbc.decrypt(encrypted_bundle, password, authdata=authdata)
Note
Memory wiping is best-effort: Python and the underlying libraries may keep immutable copies of sensitive data.
- Parameters:
encrypted_bundle (bytearray) – The password-mode bundle created by
pyaescbc.encrypt.password (bytearray) – The user password. It must not be empty.
authdata (Optional[bytearray]) – The additional authenticated data given at encryption, keyword-only (
Noneif none was given). It is never modified by this function.delete_keys (bool) – Wipe the
passwordat the end of the function, even if an error occurs. Default is True.delete_data (bool) – Wipe the
encrypted_bundleat the end of the function, only if the decryption succeeded (the bundle is never destroyed after a failed attempt, e.g. a mistyped password). Default is False: the bundle is not secret.
- Returns:
cleardata – The decrypted clear data.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If
passwordis empty or the bundle is malformed (unknown format or version, invalid length, iterations out of range).AuthError – If the password or the authdata is wrong, or if the bundle has been tampered with.
- pyaescbc.DEFAULT_ITERATIONS = 600000#
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Default number of PBKDF2 iterations (OWASP recommendation for PBKDF2-HMAC-SHA256).
- pyaescbc.MIN_ITERATIONS = 100000#
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Minimum number of PBKDF2 iterations accepted (prevents weak settings).
- pyaescbc.MAX_ITERATIONS = 100000000#
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Maximum number of PBKDF2 iterations accepted (prevents denial of service when the iteration count is read from an untrusted bundle).
Key mode#
Encryption with a random 32-byte key, without key derivation: each call takes microseconds.
Meant for envelope encryption (many secrets protected by a random data key, the data key itself
protected by a password with pyaescbc.encrypt()). Produces PACK bundles.
Warning
The key must come from pyaescbc.generate_key(). Never use a password as key: it
would get no brute-force protection. Use the password mode for passwords.
- pyaescbc.encrypt_with_key(cleardata: bytearray, key: bytearray, *, authdata: bytearray | None = None, delete_keys: bool = False, delete_data: bool = True) bytearray#
Encrypts the clear data with a random key into a key-mode bundle (no key derivation).
iv = random aes_key, hmac_key = expand_key(key) (HKDF-Expand, no PBKDF2) cipherdata = AES-256-CBC(aes_key, iv, cleardata) header = magic "PACK" | version | iv hmac = HMAC-SHA256(hmac_key, header, cipherdata, authdata) encrypted_bundle = header | hmac | cipherdata
The key mode is meant for envelope encryption: a random key (see
pyaescbc.generate_key) encrypts many small messages quickly, and the key itself is stored encrypted with a password usingpyaescbc.encrypt. Unlikepyaescbc.encrypt, there is no key derivation: each call takes microseconds.Warning
keymust be uniformly random (frompyaescbc.generate_key). Never use a password as key: it would be encrypted without any brute-force protection. Usepyaescbc.encryptfor passwords.Note
An alias for this function is
encrypt_with_key.import pyaescbc key = pyaescbc.generate_key() cleardata = bytearray("Hello, World!", 'utf-8') authdata = bytearray("entry=42", 'utf-8') # optional encrypted_bundle = pyaescbc.encrypt_with_key(cleardata, key, authdata=authdata)
Note
Memory wiping is best-effort: Python and the underlying libraries may keep immutable copies of sensitive data.
- Parameters:
cleardata (bytearray) – The clear message to encrypt. It may be empty.
key (bytearray) – The 32-byte random key.
authdata (Optional[bytearray]) – Optional additional authenticated data (keyword-only). It is authenticated by the HMAC but neither encrypted nor stored in the bundle: the same value must be given for decryption. It is never modified by this function.
delete_keys (bool) – Wipe the
keyat the end of the function, even if an error occurs. Default is False: a key-mode key is usually reused for many messages.delete_data (bool) – Wipe the
cleardataat the end of the function, only if the encryption succeeded (the clear data is never destroyed when no encrypted bundle was produced). Default is True.
- Returns:
encrypted_bundle – The key-mode encrypted bundle.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If
keyis not 32 bytes long.
- pyaescbc.decrypt_with_key(encrypted_bundle: bytearray, key: bytearray, *, authdata: bytearray | None = None, delete_keys: bool = False, delete_data: bool = False) bytearray#
Decrypts a key-mode bundle (key format version 1) and returns the clear data.
header | hmac | cipherdata = encrypted_bundle (structure checked first) aes_key, hmac_key = expand_key(key) check HMAC-SHA256(hmac_key, header, cipherdata, authdata) == hmac (constant time) cleardata = AES-256-CBC-decrypt(aes_key, iv, cipherdata)
The cipherdata is decrypted only after the HMAC has been verified.
Note
An alias for this function is
decrypt_with_key.import pyaescbc authdata = bytearray("entry=42", 'utf-8') # same value as for encryption cleardata = pyaescbc.decrypt_with_key(encrypted_bundle, key, authdata=authdata)
Note
Memory wiping is best-effort: Python and the underlying libraries may keep immutable copies of sensitive data.
- Parameters:
encrypted_bundle (bytearray) – The key-mode bundle created by
pyaescbc.encrypt_with_key.key (bytearray) – The 32-byte key used for encryption.
authdata (Optional[bytearray]) – The additional authenticated data given at encryption, keyword-only (
Noneif none was given). It is never modified by this function.delete_keys (bool) – Wipe the
keyat the end of the function, even if an error occurs. Default is False: a key-mode key is usually reused for many messages.delete_data (bool) – Wipe the
encrypted_bundleat the end of the function, only if the decryption succeeded (the bundle is never destroyed after a failed attempt). Default is False: the bundle is not secret.
- Returns:
cleardata – The decrypted clear data.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If
keyis not 32 bytes long, or the bundle is malformed or is a password-mode bundle (usepyaescbc.decryptfor those).AuthError – If the key or the authdata is wrong, or if the bundle has been tampered with.
- pyaescbc.generate_key() bytearray[source]#
Generates a random key for the key mode (
pyaescbc.encrypt_with_key).import pyaescbc key = pyaescbc.generate_key() # 32 random bytes
The key must be kept secret. To store it, encrypt it with a password using
pyaescbc.encrypt(“key wrapping”): the slow key derivation then runs once, when the key is unwrapped, instead of once per message.- Returns:
key –
KEY_SIZE(32) bytes from the operating system CSPRNG. Wipe it withpyaescbc.delete_bytearraywhen it is no longer needed.- Return type:
bytearray
- pyaescbc.KEY_SIZE = 32#
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Size in bytes of a key-mode key.
Both modes#
- class pyaescbc.AuthError(message: str = '', code: int | None = None)[source]#
Raised when the HMAC of a bundle does not match, i.e. when:
the password (
decrypt) or the key (decrypt_with_key) is wrong;the
authdatadiffers from the one given at encryption;or the bundle has been tampered with.
These cases are deliberately indistinguishable. A malformed bundle (wrong size, unknown magic or version) raises a
ValueErrorinstead, before any key derivation.The message is displayed as follows when a code is given:
AuthError: [<code>] <message>import pyaescbc try: cleardata = pyaescbc.decrypt(encrypted_bundle, password) except pyaescbc.AuthError: print("Wrong password.")
- Parameters:
message (str, optional) – The error message. Default is
"".code (Optional[int], optional) – An optional error code. Default is
None.
- message#
The error message.
- Type:
str
- code#
The error code, or
None.- Type:
Optional[int]
- pyaescbc.delete_bytearray(barray: bytearray) None[source]#
Overwrites the contents of a bytearray with zeros, then empties it.
After the call,
barrayis an empty bytearray (len(barray) == 0); the object itself still exists. If the bytearray cannot be resized because amemoryviewon it is still open, its contents are zeroed but its length is kept.Note
Wiping is best-effort: Python and the underlying libraries may have made immutable copies of the data, which cannot be erased.
import pyaescbc key = pyaescbc.generate_key() ... pyaescbc.delete_bytearray(key) # key == bytearray()
- Parameters:
barray (bytearray) – The bytearray to wipe.
- Raises:
TypeError – If the given argument is not a
bytearrayinstance.
- pyaescbc.__version__ = '3.0.0'#
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
Deprecated names#
The low-level building blocks that were public in pyaescbc 2.1 and earlier are now internal:
cleardata_to_encrypted_bundle, encrypted_bundle_to_cleardata, derive_key,
create_bundle_header, create_encrypted_bundle, extract_cryptography_components,
BundleComponents, create_hmac, check_hmac, random_bytearray, random_iv and
random_salt.
They can still be accessed as attributes of pyaescbc but emit a DeprecationWarning,
and will be removed in the next major version. Use pyaescbc.encrypt(),
pyaescbc.decrypt(), pyaescbc.encrypt_with_key() and pyaescbc.decrypt_with_key()
instead.
Bundle formats#
Both formats share the same layout: a format-specific header, the HMAC-SHA256 tag, then the AES-256-CBC cipherdata (PKCS7 padding). All integers are big-endian.
The magic identifies the format: pyaescbc.decrypt() rejects key-mode bundles and
pyaescbc.decrypt_with_key() rejects password-mode bundles, with an explicit
ValueError, before any computation.
Password-mode bundle (PACB, format version 2)#
offset size field
0 4 magic b"PACB"
4 1 version 2
5 4 iterations uint32
9 32 salt
41 16 iv
--------------------------- header (57 bytes, authenticated by the HMAC)
57 32 hmac HMAC-SHA256
89 16*n cipherdata AES-256-CBC, PKCS7 padding
The keys are derived from the password as follows:
master_key = PBKDF2-HMAC-SHA256(password, salt, iterations, 32)
aes_key = HKDF-Expand-SHA256(master_key, "pyaescbc v2 aes-256-cbc key", 32)
hmac_key = HKDF-Expand-SHA256(master_key, "pyaescbc v2 hmac-sha256 key", 32)
Key-mode bundle (PACK, format version 1)#
offset size field
0 4 magic b"PACK"
4 1 version 1
5 16 iv
--------------------------- header (21 bytes, authenticated by the HMAC)
21 32 hmac HMAC-SHA256
53 16*n cipherdata AES-256-CBC, PKCS7 padding
The keys are expanded from the 32-byte key, with labels distinct from the password mode (the same 32 bytes never give the same keys in both modes):
aes_key = HKDF-Expand-SHA256(key, "pyaescbc key-mode v1 aes-256-cbc key", 32)
hmac_key = HKDF-Expand-SHA256(key, "pyaescbc key-mode v1 hmac-sha256 key", 32)
There is no salt and no iteration count: the key is random, there is nothing to stretch.
HMAC (both formats)#
The HMAC authenticates the whole header, the cipherdata and the optional authdata, each
field prefixed by its length (8-byte big-endian), so that no byte can be moved from one field
to another:
hmac = HMAC-SHA256(hmac_key, len(header) || header
|| len(cipherdata) || cipherdata
|| len(authdata) || authdata)
The HMAC is verified in constant time before anything is decrypted. authdata is neither
encrypted nor stored in the bundle: the same value must be given to decrypt.