Random Byte String Generator with SHA256 Hashing

  • Share this:

Code introduction


Generate a random byte string of specified length using the SHA256 hash function and return the hash digest.


Technology Stack : cryptography, os

Code Type : Encryption 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

    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    random_bytes = os.urandom(length)
    digest.update(random_bytes)
    return digest.finalize()