From 373d34dce6b0511f35e46899ff74b321a1854859 Mon Sep 17 00:00:00 2001 From: Shreya Malviya Date: Fri, 15 Jul 2022 11:17:43 +0530 Subject: [PATCH] Island: Use cryptography.fernet for encryption in KeyBasedEncryptor --- .../encryption/key_based_encryptor.py | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/monkey/monkey_island/cc/server_utils/encryption/key_based_encryptor.py b/monkey/monkey_island/cc/server_utils/encryption/key_based_encryptor.py index 164dbbb3b..a786f2ddd 100644 --- a/monkey/monkey_island/cc/server_utils/encryption/key_based_encryptor.py +++ b/monkey/monkey_island/cc/server_utils/encryption/key_based_encryptor.py @@ -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)