1. 程式人生 > >Md5Utils工具類

Md5Utils工具類

package main.com.qianfeng.utils;

import java.security.NoSuchAlgorithmException;

public  class  Md5Utils {

   public static String getMD5(byte[] source) {
      String s = null;
      char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };// 用來將位元組轉換成16進製表示的字元
      try {
         java.security.MessageDigest md = java.security.MessageDigest
               .getInstance("MD5");
         md.update(source);
         byte tmp[] = md.digest();// MD5 的計算結果是一個 128 位的長整數,
         // 用位元組表示就是 16 個位元組
         char str[] = new char[16 * 2];// 每個位元組用 16 進製表示的話,使用兩個字元, 所以表示成 16
         // 進位制需要 32 個字元
         int k = 0;// 表示轉換結果中對應的字元位置
         for (int i = 0; i < 16; i++) {// 從第一個位元組開始,對 MD5 的每一個位元組// 轉換成 16
            // 進位制字元的轉換
            byte byte0 = tmp[i];// 取第 i 個位元組
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取位元組中高 4 位的數字轉換,// >>>
            // 為邏輯右移,將符號位一起右移
            str[k++] = hexDigits[byte0 & 0xf];// 取位元組中低 4 位的數字轉換

         }
         s = new String(str);// 換後的結果轉換為字串

      } catch (NoSuchAlgorithmException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return s;
   }

   public static void main(String[] args){

      String test=Md5Utils.getMD5("test".getBytes());
      System.out.println(test);

   }
}