zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python:bcrypt对密码进行加密和校验

2023-09-14 09:07:13 时间

Modern(-ish) password hashing for your software and your servers

译文:软件和服务器的现代(-ish)密码哈希

文档:

安装

pip install bcrypt

使用示例

# -*- coding: utf-8 -*-

import bcrypt

passwd = '123456'

# 加密过程
salt = bcrypt.gensalt(rounds=10)
hashed = bcrypt.hashpw(passwd.encode(), salt)

print(salt)
# b'$2b$12$BlfmESsgNnsQFCmpUnhDWO'

print(hashed)
# b'$2b$12$BlfmESsgNnsQFCmpUnhDWO2RbacoHJViT8AZR1qh3DDOHnZxB.J5q'

# 校验过程
ret = bcrypt.checkpw(passwd.encode(), hashed)

print(ret) # True

封装成工具函数

# -*- coding: utf-8 -*-
"""
bcrypt_util.py
"""

import bcrypt


def encode_password(password: str) -> str:
    """
    加密过程
    :param password: str
    :return: str
    """
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password.encode(), salt)
    return hashed.decode()


def check_password(password: str, hashed_password: str) -> bool:
    """
    校验过程
    :param password: str
    :param hashed_password: str
    :return: bool
    """
    return bcrypt.checkpw(password.encode(), hashed_password.encode())