我正在尝试将文本文件读入字符串然后解密该字符串,但它仍然失败并发出以下错误
ValueError: Input strings must be a multiple of 16 in length
我知道加密是有效的,因为我已经对它进行了测试,因此它与Display_All函数有关,并且可能是如何读取文件,任何帮助都会非常感激!
class Encryption(object):
def __init__(self, key):
self.blockSize = 32
self.key = key
def Encrypt(self, plainText):
plainText = self.Pad_Text(plainText)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(plainText))
def Decrypt(self, secretText):
secretText = base64.b64decode(secretText)
iv = secretText[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self.Unpad_Text(cipher.decrypt(secretText[AES.block_size:])).decode('utf-8')
def Pad_Text(self, text):
return text + (self.blockSize - len(text) % self.blockSize) * chr(self.blockSize - len(text) % self.blockSize)
@staticmethod
def Unpad_Text(text):
return text[:-ord(text[len(text)-1:])]
def Display_All():
try:
if sys.platform == 'win32':
if os.path.isdir("C:\\APV\\"):
file = open("C:\\APV\\Private.txt", "rb")
string = file.read()
plain = e.Decrypt(string)
displayWindow.insert('end', plain)
except OSError:
pass
return None
def Write_Test(event):
try:
if sys.platform == "win32":
if os.path.isdir("C:\\APV\\"):
file = open("C:\\APV\\Private.txt", "a")
temp2 = Test_entry.get()
encrypted = e.Encrypt(temp2)
file.write(str(encrypted) + "\n")
file.close()
Test_entry.delete(0, END)
except OSError:
pass
我意识到有更好的方法可以做到这一点,虽然我更感兴趣的是了解它们,但我的优先事项只是学习pycryptos库,这就是为什么我决定使用我在这里找到的一个例子作为一个简单的测试。请参阅下面的小例子
e = Encryption("!.o8d@c#)*=_FFsxc*@^;:12axcvbfd|")
tempTest = "This is just a quick dirty example\nshowing that the encryption does work"
random = e.Encrypt(tempTest)
print(random)
decrypted = e.Decrypt(random)
print("\n\n\n\n" + decrypted)
生成以下输出
b'ZiQ1nBUUx3Q+ZKeMlw2IXBlJoSXnWyTkWZsKVivFbENrVt78BV13/aLlFosw5v590y8WECu9f6U3D4sxlQhwbCNiDGSqMIm7Qids1aprD7JeAm/0mTpXhuF5nPJKqlylhweMsxfql7Ba6EplNyehnQ=='
This is just a quick dirty example
showing that the encryption does work