java 密碼MD5加密
java加密bytestring算法null
package com.sunnylocus.util;
import java.security.MessageDigest;
/**
* 對密碼進行加密和驗證的類
*/
public class CipherUtil{
//十六進制下數字到字符的映射數組
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 generatePassword(String inputString){
return encodeByMD5(inputString);
}
/**
* 驗證輸入的密碼是否正確
* @param password 加密後的密碼
* @param inputString 輸入的字符串
* @return 驗證結果,TRUE:正確 FALSE:錯誤
*/
public static boolean validatePassword(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 字節數組
* @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];
}
}
package com.sunnylocus.util;
public class Main {
public static void main(String[] args) {
String pwd1="123";
String pwd2="";
CipherUtil cipher = new CipherUtil();
System.out.println("未加密的密碼:"+pwd1);
//將123加密
pwd2 = cipher.generatePassword(pwd1);
System.out.println("加密後的密碼:"+pwd2);
System.out.print("驗證密碼是否下確:");
if(cipher.validatePassword(pwd2, pwd1)) {
System.out.println("正確");
}
else {
System.out.println("錯誤");
}
}
}
結果輸出:
Java代碼 收藏代碼
未加密的密碼:123
加密後的密碼:202CB962AC59075B964B07152D234B70
驗證密碼是否下確:正確