Python3 web开发中几种密码加密方式
直接上代码:
import time
import bcrypt
from passlib.apps import custom_app_context as pwd_context
from werkzeug.security import generate_password_hash, check_password_hash
from flask_bcrypt import Bcrypt
# ---------------------加密密码与验证——方式一
def generate_password(password):
password_hash = pwd_context.encrypt(password)
return password_hash
def verify_password(password, password_hash):
return pwd_context.verify(password, password_hash)
# ---------------------加密密码与验证——方式二
def encry_pwd(passwd):
salt = bcrypt.gensalt(rounds=12) #
# print('salt:', salt)
# salt = b'$2b$10$bfjZmqtf2WIu2Lv3JdP4V.'
# print(salt)
hashed = bcrypt.hashpw(passwd.encode(), salt)
return hashed
def check_pwd(passwd, hashed):
# 校验过程
ret = bcrypt.checkpw(passwd.encode(), hashed)
return ret
# ---------------------加密密码与验证——方式三
def get_password(pwd):
password = generate_password_hash(pwd)
# print(password)
return password
def check_password(hash_pwd, pwd):
return check_password_hash(hash_pwd, pwd)
# ---------------------加密密码与验证——方式四
def bcrypt_gene_pwd(pwd):
bcrypt = Bcrypt()
pw_hash = bcrypt.generate_password_hash(pwd).decode('utf-8')
return pw_hash
def bcrypt_check_pwd(pw_hash, pwd):
bcrypt = Bcrypt()
ret = bcrypt.check_password_hash(pw_hash, pwd)
return ret
if __name__ == '__main__':
# 测试————方式一
res = generate_password('123456')
print(res) # $6$rounds=656000$1ztut7P6gZtP9Bwq$C5vTNQ.pFuRnHohQXfKe/K1VXL1rByS.4C0ZMVA6qC8/6ribEc.4fMuAFUeO.mvxHMWAgQ445NJtd0JTvkks2/
start = time.time()
print(verify_password('123456', res)) # True
end = time.time()
print(int(round((end - start) * 1000))) # 679
# 测试————方式二
pwd = '123456'
encryed_pwd = encry_pwd(pwd)
print(encryed_pwd) # b'$2b$12$.9M7dawGBjmNSoZZPc29Je3BTwGtNrBD18ppY115mKVqaMnrYNSp6'
start = time.time()
flag = check_pwd(pwd, encryed_pwd)
end = time.time()
print(int(round((end - start) * 1000))) # 207
print(flag) # True
# 测试————方式三
pwd = '123456'
hash_pwd = get_password(pwd)
print(hash_pwd) # pbkdf2:sha256:50000$ZiYb26XV$fc551fc9b4221e36fa9e4711079e098f3f5406890cc03b462485e9a18b9051b8
start = time.time()
flag = check_password(hash_pwd, pwd)
end = time.time()
print(int(round((end - start) * 1000))) # 54
# print(time.time() - start)
print(flag) # True
# 测试————方式四
pw_hash = bcrypt_gene_pwd('123456')
print(pw_hash) # $2b$12$e2cI1lhEAHlyjB6ozHpGb.9cUmL5PptcQwUKVjL5tSkHGfScWcURe
start = time.time()
ret = bcrypt_check_pwd(pw_hash, '123456')
end = time.time()
print(int(round((end - start) * 1000))) # 202
print(ret) # True
从上述测试结果中,可以看出,加密与解密都可以。
一个明显的区别就是,加密或解密的速度存在不一致。
解密速度最快的是方式三,最慢的是方式一。
以上。