sio-2425/delivery1/lib/symmetric_encryption.py

54 lines
1.4 KiB
Python
Raw 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
# Function to derive a 256-bit key from a password and salt
2024-11-19 22:30:31 +00:00
def derive_key(salt):
2024-11-19 20:42:44 +00:00
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10000,
backend=default_backend()
)
2024-11-19 22:30:31 +00:00
return kdf.derive(b'')
2024-11-19 20:42:44 +00:00
2024-11-19 22:30:31 +00:00
# Function to encrypt a file using a salt
def encrypt_file(salt, input_file, output_file):
key = derive_key(salt)
2024-11-19 20:42:44 +00:00
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
with open(input_file, 'rb') as f:
plaintext = f.read()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
with open(output_file, 'wb') as f:
f.write(salt + iv + ciphertext)
2024-11-19 22:30:31 +00:00
# Function to decrypt a file
def decrypt_file(input_file, output_file=None):
2024-11-19 20:42:44 +00:00
with open(input_file, 'rb') as f:
encrypted_data = f.read()
salt = encrypted_data[:16]
iv = encrypted_data[16:32]
ciphertext = encrypted_data[32:]
2024-11-19 22:30:31 +00:00
key = derive_key(salt)
2024-11-19 20:42:44 +00:00
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
if output_file is None:
return plaintext
else:
with open(output_file, 'wb') as f:
f.write(plaintext)