See ya PyCrypto
My docker image cannot install PyCrypto anymore. It got an error "RuntimeError: autoconf error" and the issue said, "Don't use PyCrypto anymore."
https://github.com/pycrypto/pycrypto/issues/302
How to migrate Crypto.Cipher.AES
to Cryptography
As you know, the cryptography document is sucks as well. All I found was just cryptography.hazmat.primitives.ciphers.algorithms.AES
exists. No method nor example at all.
class
cryptography.hazmat.primitives.ciphers.algorithms.AES(key)
https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/
AES Encryption
I used AES.encrypt()
and AES.decrypt()
without any options. Later I noticed that I used AES's ECB mode. I was succeeded to migrate to cryptography without re-encrypting. Yay!
PyCrypto version
from Crypto.Cipher import AES
ENCRYPT_KEY = "9e3c8d04a37e057bb56d123456789012"
def aes_encrypt(data):
cipher = AES.new(ENCRYPT_KEY)
data = data + (" " * (16 - (len(data) % 16)))
return binascii.hexlify(cipher.encrypt(data))
def aes_decrypt(data):
cipher = AES.new(ENCRYPT_KEY)
return cipher.decrypt(binascii.unhexlify(data)).rstrip()
Cryptography Version
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
ENCRYPT_KEY = "9e3c8d04a37e057bb56d123456789012"
def cipher():
return Cipher(
algorithms.AES(str.encode(ENCRYPT_KEY)),
modes.ECB(),
default_backend()
)
def aes_encrypt(text: str) -> str:
encryptor = cipher().encryptor()
text = text + (" " * (16 - (len(text) % 16)))
password_bin = encryptor.update(str.encode(text)) + encryptor.finalize()
return binascii.hexlify(password_bin)
def aes_decrypt(text: str) -> str:
decryptor = cipher().decryptor()
message = decryptor.update(binascii.unhexlify(text)) + decryptor.finalize()
return message.rstrip()
I wish this helps someone in the world.
ref
I didn't know privacyIDEA but the source code helped me a lot. Thanks!
https://github.com/privacyidea/privacyidea/blob/7199be70bbe1ebee908518a8b529ac3637a86ca1/privacyidea/lib/crypto.py#L133
https://github.com/privacyidea/privacyidea/blob/7199be70bbe1ebee908518a8b529ac3637a86ca1/privacyidea/lib/importotp.py#L86
https://www.programcreek.com/python/example/94440/cryptography.hazmat.primitives.ciphers.Cipher