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

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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值