carlogtt_python_library.utils.encryption module

Utilities for authenticated encryption and password hashing.

class carlogtt_python_library.utils.encryption.Cryptography(logger: Logger = <Logger carlogtt_python_library.utils.encryption (WARNING)>)[source]

Bases: object

Provides cryptographic functionalities including key generation, serialization for storage, encryption, decryption, and signing. Utilizes symmetric encryption (AES-256) and HMAC for signing.

Parameters:

logger – The logging.Logger instance to be used for logging the execution time of the decorated function. If not explicitly provided, the function uses Python’s standard logging module as a default logger.

create_key(key_type: KeyType, key_output: KeyOutputType) bytes[source]

Generates a cryptographic key of specified type and returns it in the specified output format.

Parameters:
  • key_type – The type of key to generate, affecting its length.

  • key_output – The output format of the generated key.

Returns:

The generated key in the specified output format.

create_token(length: int, validity_secs: int | float, now_epoch: float, key: bytes, population: Sequence = ()) dict[str, str | float][source]

Generates a secure token and its expiry time. The token is encrypted with a given key to produce a cipher token.

Parameters:
  • length – Length of the random token.

  • validity_secs – Time in seconds until the token expires.

  • key – The secret key used for encryption. Must be a 32-byte key for AES-256.

  • now_epoch – Current time in seconds since the epoch.

  • population – Lets you define a different set of characters that the token can be composed of. Default letters and digits

Raises:

ValueError – If length is greater than 62.

Returns:

A dictionary with ‘token’, ‘expiry’, and ‘ciphertoken’ keys.

decrypt_string(ciphertext: str, key: bytes, algorithm: EncryptionAlgorithm = EncryptionAlgorithm.AES_GCM, associated_data: bytes | None = None) str[source]

Decrypts a string previously encrypted by the encrypt_string function.

If a version prefix is present, auto-detect the algorithm:
  • v2:gcm:… → AES-GCM

  • v1:cbc:… → AES-CBC + HMAC (legacy)

  • v1:fernet:… → Fernet (legacy)

Otherwise, fall back to the provided algorithm.

Parameters:
  • ciphertext – The encrypted string to be decrypted. It is expected to be Base64 encoded.

  • key – The secret key used for decryption. Must match the key used for encryption and be appropriate for the specified algorithm.

  • algorithm – An instance of the EncryptionAlgorithm enum indicating the encryption algorithm to use. Default EncryptionAlgorithm.AES_GCM

  • associated_data – Additional authenticated data (AAD) to be authenticated but not encrypted. It must be provided as a byte string if used.

Returns:

The decrypted plaintext string. Returns an empty string and logs a warning if decryption fails.

deserialize_key_from_str_storage(key: str) bytes[source]

Converts a string representation of a bytes object back into the original bytes object. This function is intended to be used in conjunction with serialize_key_for_str_storage, allowing for the retrieval of the original bytes object from a stored string.

Parameters:

key – The string representation of the bytes object, expected to include the bytes literal prefix b’’.

Returns:

The original bytes object.

encrypt_string(plaintext: str, key: bytes, algorithm: EncryptionAlgorithm = EncryptionAlgorithm.AES_GCM, associated_data: bytes | None = None) str[source]

Encrypts plaintext using the selected algorithm and returns a versioned, Base64-url-safe string.

Envelope prefixes:
  • v2:gcm:… → AES-256-GCM (default)

  • v1:cbc:… → AES-256-CBC + HMAC-SHA256 (legacy)

  • v1:fernet:… → Fernet (legacy)

  • AES_GCM: expects a 32-byte key (AES-256-GCM). Optional AAD.

  • AES_256 (CBC+HMAC): expects a 32-byte key; integrity via HMAC.

  • AES_128 (Fernet): expects a 44-byte urlsafe base64-encoded key.

Parameters:
  • plaintext – The plaintext string to be encrypted.

  • key – The secret key used for encryption. The format and length depend on the algorithm being used.

  • algorithm – An instance of the EncryptionAlgorithm enum indicating the encryption algorithm to use. Default EncryptionAlgorithm.AES_GCM

  • associated_data – Additional authenticated data (AAD) to be authenticated but not encrypted. It must be provided as a byte string if used.

Returns:

The encrypted string, encoded with Base64 to ensure the encrypted data is text-safe.

hash_string(raw_string: str, key: bytes) str[source]

DEPRECATED — use hash_string_v2(). Note: the key parameter is ignored in this deprecated API.

Hashes a given string using the Scrypt Key Derivation Function

Parameters:
  • raw_string – The raw string to be hashed. Typically, this would be a password or any other sensitive information requiring secure handling.

  • key – The secret key used for hashing the hashed string. This key should be generated and managed using secure cryptographic practices and must be a 32-byte key for AES-256.

Returns:

The hash of the input string.

hash_string_v2(raw_string: str, scrypt_params: ScryptParamsType | None = None) str[source]

Hash a given string with scrypt and return a PHC-style string:

scrypt$ln=<n2exp>,r=<r>,p=<p>$<salt_b64>$<hash_b64>

A new 16-byte random salt is generated per given string.

Parameters:
  • raw_string – The raw string to be hashed. Typically, this would be a password or any other sensitive information requiring secure handling.

  • scrypt_params – The scrypt parameters to be used for hashing. If not provided, secure defaults are used.

Returns:

The hash of the input string PHC-style scrypt string.

