目录
简介
bcrypt是一个跨平台的文件加密工具,它使用了由 OpenBSD 项目开发的 Blowfish 对称密钥块密码的变种来加密数据。然而,在编程和加密库的上下文中,当我们提到 bcrypt
时,我们通常是指一个特定于密码哈希的库,它使用了一种基于 Blowfish 密码的适应性哈希算法。
引入依赖
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
加密案例
import org.mindrot.jbcrypt.BCrypt;
public class PasswordEncryption {
public static void main(String[] args) {
// 原始密码
String password = "myPassword123";
// 使用BCrypt哈希密码
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
// 打印哈希后的密码
System.out.println(hashedPassword);
}
}
BCrypt.gensalt()
方法生成一个随机的盐值,而BCrypt.hashpw(password, salt)
方法则使用这个盐值和原始密码来生成哈希。
解密案例
import org.mindrot.jbcrypt.BCrypt;
public class PasswordVerification {
public static void main(String[] args) {
// 假设这是从数据库存储的哈希值
String databasePassword = "$2y$10$N9qo8uLOickgx2ZMRZoMpeOHCNfhFu84OupV5i5ru2HPWnSjN.WaG";
// 用户输入的密码
String password = "myPassword123";
// 对比
boolean result = BCrypt.checkpw(password, databasePassword);
// 判断是否正确
if(result){
System.out.println("正确");
}else{
System.out.println("错误");
}
}
}
MD5加密
/**
* 进行md5加密
* @param password
* @return
*/
public static String getMD5Hash(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// 加密方式1
String s = DigestUtils.md5DigestAsHex(password.getBytes());
// 加密方式2
byte[] mdpassword = md.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : mdpassword) {
sb.append(String.format("%02x",b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}