Python File Encryption & Decryption Guide
To encrypt and decrypt files, you can use encryption modules like cryptography or PyCrypto in Python. Below is an example code using the PyCrypto module for file encryption and decryption.
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_file(input_file, output_file, key):
cipher = AES.new(key, AES.MODE_EAX)
with open(input_file, 'rb') as f_in:
data = f_in.read()
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)
with open(output_file, 'wb') as f_out:
f_out.write(nonce)
f_out.write(tag)
f_out.write(ciphertext)
def decrypt_file(input_file, output_file, key):
with open(input_file, 'rb') as f_in:
nonce = f_in.read(16)
tag = f_in.read(16)
ciphertext = f_in.read()
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
with open(output_file, 'wb') as f_out:
f_out.write(data)
# Generate a random key
key = get_random_bytes(16)
# Encrypt a file
encrypt_file('input.txt', 'encrypted.txt', key)
# Decrypt the encrypted file
decrypt_file('encrypted.txt', 'output.txt', key)
In the example above, we first encrypt the input file using the encrypt_file() function, and then decrypt the encrypted file using the decrypt_file() function. During the encryption and decryption process, we utilize the AES encryption algorithm and a randomly generated 16-byte key.
Please make sure to keep the encryption key secure when encrypting and decrypting files to ensure correct decryption of the files.