目录
什么是文件的MD5?
java代码获得MD5的几种方式
方法一:
方法二:
方法三:
方法四:
方法五:
总结
JAVA中获取文件MD5值的四种方法其实都很类似,因为核心都是通过JAVA自带的MessageDigest类来实现。获取文件MD5值主要分为三个步骤,第一步获取文件的byte信息,第二步通过MessageDigest类进行MD5加密,第三步转换成16进制的MD5码值.
比较原始的一种实现方法,首先将文件一次性读入内存,然后通过MessageDigest进行MD5加密,最后再手动将其转换为16进制的MD5值。
private final static String[] strHex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static String getMD5One(String path) { StringBuffer sb = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] b = md.digest(FileUtils.readFileToByteArray(new File(path))); for (int i = 0; i < b.length; i++) { int d = b[i]; if (d < 0) { d += 256; } int d1 = d / 16; int d2 = d % 16; sb.append(strHex[d1] + strHex[d2]); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }方法二与方法一不同的地方主要是在步骤三,这里借助了Integer类的方法实现16进制的转换,比方法一更简洁一些
public static String getMD5Two(String path) { StringBuffer sb = new StringBuffer(""); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(FileUtils.readFileToByteArray(new File(path))); byte b[] = md.digest(); int d; for (int i = 0; i < b.length; i++) { d = b[i]; if (d < 0) { d = b[i] & 0xff; // 与上一行效果等同 // i += 256; } if (d < 16) sb.append("0"); sb.append(Integer.toHexString(d)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }方法三与前面两个方法相比,在读入文件信息上有点不同。这里是分多次将一个文件读入,对于大型文件而言,比较推荐这种方式,占用内存比较少。步骤三则是通过BigInteger类提供的方法进行16进制的转换,与方法二类似
public static String getMD5Three(String path) { BigInteger bi = null; try { byte[] buffer = new byte[8192]; int len = 0; MessageDigest md = MessageDigest.getInstance("MD5"); File f = new File(path); FileInputStream fis = new FileInputStream(f); while ((len = fis.read(buffer)) != -1) { md.update(buffer, 0, len); } fis.close(); byte[] b = md.digest(); bi = new BigInteger(1, b); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bi.toString(16); }
如果你只需要使用标准的MD5,其实一行代码就够了,JAVA自带的commons-codec包就提供了获取16进制MD5值的方法。其底层实现上,也是分多次将一个文件读入,类似方法三。所以性能上也不错
DigestUtils.md5Hex(new FileInputStream(path));
方法五接收的参数直接采用了MultipartFile 形式,在一些上传文件的过程中,可以直接实用,省的在对文件流进行操作。
/** * 获取上传文件的md5 * * @param file 上传文件MD5 * @return */ public static String getFileMd5(MultipartFile file) { try { byte[] uploadBytes = file.getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(uploadBytes); String hashString = new BigInteger(1, digest).toString(16); return hashString; } catch (Exception e) { e.printStackTrace(); return null; } }每种方法都可以,根据实际需求。
