You can download this code by clicking the button below.
This code is now available for download.
This function generates a random password and uses the SHA-256 algorithm to hash it, while also generating a salt for password storage and verification.
Technology Stack : string, hashlib, os
Code Type : Function
Code Difficulty : Intermediate
import datetime
import re
import math
import random
import string
import sys
import os
import hashlib
def generate_random_password(length=12):
if not isinstance(length, int) or length < 8:
raise ValueError("Password length must be an integer greater than or equal to 8.")
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for i in range(length))
def hash_password(password, salt=None):
if salt is None:
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
pwdhash = pwdhash[:50]
return (salt + pwdhash).decode('ascii')
def verify_password(stored_password, provided_password):
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha256',
provided_password.encode('utf-8'),
salt.encode('ascii'),
100000)
pwdhash = pwdhash[:50]
return pwdhash == stored_password