Random Bytes Generator with SHA-256 Hashing

  • Share this:

Code introduction


This function generates a random byte string of a specified length, then uses the SHA-256 hash function to generate a hash of the byte string, and finally returns the combination of the salt and the hash value.


Technology Stack : cryptography, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_bytes(length=32):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    import os
    
    # Generate a random salt
    salt = os.urandom(length // 2)
    
    # Use SHA-256 hash function to generate a hash of the salt
    hash_obj = hashes.Hash(hashes.SHA256(), backend=default_backend())
    hash_obj.update(salt)
    digest = hash_obj.finalize()
    
    # Return the combined salt and digest
    return salt + digest