Java计算字符串和文件的MD5与SHA1

package net.hkh.util; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Utils { @SuppressWarnings("unused") private static final String md5 = "MD5"; @SuppressWarnings("unused") private static final String sha1 = "SHA-1"; /** * @desc 计算字符串的md5 or sha1 * @param str * @param lx,md5 *or sha1 * @return * @throws UnsupportedEncodingException * */ public static String md5OrSha1OfString(String str, String lx) throws UnsupportedEncodingException { try { MessageDigest md = MessageDigest.getInstance(lx); byte[] inputByteArr = str.getBytes("UTF-8"); md.update(inputByteArr); byte[] rsByteArr = md.digest(); return byteArrayToHex(rsByteArr); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * @desc 计算文件的md5 or sha1 * @param inputFile * @param lx,md5 *or sha1 * @return * @throws IOException * */ @SuppressWarnings("finally") public static String md5OrSha1OfFile(String inputFile, String lx) throws IOException { int bufferSize = 256 * 1024; FileInputStream fis = null; DigestInputStream dis = null; String rslt = null; try { MessageDigest md = MessageDigest.getInstance(lx); fis = new FileInputStream(inputFile); dis = new DigestInputStream(fis, md); byte[] buffer = new byte[bufferSize]; while (dis.read(buffer) > 0) { md = dis.getMessageDigest(); byte[] arr = md.digest(); rslt = byteArrayToHex(arr); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); rslt = null; } finally { try { dis.close(); } catch (Exception e) { e.printStackTrace(); } dis = null; try { fis.close(); } catch (Exception e) { e.printStackTrace(); } fis = null; return rslt; } } /** * @desc 将生成的字节数组转化为十六进制字符串 * @param arr * @return * */ public static String byteArrayToHex(byte[] arr) { String hexStr = "0123456789ABCDEF"; StringBuilder rslt = new StringBuilder(); for (int i = 0; i < arr.length; i++) { rslt.append(String.valueOf(hexStr.charAt((arr[i] & 0xf0) >> 4))); rslt.append(String.valueOf(hexStr.charAt(arr[i] & 0x0f))); } return rslt.toString(); } }


    推荐阅读