package com.nationalelectirc.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class MD5Util { private static String kk = "greenh5"; public static String encrypt(String data) throws NoSuchAlgorithmException { MessageDigest md = messagedigest; byte[] array = md.digest((data + kk).getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } /** * 签名加密 * @param map * @return */ public static String MD5(Map map) { //参数按键名升序排序 List list = new ArrayList(); Iterator iter = map.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); list.add(entry.getKey()); } Collections.sort(list); //拼接参数 StringBuilder param=new StringBuilder(); for (int i=0;i 0) { messagedigest.update(buffer, 0, numRead); } } catch (Exception e) { }finally { if (fis != null) { fis.close(); } } return bufferToHex(messagedigest.digest()); } /** * JDK1.4中不支持以MappedByteBuffer类型为参数update方法,并且网上有讨论要慎用MappedByteBuffer, * 原因是当使用 FileChannel.map 方法时,MappedByteBuffer 已经在系统内占用了一个句柄, 而使用 * FileChannel.close 方法是无法释放这个句柄的,且FileChannel有没有提供类似 unmap 的方法, * 因此会出现无法删除文件的情况。 * * 不推荐使用 * * @param file * @return * @throws IOException */ public static String getFileMD5String_old(File file) throws IOException { FileInputStream in = null; FileChannel ch = null; try { in = new FileInputStream(file); ch = in.getChannel(); MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); messagedigest.update(byteBuffer); } catch (Exception e) { //日志 }finally { if (in != null) { in.close(); } if (ch != null) { ch.close(); } } return bufferToHex(messagedigest.digest()); } public static String getMD5String(byte[] bytes) { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); } private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同 char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换 stringbuffer.append(c0); stringbuffer.append(c1); } }