API Reference#
The package pyaescbc is composed of the following functions, classes, and modules:
- exception pyaescbc.AuthError(message: str = '', code: int | None = None)[source]#
Exception raised for errors related to the decryption key in
pyaescbc.This exception is typically raised when the provided password or key is incorrect.
The display message will be shown in the following format if a code is provided:
AuthError: [<code>] <message>- Parameters:
message (str, optional) – The error message to be displayed. Default is “”
code (Optional[int], optional) – An optional error code associated with the exception. Default is None.
Notes
You can raise this exception when the HMAC verification fails during decryption, which usually means the wrong key was used (if the data were not
- pyaescbc.check_hmac(given_hmac: bytearray, expected_hmac: bytearray) bool[source]#
Verifies if the derived 32-byte given HMAC matches the expected HMAC.
- Parameters:
given_hmac (bytearray) – The 32-byte long HMAC to verify.
expected_hmac (bytearray) – The 32-byte long expected HMAC.
- Returns:
True if the HMACs match, False otherwise.
- Return type:
bool
- Raises:
TypeError – If any argument is not a bytearray instance.
ValueError – If the given_hmac or expected_hmac isn’t 32 bytes.
- pyaescbc.cleardata_to_encrypted_bundle(cleardata: bytearray, password: bytearray, iterations: int, authdata: bytearray | None = None, delete_keys: bool = True) bytearray[source]#
cleardata_to_encrypted_bundle encrypts the clear data to generate the encrypted bundle.
The number of iterations can be generated using the function
pyaescbc.generate_random_iterations()orpyaescbc.generate_pin_iterations().Note
The cleardata, the password and the authdata are deleted from memory at the end of the function if delete_keys is True. Otherwise, they need to be deleted after dealing with Exception.
Note
An alias for this function is
encryptimport pyaescbc as aes cleardata = bytearray("Hello, World!", 'utf-8') password = bytearray("password", 'utf-8') iterations = aes.generate_random_iterations() encrypted_bundle = aes.encrypt(cleardata, password, iterations, delete_keys=True) # Or use : encrypted_bundle = aes.cleardata_to_encrypted_bundle(cleardata, password, iterations, delete_keys=True)
- Parameters:
cleardata (bytearray) – The clear message to encrypt using AES in CBC mode.
password (bytearray) – The user password. It must not be empty.
iterations (int) – The number of iterations for PBKDF2. It must be a strictly positive integer.
authdata (Optional[bytearray]) – The authentication data to use in the HMAC. Default is None. If not None, it will be used to create the HMAC.
delete_keys (bool) – Delete the cleardata, the password and authdata from memory at the end of the function. Default is True.
- Returns:
encrypted_bundle – The encrypted bundle.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If password is empty or if iterations is not a strictly positive integer.
- pyaescbc.create_encrypted_bundle(iv: bytearray, salt: bytearray, expected_hmac: bytearray, cipherdata: bytearray) bytearray[source]#
Creates a bytearray containing all the information needed to decrypt the data.
The encrypted bundle is composed by the initialization vector (IV), the salt, the expected HMAC and the cipherdata.
See also
function
pyaescbc.extract_cryptography_components()to extract the components from the encrypted bundle.
- Parameters:
iv (bytearray) – The 16-byte initialization vector used for encryption.
salt (bytearray) – The 32-byte salt used to generate the derived key.
expected_hmac (bytearray) – The 32-byte expected HMAC.
cipherdata (bytearray) – The encrypted message.
- Returns:
encrypted_bundle – The concatenated bytearray containing iv + salt + expected_hmac + cipherdata.
- Return type:
bytearray
- Raises:
TypeError – If any argument is not a bytearray instance.
ValueError – If any of the components (salt, iv, hmac) are not the correct length.
- pyaescbc.create_hmac(hmac_key: bytearray, iv: bytearray, cipherdata: bytearray, authdata: bytearray | None = None) bytearray[source]#
Creates the expected HMAC using the hmac_key on the iv, cipherdata, and optional auth_data. The HMAC is created using the SHA-256 hash function. The HMAC is used to verify the integrity of the encrypted message. The hmac_key is extracted from the derived key, which is created using PBKDF2HMAC.
HMAC = HMAC(key, SHA256(iv + cipherdata + authdata))See also
-function
pyaescbc.derive_key()to create the derived key.- Parameters:
hmac_key (bytearray) – The 32-byte long key used to create the HMAC. It is extracted from the derived key.
iv (bytearray) – The 16-byte long initialization vector used for encryption.
cipherdata (bytearray) – The encrypted message.
authdata (Optional[bytearray]) – Optional additional authentication data. If provided, it is prepended to the HMAC input.
- Returns:
expected_hmac – The 32-byte expected HMAC value.
- Return type:
bytearray
- Raises:
TypeError – If any argument is not a bytearray instance.
ValueError – If the hmac_key isn’t 32 bytes, the IV isn’t 16 bytes.
- pyaescbc.decrypt(encrypted_bundle: bytearray, password: bytearray, iterations: int, authdata: bytearray | None = None, delete_keys: bool = True) bytearray#
encrypted_bundle_to_cleardata decrypts the encrypted bundle to generate the cleardata.
The number of iterations can be generated using the function
pyaescbc.generate_random_iterations()orpyaescbc.generate_pin_iterations().Note
The encrypted_bundle, the password and the authdata are deleted from memory at the end of the function if delete_keys is True. Otherwise, they need to be deleted after dealing with Exception.
Note
An alias for this function is
decryptimport pyaescbc as aes encrypted_bundle = bytearray(...) # The encrypted bundle password = bytearray(..., 'utf-8') # The user password used to encrypt the cipherdata and create the bundle iterations = ... # The number of iterations used to encrypt the cipherdata and create the bundle cleardata = aes.decrypt(encrypted_bundle, password, iterations, delete_keys=True) # Or use : cleardata = aes.encrypted_bundle_to_cleardata(encrypted_bundle, password, iterations, delete_keys=True)
- Parameters:
encrypted_bundle (bytearray) – The encrypted bundle to decrypt using AES in CBC mode. Must contain at least 80 bytes.
password (bytearray) – The user password. It must not be empty.
iterations (int) – The number of iterations for PBKDF2. It must be a strictly positive integer.
authdata (Optional[bytearray]) – The authentication data to use in the HMAC. Default is None. If not None, it will be used to create the HMAC.
delete_keys (bool) – Delete the encrypted_bundle, the password from memory at the end of the function. Default is True.
- Returns:
cleardata – The decrypted message using AES in CBC mode.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If password is empty, iterations is not a strictly positive integer, or encrypted_bundle does not contain more than 80 bytes.
- pyaescbc.decrypt_AES_CBC(cipherdata: bytearray, aes_key: bytearray, iv: bytearray) bytearray[source]#
Decrypts a cipherdata message using AES in CBC mode.
The data is unpadded using PKCS7 padding and then decrypted using AES in CBC mode. The aes_key is the first 32 bytes of the derived key, and the iv is the initialization vector.
See also
function
pyaescbc.derive_key()to create the derived key.Note
The cipherdata, aes_key and iv must be bytearrays.
- Parameters:
cipherdata (bytearray) – The encrypted message to decrypt using AES in CBC mode.
aes_key (bytearray) – The 32-byte AES key derived from the password, salt and iterations.
iv (bytearray) – The 16-byte initialization vector (IV) to use in AES-CBC mode.
- Returns:
cleardata – The decrypted clear message.
- Return type:
bytearray
- Raises:
TypeError – If a given argument is not a bytearray instance.
ValueError – If the aes_key isn’t 32 bytes long or the iv isn’t 16 bytes long.
- pyaescbc.delete_bytearray(barray: bytearray) None[source]#
Securely overwrites the contents of a bytearray and deletes the object from memory.
import pyaescbc as aes import os # Create a bytearray barray = bytearray(os.urandom(32)) # Example: 32 random bytes # Securely delete the bytearray aes.delete_bytearray(barray)
- Parameters:
barray (bytearray) – The bytearray to securely delete from memory.
- Raises:
TypeError – If the given argument is not a bytearray instance.
- pyaescbc.derive_key(password: bytearray, salt: bytearray, iterations: int) bytearray[source]#
Derives a 64-byte key from a password using PBKDF2HMAC. The algorithm used is SHA256.
The derived key is composed by the AES key and the HMAC key, both 32 bytes long. The AES key is used to encrypt or decrypt the data using AES in CBC mode. The HMAC key is used to create the HMAC to verify the integrity of the data.
By default, the input parameters are deleted from memory at the end of the function.
See also
-function
pyaescbc.encrypt_AES_CBC()to encrypt the data using AES in CBC mode. -functionpyaescbc.decrypt_AES_CBC()to decrypt the data using AES in CBC mode. -functionpyaescbc.create_hmac()to create the HMAC of the data.- Parameters:
password (bytearray) – The user password. It must not be empty.
salt (bytearray) – The 32-byte salt used to generate the derived key.
iterations (int) – The number of iterations for PBKDF2. It must be a strictly positive integer.
- Returns:
derived_key – The derived 64-byte key.
- Return type:
bytearray
- Raises:
TypeError – If the arguments are not of the correct types.
ValueError – If iterations is not a strictly positive integer, salt is not 32 bytes long, or password is empty.
- pyaescbc.encrypt(cleardata: bytearray, password: bytearray, iterations: int, authdata: bytearray | None = None, delete_keys: bool = True) bytearray#
cleardata_to_encrypted_bundle encrypts the clear data to generate the encrypted bundle.
The number of iterations can be generated using the function
pyaescbc.generate_random_iterations()orpyaescbc.generate_pin_iterations().Note
The cleardata, the password and the authdata are deleted from memory at the end of the function if delete_keys is True. Otherwise, they need to be deleted after dealing with Exception.
Note
An alias for this function is
encryptimport pyaescbc as aes cleardata = bytearray("Hello, World!", 'utf-8') password = bytearray("password", 'utf-8') iterations = aes.generate_random_iterations() encrypted_bundle = aes.encrypt(cleardata, password, iterations, delete_keys=True) # Or use : encrypted_bundle = aes.cleardata_to_encrypted_bundle(cleardata, password, iterations, delete_keys=True)
- Parameters:
cleardata (bytearray) – The clear message to encrypt using AES in CBC mode.
password (bytearray) – The user password. It must not be empty.
iterations (int) – The number of iterations for PBKDF2. It must be a strictly positive integer.
authdata (Optional[bytearray]) – The authentication data to use in the HMAC. Default is None. If not None, it will be used to create the HMAC.
delete_keys (bool) – Delete the cleardata, the password and authdata from memory at the end of the function. Default is True.
- Returns:
encrypted_bundle – The encrypted bundle.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If password is empty or if iterations is not a strictly positive integer.
- pyaescbc.encrypt_AES_CBC(cleardata: bytearray, aes_key: bytearray, iv: bytearray) bytearray[source]#
Encrypts a cleardata message using AES in CBC mode.
The cleardata is padded using PKCS7 padding and then encrypted using AES in CBC mode. The aes_key is the first 32 bytes of the derived key, and the iv is the initialization vector.
See also
function
pyaescbc.derive_key()to create the derived key.Note
The cleardata, aes_key and iv must be bytearrays.
- Parameters:
cleardata (bytearray) – The message to encrypt using AES in CBC mode.
aes_key (bytearray) – The 32-byte AES key derived from the password, salt and iterations.
iv (bytearray) – The 16-byte initialization vector (IV) to use in AES-CBC mode.
- Returns:
cipherdata – The encrypted message.
- Return type:
bytearray
- Raises:
TypeError – If a given argument is not a bytearray instance.
ValueError – If the aes_key isn’t 32 bytes long or the iv isn’t 16 bytes long.
- pyaescbc.encrypted_bundle_to_cleardata(encrypted_bundle: bytearray, password: bytearray, iterations: int, authdata: bytearray | None = None, delete_keys: bool = True) bytearray[source]#
encrypted_bundle_to_cleardata decrypts the encrypted bundle to generate the cleardata.
The number of iterations can be generated using the function
pyaescbc.generate_random_iterations()orpyaescbc.generate_pin_iterations().Note
The encrypted_bundle, the password and the authdata are deleted from memory at the end of the function if delete_keys is True. Otherwise, they need to be deleted after dealing with Exception.
Note
An alias for this function is
decryptimport pyaescbc as aes encrypted_bundle = bytearray(...) # The encrypted bundle password = bytearray(..., 'utf-8') # The user password used to encrypt the cipherdata and create the bundle iterations = ... # The number of iterations used to encrypt the cipherdata and create the bundle cleardata = aes.decrypt(encrypted_bundle, password, iterations, delete_keys=True) # Or use : cleardata = aes.encrypted_bundle_to_cleardata(encrypted_bundle, password, iterations, delete_keys=True)
- Parameters:
encrypted_bundle (bytearray) – The encrypted bundle to decrypt using AES in CBC mode. Must contain at least 80 bytes.
password (bytearray) – The user password. It must not be empty.
iterations (int) – The number of iterations for PBKDF2. It must be a strictly positive integer.
authdata (Optional[bytearray]) – The authentication data to use in the HMAC. Default is None. If not None, it will be used to create the HMAC.
delete_keys (bool) – Delete the encrypted_bundle, the password from memory at the end of the function. Default is True.
- Returns:
cleardata – The decrypted message using AES in CBC mode.
- Return type:
bytearray
- Raises:
TypeError – If an argument is of the wrong type.
ValueError – If password is empty, iterations is not a strictly positive integer, or encrypted_bundle does not contain more than 80 bytes.
- pyaescbc.extract_cryptography_components(encrypted_bundle: bytearray) Tuple[bytearray, bytearray, bytearray, bytearray][source]#
Extracts the IV, salt, expected HMAC, and cipherdata from the encrypted bundle.
See also
function
pyaescbc.create_encrypted_bundle()to create the encrypted bundle.
- Parameters:
encrypted_bundle (bytearray) – The encrypted bundle. Must contain at least 80 bytes.
- Returns:
A tuple containing the IV, salt, expected HMAC, and cipherdata.
- Return type:
tuple
- Raises:
TypeError – If the argument is not a bytearray instance.
ValueError – If the bytearray does not contain at least 80 bytes.
- pyaescbc.generate_pin_iterations(pin: bytearray, Nmin: int | None = None, Nmax: int | None = None, delete_keys: bool = True) int[source]#
Generates a number of iterations for PBKDF2 based on the PIN.
Use the following code to estimate the order of magnitude of the number of iterations. By default, the number of iterations is between 2,000,000 and 5,000,000 (valid for computers with 4GB of RAM in 2021). It is recommended to have a derived key generation time between 1 and 2 seconds to avoid brute force attacks withouth affecting the user experience.
Note
The PIN is deleted from memory at the end of the function if delete_keys is True. Otherwise, it needs to be deleted after dealing with Exception.
import pyaescbc import time import os password = pyaescbc.random_bytearray(32) salt = pyaescbc.random_salt() time_start = time.time() iteration = 2_000_000 # Change this value to the estimated number of iterations. pyaescbc.derive_key(password, salt, iteration) time_end = time.time() print(f'{iteration=}, {time_end-time_start=}')
- Parameters:
pin (bytearray) – The PIN to generate the number of iterations.
Nmin (Optional[int], optional) – The minimum number of iterations. The default is None -> 2,000,000.
Nmax (Optional[int]) – The maximum number of iterations. The default is None -> 5,000,000.
delete_keys (bool) – Delete the PIN from memory at the end of the function. Default is True. If False, it needs to be deleted after dealing with Exception.
- Returns:
iterations – The number of iterations based on the PIN.
- Return type:
int
- Raises:
TypeError – If Nmin or Nmax are not int instances or if pin is not a bytearray instance.
ValueError – If Nmin or Nmax are not positive integers or if Nmin is greater than Nmax.
- pyaescbc.generate_random_iterations(Nmin: int | None = None, Nmax: int | None = None) int[source]#
Generates a random number of iterations for PBKDF2.
The number of iterations is randomly generated between Nmin and Nmax.
Use the following code to estimate the order of magnitude of the number of iterations. By default, the number of iterations is between 2,000,000 and 5,000,000 (valid for computers with 4GB of RAM in 2021). It is recommended to have a derived key generation time between 1 and 2 seconds to avoid brute force attacks withouth affecting the user experience.
import pyaescbc import time import os password = pyaescbc.random_bytearray(32) salt = pyaescbc.random_salt() time_start = time.time() iteration = 2_000_000 # Change this value to the estimated number of iterations. pyaescbc.derive_key(password, salt, iteration) time_end = time.time() print(f'{iteration=}, {time_end-time_start=}')
- Parameters:
Nmin (Optional[int], optional) – The minimum number of iterations. The default is None -> 2,000,000.
Nmax (Optional[int]) – The maximum number of iterations. The default is None -> 5,000,000.
- Returns:
iterations – The random number of iterations.
- Return type:
int
- Raises:
TypeError – If Nmin or Nmax are not int instances.
ValueError – If Nmin or Nmax are not positive integers or if Nmin is greater than Nmax.
- pyaescbc.random_bytearray(Nbytes: int) bytearray[source]#
Generates a random bytearray of Nbytes length.
- Parameters:
Nbytes (int) – The number of bytes of the random bytearray. Must be a positive integer.
- Returns:
barray – A random bytearray of length Nbytes.
- Return type:
bytearray
- Raises:
TypeError – If Nbytes is not an integer.
ValueError – If Nbytes is not a positive integer.
- pyaescbc.random_iv() bytearray[source]#
Generates a random 16-byte initialization vector (IV) for AES encryption.
- Returns:
iv – A random 16-byte bytearray to be used as an IV.
- Return type:
bytearray
- pyaescbc.random_salt() bytearray[source]#
Generates a random 32-byte salt for cryptographic purposes.
- Returns:
salt – A random 32-byte bytearray to be used as a salt.
- Return type:
bytearray
To learn how to use the package effectively, refer to the documentation Usage.