xuhy
昨天 69a0e318bb6ce1efec4d67d8751b7574b37ba49e
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
package com.ruoyi.system.utils.util;
 
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class MD5Util {
 
    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
 
    // 计算字符串的MD5值,返回十六进制字符串
    public static String md5Hex(String message) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(message.getBytes());
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e); // 不应该发生,因为"MD5"是一个标准的算法名称
        }
    }
 
    public static void main(String[] args) {
        String originalString = "Hello, World!";
        String md5Result = md5Hex(originalString);
        System.out.println("Original: " + originalString);
        System.out.println("MD5: " + md5Result);
    }
}