Python3 的 password_hash() 实现以及兼容

yufei       4 年 前       861

最近一些数据需要 PHP 和 Python3 兼容,主要是登录密码方面,要兼容 PHP 的 password_hash()password_verify() 函数。

Python3 中我们要使用到 bcrypt,你可以使用下面的命令安装

pip install bcrypt

范例源码如下

import datetime
import sys

import bcrypt

user_id = '123456'
created_at = datetime.datetime.now().strftime("%Y%m%d")
secret  = 'secret{user_id}{created_at}'.format(user_id=user_id,created_at=created_at)
hashed  = bcrypt.hashpw(secret.encode('utf-8'),bcrypt.gensalt())


print('明文',secret)
print('密文',hashed.decode('utf-8'))

# 检查是否匹配
if bcrypt.hashpw(secret.encode('utf-8'),hashed):
    print('一模一样')
else:
    print('您输入的密码错误')


print("兼容PHP的玩法")
hashed  = bcrypt.hashpw(secret.encode('utf-8'),bcrypt.gensalt(10))

print('明文',secret)
print('密文',hashed.decode('utf-8').replace('$2b$','$2y$'))

PHP 中使用 password_verify() 检查如下

<?php 

echo password_verify('secret12345620200404', '$2y$10$yxcLgWh5X1eDWKCWI0Ly9.KxiNppmBXma23/eOd9zJWHavzZz2y7G') ? 'true':'false';
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.