关于在数据库中存储用户密码和验证
数据库中加密存储密码和验证密码的步骤
以下内容来自ChatGLM
存储密码
- 生成盐(Salt):
- 为每个用户生成一个随机盐。
- 密码与盐结合:
- 将用户密码与盐值结合。
- 加密:
- 使用上述算法对结合后的密码进行加密。
- 存储:
- 将加密后的密码(哈希值)和盐存储在数据库中。
验证密码
从数据库中取出盐和哈希值:
- 在用户尝试登录时,系统需要从数据库中检索与该用户账户关联的盐值和之前存储的哈希密码。
使用相同的算法和盐对用户输入的密码进行加密:
- 将用户输入的密码与从数据库中取出的盐值结合,然后使用相同的加密算法对结合后的密码进行加密。
比较加密后的值与数据库中的哈希值是否相同:
- 将新计算出的哈希值与数据库中存储的哈希值进行比较。如果两者匹配,说明用户输入的密码正确;如果不匹配,说明密码错误。
关于盐:
内容来自 https://www.cnblogs.com/xjnotxj/p/12716981.html
- 盐不能太短
- 盐不能重复使用(否则一破解,所有的都遭殃)
- 盐随机变化(例如,虽用户名不重复,但用户名不能拿来当盐)
TypeScript 代码实现
生成加密后的哈希密码
import crypto from 'crypto';
// 生成盐值(生成随机字符串转换16进制并截取指定长度)
function generateSalt(length: number = 16): string {
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
}
// 哈希密码
function hashPassword(password: string, salt: string): string {
const hash = crypto.createHash('sha256');
hash.update(password + salt);
return hash.digest('hex');
}
// 示例用法
const username = '张三';
const password = 'myPassword123';
const salt = generateSalt();
const hashedPassword = hashPassword(password, salt);
const userInfo = {
username: username,
hashedPassword: hashedPassword,
salt: salt,
}
console.log(userInfo)
// {
// username: '张三',
// hashedPassword: 'd199f982ad02822110e05685241cb134b965e1d767dcad581d0d2be99f72d585',
// salt: 'be90365eb56291d2'
// }
使用保存的哈希密码和盐值对用户输入的密码进行验证
import crypto from 'crypto';
const userInfo = {
username: '张三',
hashedPassword: 'd199f982ad02822110e05685241cb134b965e1d767dcad581d0d2be99f72d585',
salt: 'be90365eb56291d2'
}
// 哈希密码
function hashPassword(password: string, salt: string): string {
const hash = crypto.createHash('sha256');
hash.update(password + salt);
return hash.digest('hex');
}
const inputPassword1 = 'myPassword123';
const inputPassword2 = 'myPassword321';
const hashedInputPassword1 = hashPassword(inputPassword1, userInfo.salt);
const hashedInputPassword2 = hashPassword(inputPassword2, userInfo.salt);
if (hashedInputPassword1 == userInfo.hashedPassword) {
console.log('密码正确');
}else{
console.log('密码错误');
}
if (hashedInputPassword2 == userInfo.hashedPassword) {
console.log('密码正确');
}else{
console.log('密码错误');
}
//结果可知 inputpassword1验证正确 inputpassword2验证错误