Essetee's Website

Creating random strings or hashes

With your editor of choice paste the following content:

import hashlib
import random
import string


def generate_random_string(length=32):
    """Generate a random string of fixed length."""
    letters = string.ascii_lowercase + string.digits  # Characters to choose from
    return "".join(random.choice(letters) for _ in range(length))


def generate_secure_hash(length=32):
    """Generate a random string of fixed length using a cryptographic hash."""
    # Generate a secure hash and truncate it to the desired length
    hasher = hashlib.sha256()
    hasher.update(str(random.getrandbits(256)).encode("utf-8"))
    return hasher.hexdigest()[:length]

Usage

var = generate_random_string()
print(var)

var = generate_secure_hash()
print(var)