下面是我使用python lib的Pycrypto模块编写的代码片段,用于加密和解密文件。
我能够加密文件,但是 decryption 逻辑似乎达不到要求。
第一阶段,我正在加密文件文本,即“ infile1.txt”,它可以按预期工作。在第二阶段,“ verifile1.txt”的输出不显示解密的文本。
import os, random, struct
from Crypto.Cipher import AES
from Crypto import Random
import hashlib
password = 'kitty'
key = hashlib.sha256(password.encode('utf-8')).digest()
%%writefile infile1.txt
ONE on FIRST
TWO on SECOND
THREE on THIRD
fsz = os.path.getsize('infile1.txt')
iv = Random.new().read(16)
encryptor = AES.new(key, AES.MODE_CBC, iv)
sz = 2048
#Encryptor Code
with open('encfile1.txt', 'wb') as fout:
fout.write(struct.pack('<Q', fsz))
fout.write(iv)
with open('infile1.txt') as fin:
while True:
data = fin.read(sz)
n = len(data)
if n == 0:
break
elif n % 16 != 0:
data += ' ' * (16 - n % 16)
encd = encryptor.encrypt(data)
fout.write(encd)
#Decryptor decode
with open('encfile1.txt','rb') as fin:
fsz = struct.unpack('<Q', fin.read(struct.calcsize('Q')))[0]
iv = fin.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open('verfile1.txt', 'wb') as fout:
while True:
data = fin.read(sz)
n = len(data)
if n == 0:
break
fout.write(decryptor.decrypt(data))
fout.truncate(fsz)