MD5 算法總結

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

發佈了1165 篇原創文章 · 獲贊 19 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章