How to encrypt and decrypt using PyCrypto AES-256?

Sometimes, we want to encrypt and decrypt using PyCrypto AES-256.

In this article, we’ll look at how to encrypt and decrypt using PyCrypto AES-256.

How to encrypt and decrypt using PyCrypto AES-256?

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.

To install it, we run:

pip install pycryptodome

Then we can use it by writing:

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()


def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key=__key__, mode=AES.MODE_CFB, iv=iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(
        base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))


encrypted = encrypt('foo')
decrypted = decrypt(encrypted)
print(encrypted)
print(decrypted)

We create a key with the haslib.sha256 method with a binary string.

We call digest to return a hash of the key.

Then we call encrypt with the raw string to encrypt.

We encrypt by padding the string with the pad function.

Then we encode the string to base64 woth b64encode and encode.

Next, we call get_random_bytes to get some random bytes that we use to create the cipher.

Finally, we return the encrypted string which we generate with b64encode, iv and cipher.encrypt.

Then we define the decrypt function that has the unpad function to unpad the enc encrypted string.

Next, we call b64decode with enc to decode the encrypted string.

Then we get iv from the enc string by slicing it from index 0 to AES.block_size exclusively.

Then we call AES.new with the secret __key__, AES.MODE_CFB, and iv to get the cipher.

And we call unpad with the decoded cipher base64 cipher string to decrypt the string.

A regular string is returned since we called decode on the decrypted string.

Therefore, encrypted is b'zEMqurGW5NgwRwSAJ0lyejwF3Md02LtlC7oxP/SVJJVI/VLwQqpvvw=='

And decrypted is 'foo'.

Conclusion

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.