要給文件加密和解密,可以使用Python中的加密模塊如cryptography
或PyCrypto
。以下是一個(gè)使用PyCrypto
模塊進(jìn)行文件加密和解密的示例代碼:
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)
在上面的示例中,我們首先使用encrypt_file()
函數(shù)對輸入文件進(jìn)行加密,然后使用decrypt_file()
函數(shù)對加密后的文件進(jìn)行解密。在加密和解密過程中,我們使用AES加密算法和隨機(jī)生成的16字節(jié)密鑰。
請注意,加密和解密文件時(shí),務(wù)必保管好密鑰,以便正確解密文件。