1
zj
2024-07-29 f6f3df18ea57ea4128fcccf3282e1520e867c631
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
package org.example.util;
 
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
/**
 * @program: demo
 * @description:
 * @create: 2024-07-29 11:22
 **/
public class MD5Util {
    // 使用MD5算法对密码进行加密
    public static String encrypt(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            StringBuilder hashText = new StringBuilder(no.toString(16));
            while (hashText.length() < 32) {
                hashText.insert(0, "0");
            }
            return hashText.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
 
    // 校验输入的密码和加密后的密码是否匹配
    public static boolean verify(String inputPassword, String hashedPassword) {
        String hashedInputPassword = encrypt(inputPassword);
        return hashedInputPassword.equals(hashedPassword);
    }
 
    // 示例用法
    public static void main(String[] args) {
        String originalPassword = "myPassword123";
        String hashedPassword = encrypt(originalPassword);
 
        // 模拟校验过程
        String inputPassword = "myPassword123";
        if (verify(inputPassword, hashedPassword)) {
            System.out.println("Password Matched!");
        } else {
            System.out.println("Password Not Matched!");
        }
    }
 
}