sio-2425/delivery2/server/utils/comms_encryption.py

38 lines
1.1 KiB
Python

import json
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from utils import encrypt, decrypt
def encrypt_response(payload: json, code: int, key):
payload_str = json.dumps(payload)
encrypted = encrypt(payload_str.encode(), key).hex()
return encrypted, code
def decrypt_request(data: str, key):
return json.loads(decrypt(bytes.fromhex(data), key).decode())
def encrypt_response_with_iv(input_string: str, code: int) -> tuple[str, int]:
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(iv), modes.CFB(iv))
encryptor = cipher.encryptor()
plaintext_bytes = input_string.encode('utf-8')
ciphertext = encryptor.update(plaintext_bytes) + encryptor.finalize()
encrypted_data = iv + ciphertext
return encrypted_data.hex(), code
def decrypt_request_with_iv(encrypted_data: bytes) -> str:
iv = encrypted_data[:16]
ciphertext = encrypted_data[16:]
cipher = Cipher(algorithms.AES(iv), modes.CFB(iv))
decryptor = cipher.decryptor()
plaintext_bytes = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext_bytes.decode('utf-8')