用Python编写一个简单的文件加密工具
发布时间:2023-12-04 17:01:27
下面是一个简单的文件加密工具的Python代码,该代码使用AES算法进行文件加密和解密。例子中,将一个名为plaintext.txt的文件加密,并将加密后的内容存储在名为encrypted.txt的文件中,然后将加密后的文件解密并输出到屏幕上。
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def encrypt_file(key, filename):
# 生成随机的IV向量
iv = os.urandom(16)
# 使用AES算法和CBC模式进行加密
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# 读取明文文件并加密
with open(filename, 'rb') as plainfile:
plaintext = plainfile.read()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
# 将加密后的内容和IV向量写入文件
with open('encrypted.txt', 'wb') as encryptedfile:
encryptedfile.write(iv)
encryptedfile.write(ciphertext)
def decrypt_file(key, filename):
# 使用AES算法和CBC模式进行解密
with open(filename, 'rb') as encryptedfile:
iv = encryptedfile.read(16)
ciphertext = encryptedfile.read()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
# 解密并输出到屏幕上
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
print(plaintext.decode())
# 主函数
def main():
# 假设密钥为16字节长度的字符串
key = b'This is a key123'
# 加密文件
encrypt_file(key, 'plaintext.txt')
print('File encrypted.')
# 解密文件
decrypt_file(key, 'encrypted.txt')
print('File decrypted.')
if __name__ == '__main__':
main()
在上面的代码中,需要使用到cryptography库,可以通过在命令行中运行pip install cryptography来安装该库。
使用例子中的代码进行加密和解密时,需要将要加密的文件放在同一目录下,并将其命名为plaintext.txt。执行代码后,会生成一个名为encrypted.txt的加密文件,并将解密后的内容输出到屏幕上。
请注意,这只是一个简单的文件加密工具的示例代码。实际应用中,需要进一步做一些安全性方面的考虑,例如使用更强的密钥、密钥的安全保存等。
