0
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import os

class EncryptionManager:
    def __init__(self):
        key = os.urandom(32)
        iv = os.urandom(16)
        aesContext = Cipher(algorithms.AES(key),
        modes.CBC(iv),
        backend=default_backend())
        self.encryptor = aesContext.encryptor()
        self.decryptor = aesContext.decryptor()
        self.padder = padding.PKCS7(128).padder()
        self.unpadder = padding.PKCS7(128).unpadder()

    def update_encryptor(self, plaintext):
        return self.encryptor.update(self.padder.update(plaintext))

    def finalize_encryptor(self):
        return self.encryptor.update(self.padder.finalize()) + self.encryptor.finalize()

    def update_decryptor(self, ciphertext):
        return self.unpadder.update(self.decryptor.update(ciphertext))

    def finalize_decryptor(self):
        return self.unpadder.update(self.decryptor.finalize()) + self.unpadder.finalize()
 
# Auto generate key/IV for encryption
manager = EncryptionManager()

plaintexts = [
b"SHORT",
b"MEDIUM MEDIUM MEDIUM",
b"LONG LONG LONG LONG LONG LONG"
]

ciphertexts = []

for m in plaintexts:
    ciphertexts.append(manager.update_encryptor(m))
    ciphertexts.append(manager.finalize_encryptor())

for c in ciphertexts:
    print("Recovered", manager.update_decryptor(c))
    print("Recovered", manager.finalize_decryptor())

And always this exception raise:

raise AlreadyFinalized("Context was already finalized.") cryptography.exceptions.AlreadyFinalized: Context was already finalized.

This error raise when the for loop in the second item in "plaintext" list.

for m in plaintexts:
    ciphertexts.append(manager.update_encryptor(m)) # If m == plaintexts[1] the exception raise here
    ciphertexts.append(manager.finalize_encryptor())
  • It means that you need a new encryptor or decryptor instance. You cannot reuse the instance after finalizing. It also means that you have to redesign your class. The key and IV have to be handled differently. You will also have at least twice as many (broken) ciphertexts than plaintexts which you are also probably not aware. What do you need that class for? Can you describe the use case? – Artjom B. Feb 26 '21 at 16:30
  • I'm new to cryptography Science. If you have time can you explain me more. I will be grateful. – zahir 9 Feb 26 '21 at 17:56
  • I did fix the problem but i don't understand well. – zahir 9 Feb 26 '21 at 18:10
  • I don't know how to use deferent key an IV. – zahir 9 Feb 26 '21 at 18:21

0 Answers0