forked from p34709852/monkey
Island: Use cryptography.fernet for encryption in KeyBasedEncryptor
This commit is contained in:
parent
c1449fb897
commit
373d34dce6
|
@ -1,11 +1,6 @@
|
||||||
import base64
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
# PyCrypto is deprecated, but we use pycryptodome, which uses the exact same imports but
|
from cryptography.fernet import Fernet
|
||||||
# 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 .i_encryptor import IEncryptor
|
from .i_encryptor import IEncryptor
|
||||||
|
|
||||||
|
@ -28,14 +23,9 @@ class KeyBasedEncryptor(IEncryptor):
|
||||||
self._key = key
|
self._key = key
|
||||||
|
|
||||||
def encrypt(self, plaintext: bytes) -> bytes:
|
def encrypt(self, plaintext: bytes) -> bytes:
|
||||||
cipher_iv = Random.new().read(AES.block_size)
|
fernet_object = Fernet(self._key)
|
||||||
cipher = AES.new(self._key, AES.MODE_CBC, cipher_iv)
|
return fernet_object.encrypt(plaintext.encode())
|
||||||
padded_plaintext = Padding.pad(plaintext, self._BLOCK_SIZE)
|
|
||||||
return base64.b64encode(cipher_iv + cipher.encrypt(padded_plaintext))
|
|
||||||
|
|
||||||
def decrypt(self, ciphertext: bytes) -> bytes:
|
def decrypt(self, ciphertext: bytes) -> bytes:
|
||||||
enc_message = base64.b64decode(ciphertext)
|
fernet_object = Fernet(self._key)
|
||||||
cipher_iv = enc_message[0 : AES.block_size]
|
return fernet_object.decrypt(ciphertext)
|
||||||
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)
|
|
||||||
|
|
Loading…
Reference in New Issue