View Javadoc
1   package gboat2.attachment.util;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.security.MessageDigest;
8   import java.security.NoSuchAlgorithmException;
9   
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  public final class MD5Util {
14  	/**
15  	 * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
16  	 */
17  	private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6',
18  			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
19  	private static MessageDigest messagedigest = null;
20  	
21  	private static Logger logger = LoggerFactory.getLogger(MD5Util.class);
22  	static {
23  		try {
24  			messagedigest = MessageDigest.getInstance("MD5");
25  		} catch (NoSuchAlgorithmException e) {
26  			logger.error("初始化MD5失败", e);
27  		}
28  	}
29  
30  	public static void main(String[] args) throws IOException {
31  		File file = new File("velocity.log");
32  		String md5 = getFileMD5String(file);
33  		System.out.println("md5:" + md5);
34  		File file2 = new File("velocity2.log");
35  		String md52 = getFileMD5String(file2);
36  		System.out.println("md5:" + md52);
37  	}
38  
39  	public static String getFileMD5String(File file) throws IOException {
40  		InputStream fis;
41  		fis = new FileInputStream(file);
42  		byte[] buffer = new byte[1024];
43  		int numRead = 0;
44  		while ((numRead = fis.read(buffer)) > 0) {
45  			messagedigest.update(buffer, 0, numRead);
46  		}
47  		fis.close();
48  		return bufferToHex(messagedigest.digest());
49  	}
50  
51  	private static String bufferToHex(byte[] bytes) {
52  		return bufferToHex(bytes, 0, bytes.length);
53  	}
54  
55  	private static String bufferToHex(byte[] bytes, int m, int n) {
56  		StringBuffer stringbuffer = new StringBuffer(2 * n);
57  		int k = m + n;
58  		for (int l = m; l < k; l++) {
59  			appendHexPair(bytes[l], stringbuffer);
60  		}
61  		return stringbuffer.toString();
62  	}
63  
64  	private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
65  		char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换
66  		// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
67  		char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
68  		stringbuffer.append(c0);
69  		stringbuffer.append(c1);
70  	}
71  }