Search code examples
python-3.xaesencryption-symmetric

AES encryption example class to encrypt data using user's password


In a Python 3 application I need to encrypt user's data using his own password. I'm using Cryptodome library.

Given that AES needs a fixed size key (128bit in the example), I used PBKDF2 to get the key. Below is the class I use in my code.

I store the salt (salt in the code) used for key derivation and the initialization vector (iv in the code) at the top of the message itself. Indeed, for what I understood (reading the docs here) neither the salt nor the iv must be kept secret.

Is this a correct approach or can you suggest me a better one?

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol import KDF

class crypto:
    def __init__(self,pwd):
        self.pwd = pwd

    def encrypt(self,data):
        salt = get_random_bytes(8)
        key = KDF.PBKDF2(self.pwd,salt) #128bit key derivation function
        iv = get_random_bytes(16)
        cipher = AES.new(key, AES.MODE_CFB, iv)
        return salt + iv + cipher.encrypt(data)

    def decrypt(self,msg):
        key = KDF.PBKDF2(self.pwd,msg[:8])
        cipher = AES.new(key, AES.MODE_CFB, msg[8:24])
        return cipher.decrypt(msg[24:])

Thanks in advance.


Solution

  • Yes, this is correct and a good practice and good method of providing the derivation salt and iv to the decryption code.

    PBKDF provides substantial security against brute force password attacks as well as a correct length key.