一個JAVA編寫的MD5加密程序

[code]

package com.myclover.java.test.util;

import java.security.MessageDigest;

/**
*
* 效驗地址:http://www.cmd5.com/
*
*/

public class MD5Password {

private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

// 十六進制下數字到字符的映射數組

/** 把inputString加密 */
public static String createPassword(String inputString) {
return encodeByMD5(inputString);
}

/**
* 驗證輸入的密碼是否正確
*
* @param password
* 真正的密碼(加密後的真密碼) 和 "一個MD5加密類的例子" 有關的 java 編程小帖士:
*
* strong>Locale.Languages.DUTCH
*
* 表示荷蘭語。
*
* 語法
*
* public static final int DUTCH;
*
* @param inputString
* 輸入的字符串
* @return 驗證結果,boolean類型
*/
public static boolean authenticatePassword(String password,
String inputString) {
if (password.equals(encodeByMD5(inputString))) {
return true;
} else {
return false;
}
}

/** 對字符串進行MD5編碼 */
private static String encodeByMD5(String originString) {
if (originString != null) {
try {
// 創建具有指定算法名稱的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字節數組對摘要進行最後更新,然後完成摘要計算
byte[] results = md.digest(originString.getBytes());
// 將得到的字節數組變成字符串返回
String resultString = byteArrayToHexString(results);
return resultString.toUpperCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}

/**
* 輪換字節數組爲十六進制字符串
*
* @param b
* 字節數組
* @return 十六進制字符串
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}

/**
* 將一個字節轉化成十六進制形式的字符串
*/
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}

public static void main(String[] args) {
String password = MD5Password.createPassword("testMD5");
System.out.println("對testMD5用MD5摘要後的字符串:" + password);
System.out.println(password.equalsIgnoreCase("488d3d6f63d713b8525ada7c75d25d7b"));
String inputString = "MD5Test";
System.out.println("MD5Test與密碼匹配?"
+ MD5Password.authenticatePassword(password, inputString));
inputString = "testMD5";
System.out.println("testMD5與密碼匹配?"
+ MD5Password.authenticatePassword(password, inputString));
}

}

[/code]
發佈了35 篇原創文章 · 獲贊 1 · 訪問量 2653
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章