re_encrypt_string(ciphertext_to_re_encrypt: str, old_key: bytes, new_key: bytes, old_algorithm: EncryptionAlgorithm = EncryptionAlgorithm.AES_256, new_algorithm: EncryptionAlgorithm = EncryptionAlgorithm.AES_256) str[source]

Re-encrypts data, transitioning it from an old key to a new key.

This function first decrypts the given encrypted data with the old key, then re-encrypts it using the new key. It supports key rotation and the update of the encryption scheme for securely stored data.

Ideal for key rotation or encryption scheme updates, ensuring data remains secure during key transitions or algorithm updates.

Parameters:
  • ciphertext_to_re_encrypt – Encrypted data with old key.

  • old_key – The old encryption key.

  • new_key – The new encryption key for re-encryption.

  • old_algorithm – An instance of the EncryptionAlgorithm enum indicating the encryption algorithm to use. Default EncryptionAlgorithm.AES_256

  • new_algorithm – An instance of the EncryptionAlgorithm enum indicating the encryption algorithm to use. Default EncryptionAlgorithm.AES_256

Returns:

Re-encrypted data as a string with the new key.

serialize_key_for_str_storage(key: bytes) str[source]

Converts a bytes object (key) to a string representation suitable for storage. Utilizes Python’s repr() function to create a string that represents the bytes object.

Parameters:

key – The bytes object to be serialized.

Returns:

A string representation of the bytes object, including the bytes literal prefix b’’.

sign(data_to_sign: bytes, key: bytes) bytes[source]

Signs the given data using HMAC with SHA256 hash function.

First, the data is encoded to Base64. Then, an HMAC signature is generated using the provided key and the SHA256 hash function. The data and its HMAC signature are concatenated, base64 encoded, and returned.

Parameters:
  • data_to_sign – Data to be signed.

  • key – Secret key used for HMAC.

Returns:

Base64 encoded signature of the data.

validate_hash_match(raw_string: str, hashed_to_match: str, key: bytes) bool[source]

DEPRECATED — use validate_hash_match_v2(). Note: the key parameter is ignored in this deprecated API.

Validates whether a provided raw string matches the hashed string stored.

Parameters:
  • raw_string – The plaintext string provided by the user, typically a password or sensitive information that needs validation against a stored, hashed version.

  • hashed_to_match – The hashed data that the raw_string is compared against.

  • key – The secret key used for hashing the hashed string.

Returns:

True if the raw_string, when hashed and processed, matches the hashed_string_to_match; False otherwise.

validate_hash_match_v2(raw_string: str, hashed_to_match: str) bool[source]

Verify a provided raw string against a PHC-style scrypt string in constant time.

Parameters:
  • raw_string – The plaintext string provided by the user, typically a password or sensitive information that needs validation against a stored, hashed version.

  • hashed_to_match – The hashed data that the raw_string is compared against.

Returns:

True if the raw_string, when hashed and processed, matches the hashed_string_to_match; False otherwise.

verify_signature(signature: bytes, key: bytes) dict[str, str | bool | bytes][source]

Verifies the signature of the provided data.

Decodes the signature from Base64, extracts the data and its HMAC signature, and verifies it using HMAC with SHA256. Returns a dict indicating whether the signature is valid, the original data, and the hash signature.

Parameters:
  • signature – Base64 encoded data and signature.

  • key – Secret key used for HMAC verification.

Returns:

A dictionary containing the verification result, the original data, and the hash signature with the keys ‘data’, ‘signature’, ‘signature_valid’, and possibly ‘response_info’ if an error occurs.

verify_token(token: str, ciphertoken: str, now_epoch: float, key: bytes) dict[str, str | float | bool][source]

Verifies the validity of the given token by decrypting the cipher token using the provided key, and checks if it’s expired based on the current time and the expiry time embedded in the cipher token.

Parameters:
  • token – The original token to be validated.

  • ciphertoken – The encrypted string containing the token and expiry.

  • now_epoch – Current time in seconds since the epoch.

  • key – The secret key used for encryption. Must be a 32-byte key for AES-256.

Returns:

A dictionary with the keys ‘token_valid’, ‘token’, ‘expiry’, and possibly ‘response_info’ if an error occurs.

class carlogtt_python_library.utils.encryption.EncryptionAlgorithm(*values)[source]

Bases: Enum

Defines supported encryption algorithms anf their envelope prefixes.

AES_128 = 'v1:fernet:'
AES_256 = 'v1:cbc:'
AES_GCM = 'v2:gcm:'
classmethod all_alg_prefixes() tuple[str, ...][source]
class carlogtt_python_library.utils.encryption.KeyOutputType(*values)[source]

Bases: Enum

Enumeration to specify the output format of the generated key.

BYTES

The key is returned as raw bytes.

BASE64

The key is returned as URL-safe Base64-encoded bytes.

BASE64 = 2
BYTES = 1
class carlogtt_python_library.utils.encryption.KeyType(*values)[source]

Bases: Enum

Enumeration to specify the key type based on its length.

AES128

Represents a key length of 128 bits (16 bytes) for AES encryption. This size is often used for its balance between security and performance.

AES256

Represents a key length of 256 bits (32 bytes) for AES encryption. Offers a high level of security and is recommended for situations requiring enhanced data protection.

INITIALIZATION_VECTOR

A 128-bit (16-byte) IV used in various encryption modes to ensure ciphertext uniqueness. Suitable for use with AES and other block ciphers in modes like CBC.

AES128 = 16
AES256 = 32
INITIALIZATION_VECTOR = 16