32位:
private static String md5HashCode(String filePath) {
try {
InputStream fis = new FileInputStream(filePath);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
fis.close();
byte[] md5Bytes = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < md5Bytes.length; offset++) {
i = md5Bytes[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
//32位加密
return buf.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
16位:
private String md5HashCode(String filePath) {
try {
InputStream fis = new FileInputStream(filePath);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
fis.close();
//转换并返回包含16个元素字节数组,返回数值范围为-128到127
byte[] md5Bytes = md.digest();
BigInteger bigInt = new BigInteger(1, md5Bytes);
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}