sio-2425/delivery1/lib/symmetric_encryption.py

47 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-11-19 20:42:44 +00:00
import os
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
2024-11-19 22:30:31 +00:00
# Function to encrypt a file using a salt
2024-11-20 19:46:18 +00:00
def encrypt_file(input_file, output_file=None):
key = os.urandom(16)
2024-11-19 20:42:44 +00:00
iv = os.urandom(16)
2024-11-20 19:46:18 +00:00
cipher = Cipher(algorithms.AES(key), modes.CFB(iv))
2024-11-19 20:42:44 +00:00
encryptor = cipher.encryptor()
with open(input_file, 'rb') as f:
plaintext = f.read()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
ciphertext = iv + ciphertext
2024-11-19 20:42:44 +00:00
2024-11-20 19:46:18 +00:00
if output_file is not None:
with open(output_file, 'wb') as f:
f.write(ciphertext)
print(iv.hex())
2024-11-20 19:46:18 +00:00
return key, ciphertext, iv
2024-11-19 20:42:44 +00:00
2024-11-19 22:30:31 +00:00
# Function to decrypt a file
def decrypt_file(nonce, key, input_file, output_file=None):
2024-11-19 20:42:44 +00:00
with open(input_file, 'rb') as f:
encrypted_data = f.read()
ciphertext = encrypted_data
2024-11-20 19:46:18 +00:00
cipher = Cipher(algorithms.AES(key), modes.CFB(nonce))
2024-11-19 20:42:44 +00:00
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
if output_file is not None:
2024-11-19 20:42:44 +00:00
with open(output_file, 'wb') as f:
f.write(plaintext)
return plaintext.hex()