Usage#
All data, passwords and keys are bytearray objects, so that they can be wiped from memory
after use (see Wiping secrets from memory).
Password mode#
To encrypt data with a password, use pyaescbc.encrypt() and pyaescbc.decrypt().
This example is available in the examples directory of the repository:
"""
Password mode: encrypt and decrypt data with a password.
The key is derived from the password with PBKDF2 (slow on purpose, to resist brute-force
attacks). To encrypt many secrets, see encrypt_with_key.py.
Run from the repository root: python examples/encrypt.py
"""
import os
import sys
# Use the pyaescbc of this repository rather than an installed one
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pyaescbc
# --- Encryption -------------------------------------------------------------
cleardata = bytearray("Hello, World!", "utf-8")
password = bytearray("password", "utf-8")
authdata = bytearray("user=toto", "utf-8") # optional additional authenticated data (can be None)
encrypted_bundle = pyaescbc.encrypt(
cleardata,
password,
authdata=authdata,
iterations=2_000_000, # stored in the bundle: not needed to decrypt
delete_keys=True, # wipe the password (default)
delete_data=True, # wipe the clear data once encrypted (default)
)
assert len(cleardata) == 0 and len(password) == 0 # both wiped
# --- Decryption -------------------------------------------------------------
password = bytearray("password", "utf-8")
authdata = bytearray("user=toto", "utf-8") # same value as for encryption
decrypted_data = pyaescbc.decrypt(encrypted_bundle, password, authdata=authdata, delete_keys=True)
print(decrypted_data) # bytearray(b'Hello, World!')
# --- Wrong password ---------------------------------------------------------
try:
pyaescbc.decrypt(encrypted_bundle, bytearray("wrong password", "utf-8"), authdata=authdata)
except pyaescbc.AuthError:
print("Wrong password or authdata, or tampered data.")
print("This failed as expected.")
iterationssets the cost of the PBKDF2 key derivation:pyaescbc.DEFAULT_ITERATIONS(600 000) by default, betweenpyaescbc.MIN_ITERATIONS(100 000) andpyaescbc.MAX_ITERATIONS(100 000 000). It is stored in the bundle, so it is not needed to decrypt. A higher value makes brute-force attacks slower, but also every call.authdata(optional, keyword-only) is authenticated but neither encrypted nor stored: the same value must be given to decrypt. It binds the data to a context (a user, a record, a field).
Key mode: encrypting many secrets#
The password mode runs a slow key derivation on every call, by design. To encrypt many small
secrets (e.g. the entries of a password manager), use a random data key with
pyaescbc.encrypt_with_key() and pyaescbc.decrypt_with_key(), and protect that data
key once with the password (“envelope encryption”):
"""
Key mode: encrypt many secrets with a random key ("envelope encryption").
A random data key encrypts each secret without any key derivation (microseconds per call).
The data key itself is protected once with a password, using the password mode.
Run from the repository root: python examples/encrypt_with_key.py
"""
import os
import sys
# Use the pyaescbc of this repository rather than an installed one
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pyaescbc
# --- Creation (once) --------------------------------------------------------
# Random data key, wrapped with the password: one slow key derivation.
data_key = pyaescbc.generate_key() # 32 random bytes. NEVER use a password as key.
wrapped_key = pyaescbc.encrypt(data_key.copy(), bytearray("password", "utf-8"))
# Each secret is encrypted with the data key: fast, no key derivation.
# authdata binds each secret to its entry, so it cannot be swapped with another one.
entries = {"github": "gh-p4ssw0rd", "mail": "m41l-s3cr3t", "bank": "b4nk-c0de"}
vault = {
name: pyaescbc.encrypt_with_key(
bytearray(secret, "utf-8"),
data_key, # kept: reused for every secret
authdata=bytearray(f"entry={name}", "utf-8"),
)
for name, secret in entries.items()
}
pyaescbc.delete_bytearray(data_key) # end of the session
# --- Next session -----------------------------------------------------------
# One slow derivation to unwrap the data key, then every secret decrypts quickly.
data_key = pyaescbc.decrypt(wrapped_key, bytearray("password", "utf-8"))
for name, bundle in vault.items():
secret = pyaescbc.decrypt_with_key(bundle, data_key, authdata=bytearray(f"entry={name}", "utf-8"))
print(f"{name}: {secret.decode('utf-8')}")
pyaescbc.delete_bytearray(secret)
# A secret moved to another entry is detected
try:
pyaescbc.decrypt_with_key(vault["github"], data_key, authdata=bytearray("entry=bank", "utf-8"))
except pyaescbc.AuthError:
print("Swapped entries detected.")
print("This failed as expected.")
# --- Password change --------------------------------------------------------
# Only the data key is re-wrapped: the secrets are not re-encrypted.
wrapped_key = pyaescbc.encrypt(data_key.copy(), bytearray("new password", "utf-8"))
pyaescbc.delete_bytearray(data_key) # end of the session
The slow derivation runs once per session (to unwrap the data key), not once per secret.
Changing the password only re-wraps the data key: the secrets are not re-encrypted.
To make an old password useless even against old copies of the data, generate a new data key and re-encrypt the secrets with it: this is fast in key mode.
authdatacan bind each secret to its location (e.g."entry=42"), so that a ciphertext cannot be moved to another entry unnoticed.
Warning
The key must come from pyaescbc.generate_key(). Never use a password as key: it
would get no brute-force protection.
Handling errors#
import pyaescbc
try:
cleardata = pyaescbc.decrypt(encrypted_bundle, password)
except pyaescbc.AuthError:
... # wrong password or authdata, or the bundle has been tampered with
except ValueError:
... # not a valid bundle (wrong size, unknown format or version, bundle of the other mode)
pyaescbc.AuthError covers every authentication failure on purpose: a wrong password,
a wrong authdata and a modified bundle cannot be told apart. A ValueError is raised
before any key derivation when the bundle is malformed, or when a bundle of one mode is given to
the other mode (for example: “this is a key-mode bundle, use decrypt_with_key()”).
Wiping secrets from memory#
By default:
pyaescbc.encrypt()wipescleardataandpasswordonce the encryption succeeded;pyaescbc.decrypt()wipespassword;pyaescbc.encrypt_with_key()wipescleardatabut keepskey(reused for many messages);pyaescbc.decrypt_with_key()keepskey.
Use delete_keys and delete_data to change this behaviour. The clear data and the bundle
are never wiped when the operation fails (for example after a mistyped password), so that the
call can be retried. Use pyaescbc.delete_bytearray() to wipe your own secrets, such as
the decrypted data once used:
cleardata = pyaescbc.decrypt(encrypted_bundle, password)
... # use cleardata
pyaescbc.delete_bytearray(cleardata) # cleardata == bytearray()
Note
Wiping is best-effort: Python and the underlying libraries may keep immutable copies of sensitive data, which cannot be erased.
Type conversion#
If your clear data is a string, convert it to a bytearray before encrypting it:
cleardata = bytearray("Hello, World!", "utf-8")
After decrypting, convert the bytearray back to a string:
text = cleardata.decode("utf-8")
print(text) # Hello, World!
Storing a bundle#
An encrypted bundle is binary data: it is not valid UTF-8 and cannot be decoded as text. Store
it as bytes in a file or a database, and read it back as a bytearray:
from pathlib import Path
Path("secret.bin").write_bytes(encrypted_bundle)
encrypted_bundle = bytearray(Path("secret.bin").read_bytes())
To store it as text (JSON, a text column, a configuration file…), encode it in base64:
import base64
text = base64.b64encode(encrypted_bundle).decode("ascii") # bytearray -> str
encrypted_bundle = bytearray(base64.b64decode(text)) # str -> bytearray