zhuguifei
2025-04-28 442928123f63ee497d766f9a7a14f0a6ee067e25
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package org.jeecg.modules.doc.util;
import java.io.File;
 
import java.io.FileInputStream;
 
import java.io.IOException;
 
import java.security.MessageDigest;
 
 
 
public class MD5 {
 
    static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
 
    public static String getMD5(File file) {
 
        FileInputStream fis = null;
 
        try {
 
            MessageDigest md = MessageDigest.getInstance("MD5");
 
            fis = new FileInputStream(file);
 
            byte[] buffer = new byte[4096];
 
            int length = -1;
 
            while ((length = fis.read(buffer)) != -1) {
 
                md.update(buffer, 0, length);
 
            }
 
            byte[] b = md.digest();
 
            return byteToHexString(b);
 
        } catch (Exception e) {
 
            e.printStackTrace();
 
            return null;
 
        } finally {
 
            try {
 
                fis.close();
 
            } catch (IOException e) {
 
                e.printStackTrace();
 
            }
 
        }
 
    }
 
 
    private static String byteToHexString(byte[] tmp) {
 
        String s;
 
        // 用字节表示就是 16 个字节
 
        // 每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符
 
        // 比如一个字节为01011011,用十六进制字符来表示就是“5b”
 
        char str[] = new char[16 * 2];
 
        int k = 0; // 表示转换结果中对应的字符位置
 
        for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节转换成 16 进制字符的转换
 
            byte byte0 = tmp[i]; // 取第 i 个字节
 
            str[k++] = hexdigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移
 
            str[k++] = hexdigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
 
        }
        s = new String(str); // 换后的结果转换为字符串
        return s;
    }
    public static void main(String arg[]) {
        String a = getMD5(new File("d:/a.txt"));
        System.out.println("a.txt的摘要值为:" + a);
 
    }
 
}