1.背景
做文件分片上传时,在合并文件片段时校验文件md5值时和前端不一致
2.源代码
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(new File(file));
int len;
byte[] buf = new byte[8 * 1024 * 1024];
while ((len = fis.read(buf)) != -1) {
md5.update(buf, 0, len);
}
fis.close();
byte[] md5Array = md5.digest();
// 1代表绝对值
BigInteger bigInt = new BigInteger(1, md5Array);
return bigInt.toString(16);
结果:
fileHash是传入的,newFileHash是上面代码计算的,只有31位,原因:转16进制时字节转换成字符串要保证长度是2,所有bigInt直接toString(16)不行
3.解决办法
StringBuilder sb = new StringBuilder();
for (byte b : md5Array) {
int c = b & 0xFF;
if (c < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(c));
}
return sb.toString();
|