I'm attempting to read a text file into a string and then decrypt that string but it keeps failing and giving the following error
ValueError: Input strings must be a multiple of 16 in length
I know the encryption works because I've tested it so it has something to do with the Display_All function and presumably how the file is being read, any help would be really appreciated!
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
I realize there are much better ways of doing this and while I'm more than interested in learning about them my priority is simply learning pycryptos libraries which is why I decided to use an example I found here as a simple test. See below for a small example
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)
Produces the following output
b'ZiQ1nBUUx3Q+ZKeMlw2IXBlJoSXnWyTkWZsKVivFbENrVt78BV13/aLlFosw5v590y8WECu9f6U3D4sxlQhwbCNiDGSqMIm7Qids1aprD7JeAm/0mTpXhuF5nPJKqlylhweMsxfql7Ba6EplNyehnQ=='
This is just a quick dirty example
showing that the encryption does work