Password Hashing with SHA-256 and PBKDF2_HMAC

  • Share this:

Code introduction


This function generates a hash value of a password using the SHA-256 algorithm and the pbkdf2_hmac function, used for password storage and verification.


Technology Stack : hashlib, os, math

Code Type : Password hash function

Code Difficulty : Intermediate


                
                    
import csv
import hashlib
import math
import os
import random
import re
import time

def hash_password(password):
    """
    使用内置的hashlib库生成密码的哈希值。

    :param password: str, 用户输入的密码
    :return: str, 密码的哈希值
    """
    # 使用SHA-256算法生成密码的哈希值
    salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
    pwdhash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
    pwdhash = pwdhash[:50].encode('ascii')
    return (salt + pwdhash).decode('ascii')                
              
Tags: