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];
}
java代碼

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("錯誤");
結果輸出:

未加密的密碼:123
加密後的密碼:202cb962ac59075b964b07152d234b70
驗證密碼是否下确:正确