Reputation:
I'm trying to make a high-level encryption and decryption class for a safe cloud share application project. And for the sake of using same key, nonce, and "authorized but unencrypted data" which I don't know what it means; I'm using this class. But, I couldn't understand why I'm getting InvalidTag exception. I'm restoring same values and doing decryption symmetrically. Interestingly it is working without class storing values in variables. What is the difference of restoring the same variable with the same value?
import os
from base64 import urlsafe_b64encode, urlsafe_b64decode
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
class cryptoUtils(AESGCM):
def __init__(self, key=None):
self.key = key if key else self.newKey()
self.nonce = os.urandom(12)
# Initialize AESGCM
super().__init__(self.key) <------------------
def encryptFile(self, fileName):
with open(fileName, "rb") as aFile:
pText = aFile.read()
eText = self.encrypt(self.nonce, pText, None)
newFile = "{}.enc".format(fileName)
with open(newFile, "wb") as bFile:
bFile.write(eText)
def decryptFile(self, fileName):
with open(fileName, "rb") as bFile:
eText = bFile.read()
pText = self.decrypt(self.nonce, eText, None)
newFile = fileName[0:-4]
with open(newFile, "wb") as aFile:
aFile.write(pText)
def exportKey(self):
key = "".join(map(chr, self.key))
nonce = "".join(map(chr, self.nonce))
str = "{}:{}".format(key, nonce)
return str
def importKey(self, input):
self.key = input.split(":")[0]
self.nonce = input.split(":")[1]
I'm importing this class in the main file and use it like:
from crypto import cryptoUtils
if __name__ == "__main__":
cu1 = cryptoUtils()
cu1.importKey("Gr0k6-ve8p7_5ysGEoLmnQ==:LylEffLP1a_fElsy")
cu1.encryptFile("T.pdf")
cu2 = cryptoUtils()
cu2.importKey("Gr0k6-ve8p7_5ysGEoLmnQ==:LylEffLP1a_fElsy")
cu2.decryptFile("T.pdf.enc")
Thanks.
Upvotes: 3
Views: 591
Reputation: 93968
You are forgetting to call super().__init__(self.key)
after importing the key. The key is set, but it is likely that the new key value is never directly used.
Please do not extend a class such as AESGCM
. Instead write a class that performs the required functionality using such a class. Then write test cases around the specific functionality, in this case encrypting / decrypting specific files.
Upvotes: 1