Secure Key Generation with PBKDF2HMAC, Scrypt, and HKDF

  • Share this:

Code introduction


The function generates a secure key from a password using PBKDF2HMAC, Scrypt, and HKDF algorithms, combining different key derivation functions to enhance security. The function also generates a salt to ensure that even with the same password, the generated key will be different.


Technology Stack : Cryptography library, PBKDF2HMAC, Scrypt, HKDF, secure key generation, password hashing, salt, SHA256

Code Type : Function

Code Difficulty :


                
                    
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import serialization

def generate_key_from_password(password, salt=None, iterations=100000):
    """
    Generate a secure key from a password using PBKDF2HMAC, Scrypt, and HKDF.
    """
    # If no salt is provided, generate a new one
    if salt is None:
        salt = os.urandom(16)

    # Generate key using PBKDF2HMAC
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=iterations,
        backend=default_backend()
    )
    key = kdf.derive(password.encode())

    # Generate a new key using Scrypt
    kdf_scrypt = Scrypt(
        salt=salt,
        length=32,
        n=2**14,
        r=8,
        p=1,
        backend=default_backend()
    )
    key_scrypt = kdf_scrypt.derive(password.encode())

    # Generate a new key using HKDF
    kdf_hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        info=b'handshake',
        backend=default_backend()
    )
    key_hkdf = kdf_hkdf.derive(password.encode())

    # Serialize the final key
    final_key = serialization.dumps(key_hkdf, encoding=serialization.Encoding.PEM)

    return final_key