需求:在查用户表时,不同的用户可能会输入相同的密码,怎么使得存储的时变得不同?
解决:存储用户敏感信息一般会存储加密过的数据,这样可以防止用户的信息泄漏,一般使用的加密方式就是MD5的方式存储,而MD5就是把一个任意长度的字节串变换成一定长的十六进制数字串,固然不同的用户有可能会输入相同的密码,一般用户名都是公开的,假如使用一个用户的密码查库,得到另一个用户的用户名,固然也可以进入到另一个人的账号,所以这样还是有点不安全的,以下介绍最近学到的两种比较安全的加密方式:
方式1:一般在建表时用户名都是唯一的,固然不会重复,那么何不将用户的用户名与密码放在一起MD5结果存储为密码呢(passwd_store = MD5(username+passwd_input)),这样也就不会重复了,而且实现也比较简单。
方式2: PostgreSQL 的 pgcrypto 模块实现
首先需要创建外部模块pgcrypto : create extension pgcrypto ;
使用方式:
insert into crm.test_user(username, password) values ('user', crypt('123456', gen_salt('md5'))); //插入
select * from crm.test_user where username ='user' and password=crypt('123456',password); //查询或验证
相关函数:
crypt(password text, salt text) returns text
Calculates a crypt(3)-style hash of password. When storing a new password, you need to use gen_salt() to generate a new salt value. To check a password, pass the stored hash value as salt, and test whether the result matches the stored value.
crypt() 函数支持的加密算法
gen_salt(type text [, iter_count integer ]) returns text
Generates a new random salt string for use in crypt(). The salt string also tells crypt() which algorithm to use.
The type parameter specifies the hashing algorithm. The accepted types are: des, xdes, md5 and bf.