MD5总结
package com.medishare.platform.pharos.client.common; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author jiangyunpeng * */ public class MD5 { private static String[] digits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; //private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; //返回形式为数字跟字符串 private static String byteToArrayString(byte bByte) { int iRet = bByte; if (iRet < 0) { iRet += 256; } int iD1 = iRet / 16; int iD2 = iRet % 16; return digits[iD1] + digits[iD2]; } //转换字节数组为16进制字串 private static String byteToString(byte[] bByte) { StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i < bByte.length; i++) { sBuffer.append(byteToArrayString(bByte[i])); } return sBuffer.toString(); } // private static String byteToString(byte[] bt) { // int l = bt.length; // // char[] out = new char[l << 1]; // // for (int i = 0, j = 0; i < l; i++) { // out[j++] = digits[(0xF0 & bt[i]) >>> 4]; // out[j++] = digits[0x0F & bt[i]]; // } // // return new String(out); // } // public static String getMD5Code(Object obj) { String str = obj.toString(); if (str == null || str.length() == 0) { return "0000000000000000"; } String resultString = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); // md.digest() 该函数返回值为存放哈希值结果的byte数组 byte[] out = md.digest(str.getBytes()); System.out.println(out.length); resultString = byteToString(out); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return resultString.substring(8, 24); } public static void main(String[] args) { for (int i = 0; i < 10; ++i) { String md5 = MD5.getMD5Code(i); System.out.println(md5); } } }
zhu