/** * Copyright © 2012-2014 JeeSite All rights reserved. */ package com.nis.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.digest.DigestUtils; /** * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 * @author ThinkGem * @version 2013-05-22 */ public class MD5Utils { /** * 字符串转为MD532位小写 * @param plain * @return */ public static String md5LowerCase(String plain) throws Exception { String re_md5 = new String(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plain.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } re_md5 = buf.toString(); return re_md5; } public static byte[] createChecksum(String filename) throws IOException, NoSuchAlgorithmException { InputStream fis = new FileInputStream(filename); byte[] buffer = new byte[1024]; MessageDigest complete = MessageDigest.getInstance("MD5"); int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); return complete.digest(); } public static String getMD5Checksum(String filename) throws NoSuchAlgorithmException, IOException { byte[] b = createChecksum(filename); StringBuffer result = new StringBuffer(); for (int i = 0; i < b.length; i++) { result.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)); } return result.toString(); } public static void main(String[] args) throws NoSuchAlgorithmException, IOException { long start1 = System.currentTimeMillis(); String md5Checksum = getMd5ByIS(new FileInputStream("f:\\1.iso")); System.out.println(md5Checksum); long start2 = System.currentTimeMillis(); System.out.println("第一次用时" + (start2 - start1)); String md5Checksum1 = getMD5Checksum("f:\\1.iso"); long start3 = System.currentTimeMillis(); System.out.println(md5Checksum1); System.out.println("第二次用时" + (start3 - start2)); } /** * 这种方式计算大文件时更快一些 * @param fis * @return * @throws IOException * @throws NoSuchAlgorithmException */ public static String getMd5ByIS(InputStream is) throws IOException, NoSuchAlgorithmException { return DigestUtils.md5Hex(is); } }