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):
|
2024-11-20 23:52:00 +00:00
|
|
|
key = os.urandom(16)
|
2024-11-19 20:42:44 +00:00
|
|
|
iv = os.urandom(16)
|
2024-11-20 19:46:18 +00:00
|
|
|
|
2024-11-20 23:52:00 +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()
|
2024-11-20 23:52:00 +00:00
|
|
|
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:
|
2024-11-20 23:52:00 +00:00
|
|
|
f.write(ciphertext)
|
|
|
|
|
|
|
|
print(iv.hex())
|
2024-11-20 19:46:18 +00:00
|
|
|
|
2024-11-20 23:52:00 +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
|
2024-11-20 23:52:00 +00:00
|
|
|
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()
|
|
|
|
|
2024-11-20 23:52:00 +00:00
|
|
|
ciphertext = encrypted_data
|
2024-11-20 19:46:18 +00:00
|
|
|
|
2024-11-20 23:52:00 +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()
|
|
|
|
|
2024-11-20 23:52:00 +00:00
|
|
|
if output_file is not None:
|
2024-11-19 20:42:44 +00:00
|
|
|
with open(output_file, 'wb') as f:
|
|
|
|
f.write(plaintext)
|
2024-11-20 23:52:00 +00:00
|
|
|
|
|
|
|
return plaintext.hex()
|