Java实现BCrypt加密

描述

BCrypt是比较流行的加密算法,相比MD5。BCrypt还是多对多,在数据库存加密数据方面很实用。Spring Security里面集成了BCrypt的算法,但是普通项目可以用一个第三方开发的工具栏,这里粗略介绍这个工具类。


使用

下载

=>下载该工具类


加密 & 验证

// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());

// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));

// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(password, hashed))
	System.out.println("It matches");
else
	System.out.println("It does not match");

注意:这个算法是多对多的,对于同一个明文,每次生成的密文都不一样(长度都是60 char)
所以必须用它实现的checkpw方法

你可能感兴趣的:(Java,开发)