Ressenger/ressenger_cryptography.py

24 lines
825 B
Python
Executable File

#!/usr/bin/python3
from Cryptodome.Cipher import AES
from Cryptodome.Protocol.KDF import PBKDF2
from Cryptodome.Random import get_random_bytes
from Cryptodome.Util.Padding import pad, unpad
def encrypt_bytes(data: bytes, password: str, *, salt: bytes = None) -> bytes:
if salt is None:
salt = get_random_bytes(16)
key = PBKDF2(password, salt, dkLen=32, count=100_000)
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(data, AES.block_size))
return salt + iv + ct
def decrypt_bytes(token: bytes, password: str) -> bytes:
salt = token[:16]
iv = token[16:32]
ct = token[32:]
key = PBKDF2(password, salt, dkLen=32, count=100_000)
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
return pt