PBKDF2HMAC Key Derivation with Random Bytes Generation

  • Share this:

Code introduction


This function derives a key from a random salt using the PBKDF2HMAC algorithm and then generates a specified number of random bytes using the derived key.


Technology Stack : cryptography, PBKDF2HMAC, SHA-256, urandom

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_bytes(length):
    from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.backends import default_backend
    from os import urandom

    # Generate a random salt
    salt = urandom(length // 2)
    
    # Derive a key using PBKDF2HMAC with SHA-256 hash algorithm
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=length,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    
    # Generate random bytes using the derived key
    key = kdf.derive(urandom(length // 2))
    
    return key