Crypt module
On-the-fly AES256 CTR encryption with file-like interface.
-
class
crypt.AESFile(filename: str, mode: str, key: bytes, iv: Optional[bytes] = None)[source]
On-the-fly AES encryption (on read) and decryption (on write).
Uses CTR mode with 16 byte initial value (iv). When reading,
returns the iv first, then encrypted payload. On writing, first
16 bytes are assumed to contain the iv.
Does the bare minimum, you may get errors if not careful. See
Python’s io.IOBase for details on most methods.
- Parameters
filename (str) – File to open for reading (encrypt on the fly)
or writing (decrypt on the fly)
mode (str) – Either ‘rb’ or ‘wb’, just like with io.open()
key (bytes) – Encryption/decryption key (32 bytes for AES256)
iv (bytes) – Initial value (16 bytes), if not set uses os.urandom
- Returns
File-like object
- Return type
AESFile
-
close() → None[source]
Close the file stream.
-
read(size: int = - 1) → bytes[source]
Read data and encrypt on the fly. First 16 bytes returned are iv.
-
seek(offset: int, whence: int = 0) → None[source]
Seek to given position.
Only offset 0 is supported (relative to start, current position
or end depending on whence parameter). Otherwise dummy-encrypting
stuff might get really slow.
- Parameters
offset (int) – Offset, has to be 0
whence (int) – 0,1,2 for absolute,relative,end-based
- Raises
RuntimeError – If offset is nonzero
-
tell() → int[source]
Tell the current position.
Note that when reading, goes 16 bytes further than the file
being read, due to the fact that iv is injected to start.
-
write(data: bytes) → int[source]
Write data and decrypt on the fly. First 16 bytes absorbed as iv.
-
crypt.keygen(password: str, salt: str, iterations: int = 1000000) → bytes[source]
Generate a 32 byte key from password and salt using PBKDF2.
- Parameters
password (str) – Password string (encoded to utf8)
salt (str) – Salt (encoded to utf8)
iterations (int) – Number of iterations, 1M is the default
- Returns
32 byte key
- Return type
bytes