使用Python编写的文件加密和解密程序
发布时间:2023-12-04 13:38:43
下面是一个使用Python编写的简单文件加密和解密程序,它使用了AES对称加密算法和base64编码来实现。
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
def encrypt_file(key, input_file, output_file):
cipher = AES.new(key, AES.MODE_CBC)
with open(input_file, 'rb') as f:
plaintext = f.read()
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
with open(output_file, 'wb') as f:
f.write(base64.b64encode(cipher.iv + ciphertext))
def decrypt_file(key, input_file, output_file):
with open(input_file, 'rb') as f:
ciphertext = base64.b64decode(f.read())
iv = ciphertext[:AES.block_size]
ciphertext = ciphertext[AES.block_size:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
with open(output_file, 'wb') as f:
f.write(plaintext)
# 使用例子
key = b'This is a 16-byte key' # 加密密钥,必须是16字节长度
input_file = 'input.txt' # 要加密的文件
encrypted_file = 'encrypted.bin' # 加密后的文件
decrypted_file = 'decrypted.txt' # 解密后的文件
# 加密文件
encrypt_file(key, input_file, encrypted_file)
# 解密文件
decrypt_file(key, encrypted_file, decrypted_file)
在上面的例子中,我们使用了Crypto模块中的AES类来进行加密和解密操作。它使用了CBC模式(Cipher Block Chaining)来对文件进行加密和解密,并使用了填充函数pad和unpad来确保文件的长度满足加密算法的要求。
在进行文件加密时,我们先将需要加密的文件读取出来,然后使用pad函数将文件内容进行填充,然后使用AES对象的encrypt方法进行加密,得到密文,最后将密文写入到输出文件中。
在进行文件解密时,我们先将需要解密的文件读取出来,然后使用base64解码得到密文和初始向量IV,然后使用AES对象的decrypt方法进行解密,得到明文,最后将明文写入到输出文件中。
需要注意的是,加密密钥必须是16字节长度,如果不是16字节,可以通过对密钥进行填充或截断来满足要求。
请注意,密码学涉及到安全性问题,本程序仅供学习和参考使用。
