package com.aug3.sys.util; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.DigestInputStream; import java.security.MessageDigest; import org.apache.commons.lang.StringUtils; /** * * @author * */ public class MD5 { public static final int BUFFER_SIZE = 1024 * 200; //create md5 string according to first 200k data /** * 根据文件的前200k数据生成MD5字符串 * @param is * @return */ public static String getMD5Str(InputStream is) { DigestInputStream dis = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); dis = new DigestInputStream(is, messageDigest); dis.read(new byte[BUFFER_SIZE]); return new BigInteger(1, messageDigest.digest()).toString(16); } catch (Exception e) { return ""; } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { } } } } /** * 根据文件的全部数据生成MD5字符串 * @param is * @return */ public static String getMD5Str(InputStream is, byte[] bytes) { DigestInputStream dis = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); dis = new DigestInputStream(is, messageDigest); dis.read(bytes); return new BigInteger(1, messageDigest.digest()).toString(16); } catch (Exception e) { return ""; } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { } } } } public static String md5(String str) { String result = null; if (!StringUtils.isBlank(str)) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes(), 0, str.length()); result = String .format("%032X", new BigInteger(1, md5.digest())); } catch (Exception e) { } } return result; } }