Skip to content

Instantly share code, notes, and snippets.

@borgle
Created August 28, 2015 09:13
Show Gist options
  • Save borgle/872ad348769e714b12dd to your computer and use it in GitHub Desktop.
Save borgle/872ad348769e714b12dd to your computer and use it in GitHub Desktop.
获取文件或者某个字符串的MD5 hash值
package com.gkeeps.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
static MessageDigest MD5 = null;
static {
try {
MD5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ne) {
ne.printStackTrace();
}
}
/**
* 对一个文件获取md5值
*
* @return md5串
*/
public static String getMD5(File file) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
return new String(encodeHex(MD5.digest(), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 求一个字符串的md5值
*
* @param srcString
* 字符串
* @return md5 value
*/
public static String getMD5(String srcString) {
return encodeHexString(MD5.digest(srcString.getBytes(Charset.forName("utf-8"))));
}
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F' };
private static String encodeHexString(final byte[] data) {
return new String(encodeHex(data, true));
}
private static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
private static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
public static void main(String[] args) {
java.util.Date d = new java.util.Date();
long t1 = d.getTime();
String md5 = getMD5(
new File("F:\\Downloads\\xxxxx_x86_and_x64_dvd.iso")); //1.7G
d = new java.util.Date();
long t2 = d.getTime();
System.out.println(String.format("times: %s ms, md5 = %s", t2 - t1, md5));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment