密码哈希验证


除了单纯将密码md5一下放入数据库,还存在一种相对来说更安全的加密存储方式:随机哈希验证

放两个存储过程,一个是新增用户,一个是验证用户。

新增用户:

DECLARE
salt character(32);
hashValue character(32);
uid bigint;
BEGIN
    IF is_existed_username(_username) IS TRUE THEN
    RETURN -1;
    END IF;
    salt := md5(random()::TEXT);
    hashValue := md5(salt || _password);
    INSERT INTO users(userid,username,password_salt,password_hash,platform) VALUES(DEFAULT,_username,salt,hashValue,_platform) 
    RETURNING userid INTO uid;
    return uid;
END;

验证用户:

DECLARE
uid bigint;
BEGIN
    SELECT userid INTO uid FROM users WHERE username = _username AND password_hash = md5(password_salt||_password);
    IF FOUND THEN
        RETURN uid;
    ELSE
        RETURN 0;
    END IF;
END;

更改密码

最后,如果更改密码,可以用下面这个存储过程:

DECLARE
salt character(32);
hashValue character(32);
uid bigint;
BEGIN
    IF is_existed_userid(_userid) IS FALSE THEN
        RETURN -1;
    END IF;
    salt := md5(random()::TEXT);
    hashValue := md5(salt || _password);
    UPDATE users SET "password_hash"=hashValue,"password_salt"=salt WHERE userid=_userid;
    RETURN _userid;
END;


原文链接:https://blog.yongit.com/note/96792.html