1
zj
2025-08-19 12c5babf57f42b134f199b82a0033eb9bbfa2b2b
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.ruoyi.web.controller.api.util;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
 
public class MD5Util {
 
    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
 
    /**
     * 计算字符串MD5
     */
    public static String md5(String input) {
        if (input == null) return null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(digest);
        } catch (Exception e) {
            throw new RuntimeException("MD5计算失败", e);
        }
    }
 
    /**
     * 计算文件MD5
     */
    public static String md5(File file) {
        if (file == null || !file.exists()) return null;
 
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            return bytesToHex(md.digest());
        } catch (Exception e) {
            throw new RuntimeException("文件MD5计算失败", e);
        }
    }
 
    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        if (bytes == null) return null;
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            sb.append(HEX_CHARS[(b >> 4) & 0x0F]);
            sb.append(HEX_CHARS[b & 0x0F]);
        }
        return sb.toString();
    }
 
    /**
     * 验证MD5
     */
    public static boolean verify(String input, String md5) {
        return md5(input).equalsIgnoreCase(md5);
    }
 
    public static boolean verify(File file, String md5) {
        return md5(file).equalsIgnoreCase(md5);
    }
}