使用pycryptodome库,采用DES算法,实现文件的加密和解密
时间: 2024-02-18 19:05:16 浏览: 21
好的,下面是使用pycryptodome库,采用DES算法实现文件的加密和解密的示例代码:
```python
from Crypto.Cipher import DES
import os
# DES加密函数
def des_encrypt(key, data):
cipher = DES.new(key, DES.MODE_ECB)
return cipher.encrypt(data)
# DES解密函数
def des_decrypt(key, data):
cipher = DES.new(key, DES.MODE_ECB)
return cipher.decrypt(data)
# 加密文件
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
iv = os.urandom(8)
encryptor = DES.new(key, DES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 8 != 0:
chunk += b' ' * (8 - len(chunk) % 8)
outfile.write(encryptor.encrypt(chunk))
# 解密文件
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
iv = infile.read(8)
decryptor = DES.new(key, DES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate()
# 测试代码,加密并解密文件
if __name__ == '__main__':
key = b'abcdefgh'
encrypt_file(key, 'test.txt', 'test.txt.enc')
decrypt_file(key, 'test.txt.enc', 'test_decrypted.txt')
with open('test_decrypted.txt', 'r') as file:
print(file.read())
```
上述代码中,我们首先定义了DES加密和解密的函数,然后分别实现了文件加密和解密的函数。在加密文件时,我们使用了CBC模式,并在文件开头写入了一个随机生成的8字节的IV向量。在解密文件时,我们首先从文件中读取IV向量,然后使用该向量进行解密。
测试代码中,我们使用了一个8字节的密钥,对test.txt文件进行加密,并将加密结果输出到test.txt.enc文件中。然后,我们对test.txt.enc文件进行解密,并将解密结果输出到test_decrypted.txt文件中。最后,我们读取test_decrypted.txt文件的内容并打印出来。