写两个脚本,用来使用指定秘钥为文本文件内容加密和解密,使用AES
时间: 2024-03-20 11:40:42 浏览: 87
好的,下面是使用AES加密和解密文本文件内容的Python脚本。请在使用前先安装 pyaes 库。
加密脚本:
```python
import pyaes
# 加密函数
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
iv = pyaes.AESModeOfOperationCTR.generate_nonce()
encryptor = pyaes.AESModeOfOperationCTR(key, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(encryptor.encrypt(chunk))
# 示例
key = b'This_is_a_secret_key'
in_filename = 'test.txt'
encrypt_file(key, in_filename)
```
解密脚本:
```python
import pyaes
# 解密函数
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:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = pyaes.AESModeOfOperationCTR(key, 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(origsize)
# 示例
key = b'This_is_a_secret_key'
in_filename = 'test.txt.enc'
decrypt_file(key, in_filename)
```
这两个脚本分别用于加密和解密指定的文本文件,使用AES算法,并使用指定的秘钥进行加密和解密。注意,这两个脚本必须在同一目录下使用。
阅读全文