PostgreSQL的MD5加密不重复的方法

本文探讨了在用户表中存储密码时如何确保安全性,介绍了两种加密方式:一种是将用户名与密码一起进行MD5加密,以避免密码重复;另一种是使用PostgreSQL的pgcrypto模块实现更安全的加密方式,通过`crypt()`函数与`gen_salt()`函数来生成盐值,增强密码保护。

需求:在查用户表时,不同的用户可能会输入相同的密码,怎么使得存储的时变得不同?


解决:存储用户敏感信息一般会存储加密过的数据,这样可以防止用户的信息泄漏,一般使用的加密方式就是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.



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值