hakk

software development, devops, and other drivel
Tree lined path

How to Generate a 32-byte Key for AES Encryption

Generating a 32-byte key for AES encryption from a password using only built-in Python modules. To do this we’ll use the hashlib library. For this approach we’ll use the PBKDF2 (Password-Based Key Derivation Function 2) via hashlib.pbkdf2_hmac. This ensures that the key is securely derived from the password.

Here’s some example code:

import os
import hashlib

def generate_aes_key(password: str, salt: bytes = None, iterations: int = 100_000) -> bytes:
    """
    Generate a 32-byte AES key from a password using PBKDF2-HMAC-SHA256.

    :param password: The password to derive the key from.
    :param salt: A unique salt (16 bytes recommended). If None, a random salt will be generated.
    :param iterations: The number of iterations for the key derivation function.
    :return: A tuple containing the derived key and the salt used.
    """
    if salt is None:
        salt = os.urandom(16)  # Generate a random 16-byte salt if not provided

    # Use PBKDF2 with HMAC-SHA256 to derive the key
    key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations, dklen=32)
    return key, salt

# Example usage
password = "securepassword"
key, salt = generate_aes_key(password)

print("Derived Key (hex):", key.hex())
print("Salt (hex):", salt.hex())

I preferred to use this approach to avoid any external dependencies.