MD5加密替代方案

本文最后更新于:2025年2月18日 下午

由于MD5加密存在撞库的漏洞(尽管那概率很小),所以现在并不适合用来加密用户的密码。

目前的用处一般在文件完整性检查数据去重上。

替代方案

Bcrypt加密,这也是一种单向加密算法。也是SpringSecurity中的加密算法之一。

使用方法

依赖

1
2
3
4
5
6
<!--  用于密码加密  -->
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import org.mindrot.jbcrypt.BCrypt;

/**
* BCrypt密码加密工具
* @author peter
* @date 2024/10/16
* @className PasswordUtil
* @description 这是替代MD5加密的完美选择
*/
public class PasswordUtil {

/**
* 密码加密
* @author peter
* @date 2024/10/16
* @className PasswordUtil
* @param password 密码
* @return 返回被BCrypt加密后的密码
*/
public static String hashPassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}

/**
* 密码校验
* @author peter
* @date 2024/10/16
* @className PasswordUtil
* @param password 待校验的密码
* @param hashed 数据库中存储的密文
* @return 返回校验结果,成功为true,否则为false
*/
public static boolean checkPassword(String password, String hashed) {
return BCrypt.checkpw(password, hashed);
}

// 示例用法
public static void main(String[] args) {
String password = "mySecretPassword";

// 哈希密码
String hashedPassword = hashPassword(password);
System.out.println("Hashed Password: " + hashedPassword);

// 验证密码
boolean isMatch = checkPassword(password, hashedPassword);
System.out.println("Password matches: " + isMatch);
}
}


MD5加密替代方案
https://superlovelace.top/2024/10/16/MD5加密替代方案/
作者
棱境
发布于
2024年10月16日
更新于
2025年2月18日
许可协议