一個實現MD5的簡潔的java類 Jagie 原創

來源:互聯網
上載者:User
一個實現MD5的簡潔的java類
Jagie 原創  (參與分:311,專家分:1500)   發表:2003-11-18 下午5:14   更新:2003-11-19 上午8:34   版本:1.0   閱讀:3266
關鍵詞:md5

由於訊息摘要唯一性和無法復原性的特點,所以不失為一種簡單的常用的加密手段,比如你可以用md5來加密你的應用中的使用者口令。

        
         
  1. package test;
  2. import java.security.MessageDigest;
  3. /**
  4.  * <p>Title: </p>
  5.  * <p>Description: </p>
  6.  * <p>Copyright: Copyright (c) 2003</p>
  7.  * <p>Company: </p>
  8.  * @author unascribed
  9.  * @version 1.0
  10.  */
  11. public class StringUtil {
  12.   private final static String[] hexDigits = {
  13.       "0", "1", "2", "3", "4", "5", "6", "7",
  14.       "8", "9", "a", "b", "c", "d", "e", "f"};
  15.   /**
  16.    * 轉換位元組數組為16進位字串
  17.    * @param b 位元組數組
  18.    * @return 16進位字串
  19.    */
  20.   public static String byteArrayToHexString(byte[] b) {
  21.     StringBuffer resultSb = new StringBuffer();
  22.     for (int i = 0; i < b.length; i++) {
  23.       resultSb.append(byteToHexString(b[i]));
  24.     }
  25.     return resultSb.toString();
  26.   }
  27.   private static String byteToHexString(byte b) {
  28.     int n = b;
  29.     if (n < 0)
  30.       n = 256 + n;
  31.     int d1 = n / 16;
  32.     int d2 = n % 16;
  33.     return hexDigits[d1] + hexDigits[d2];
  34.   }
  35.   public static String MD5Encode(String origin) {
  36.     String resultString = null;
  37.     try {
  38.       resultString=new String(origin);
  39.       MessageDigest md = MessageDigest.getInstance("MD5");
  40.       resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
  41.     }
  42.     catch (Exception ex) {
  43.     }
  44.     return resultString;
  45.   }
  46.   public static void main(String[] args){
  47.     System.err.println(MD5Encode("a"));
  48.   }
  49. }

在RFC 1321中,給出了Test suite用來檢驗你的實現是否正確:

MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72
MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0
MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b

參考資料:《java security handbook》 jamie jaworski

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.