/**
* 检查输入流的MD5值是否符合.如果MD5为null则直接返回此流.
*
* @param md5
* 验证码
* @param is
* 源输入流
* @return 处理后的输入流,和源输入流可能不为一个对象
*/
private InputStream checkMD5(String md5, InputStream is) {
if (md5 == null) {
return is;
}
// 重写一个流,防止传入的流不能reset
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
int len = -1;
byte[] b = new byte[1024 * 5];
while ((len = is.read(b)) != -1) {
if (md != null) {
md.update(b, 0, len);
}
baos.write(b, 0, len);
}
if (!md5.equalsIgnoreCase(digestMD5(md.digest()))) {
if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(
getUiManager().getRootPanel(),
"数据校验发现和传入值不匹配,系统将无法解析该文件,是否重新读取文件?")) {
actionPerformed(null);
} else {
return null;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(baos.toByteArray());
}
/**
* 由128位的字节结果转换成32位字符串
*
* @param digest
* MD5 的计算结果是一个 128位的长整数,
* @return
*/
private String digestMD5(byte digest[]) {
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
// 用字节表示就是 16 个字节
char[] result = new char[16 * 2]; // 每个字节用 16
// 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int j = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5
// 的每一个字节
// 转换成 16 进制字符的转换
byte b = digest[i]; // 取第 i 个字节
result[j++] = hexDigits[b >>> 4 & 0xf];
// 取字节中高4位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
result[j++] = hexDigits[b & 0xf];
// 取字节中低 4位的数字转换
}
return new String(result);
}
自用的MD5计算工具
最新推荐文章于 2024-04-11 09:30:46 发布