Island: Use cryptography.fernet for encryption in KeyBasedEncryptor

This commit is contained in:
Shreya Malviya 2022-07-15 11:17:43 +05:30
parent c1449fb897
commit 373d34dce6
1 changed files with 5 additions and 15 deletions

View File

@ -1,11 +1,6 @@
import base64
import logging
# PyCrypto is deprecated, but we use pycryptodome, which uses the exact same imports but
# is maintained.
from Crypto import Random # noqa: DUO133 # nosec: B413
from Crypto.Cipher import AES # noqa: DUO133 # nosec: B413
from Crypto.Util import Padding # noqa: DUO133
from cryptography.fernet import Fernet
from .i_encryptor import IEncryptor
@ -28,14 +23,9 @@ class KeyBasedEncryptor(IEncryptor):
self._key = key
def encrypt(self, plaintext: bytes) -> bytes:
cipher_iv = Random.new().read(AES.block_size)
cipher = AES.new(self._key, AES.MODE_CBC, cipher_iv)
padded_plaintext = Padding.pad(plaintext, self._BLOCK_SIZE)
return base64.b64encode(cipher_iv + cipher.encrypt(padded_plaintext))
fernet_object = Fernet(self._key)
return fernet_object.encrypt(plaintext.encode())
def decrypt(self, ciphertext: bytes) -> bytes:
enc_message = base64.b64decode(ciphertext)
cipher_iv = enc_message[0 : AES.block_size]
cipher = AES.new(self._key, AES.MODE_CBC, cipher_iv)
padded_plaintext = cipher.decrypt(enc_message[AES.block_size :])
return Padding.unpad(padded_plaintext, self._BLOCK_SIZE)
fernet_object = Fernet(self._key)
return fernet_object.decrypt(ciphertext)