使用Python中的Cryptodome.Cipher.AES进行文件加密和解密
发布时间:2024-01-13 03:41:27
在Python中,可以使用Cryptodome库的Cipher模块来进行文件加密和解密。该模块提供了AES加密算法的实现。
首先,你需要确保安装了Cryptodome库。可以使用以下命令进行安装:
pip install pycryptodomex
下面是一个使用Cryptodome.Cipher.AES进行文件加密和解密的例子。
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
def encrypt_file(file_path, key):
# 生成16字节的初始化向量
iv = get_random_bytes(16)
# 创建一个AES加密对象
cipher = AES.new(key, AES.MODE_CBC, iv)
# 打开待加密的文件
with open(file_path, 'rb') as file:
plaintext = file.read()
# 加密文件内容并写入新文件
encrypted_data = cipher.encrypt(plaintext)
with open(file_path + '.encrypted', 'wb') as encrypted_file:
encrypted_file.write(iv + encrypted_data)
def decrypt_file(file_path, key):
# 打开待解密的文件
with open(file_path, 'rb') as encrypted_file:
ciphertext = encrypted_file.read()
# 读取初始化向量
iv = ciphertext[:16]
# 创建一个AES解密对象
cipher = AES.new(key, AES.MODE_CBC, iv)
# 解密文件内容并写入新文件
decrypted_data = cipher.decrypt(ciphertext[16:])
with open(file_path + '.decrypted', 'wb') as decrypted_file:
decrypted_file.write(decrypted_data)
# 测试代码
key = get_random_bytes(16) # 生成一个随机的16字节密钥
# 加密文件
encrypt_file('plaintext.txt', key)
print('文件已加密')
# 解密文件
decrypt_file('plaintext.txt.encrypted', key)
print('文件已解密')
上述代码中,我们使用了AES-CBC模式进行加密和解密操作。首先,我们生成了一个16字节的随机密钥。然后,我们通过调用encrypt_file函数来加密指定路径的文件。在加密过程中,我们生成一个16字节的随机初始化向量,并使用密钥和初始化向量创建一个AES加密对象。我们读取待加密文件的内容,加密数据,并将加密后的数据和初始化向量写入新文件。
接着,我们通过调用decrypt_file函数来解密加密文件。在解密过程中,我们读取加密文件的内容,并从中提取初始化向量。然后,我们使用密钥和初始化向量创建一个AES解密对象。我们解密文件的内容,并将解密后的数据写入新文件。
在上述代码示例中,我们加密了名为plaintext.txt的文件,并得到了一个新文件plaintext.txt.encrypted。然后,我们再对这个加密文件进行解密,并得到了一个新文件plaintext.txt.encrypted.decrypted。你可以根据自己的需求修改文件名和路径。
需要注意的是,加密算法的安全性与密钥的保密性有密切关系。确保你启用了适当的安全措施来保护你的密钥。
