Java完成MD5加密及解密的代碼實例分享。本站提示廣大學習愛好者:(Java完成MD5加密及解密的代碼實例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成MD5加密及解密的代碼實例分享正文
根底:MessageDigest類的運用
其實要在Java中完成MD5加密,MessageDigest類大局部都幫你完成好了,幾行代碼足矣:
/**
* 對字符串md5加密
*
* @param str
* @return
*/
import java.security.MessageDigest;
public static String getMD5(String str) {
try {
// 生成一個MD5加密計算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 計算md5函數
md.update(str.getBytes());
// digest()最後確定前往md5 hash值,前往值為8為字符串。由於md5 hash值是16位的hex值,實踐上就是8位的字符
// BigInteger函數則將8位的字符串轉換成16位hex值,用字符串來表示;失掉字符串方式的hash值
return new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
throw new SpeedException("MD5加密呈現錯誤");
}
}
進階:加密及解密類
Java完成MD5加密以及解密類,附帶測試類,詳細見代碼。
MD5加密解密類——MyMD5Util,代碼如下
package com.zyg.security.md5;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
public class MyMD5Util {
private static final String HEX_NUMS_STR="0123456789ABCDEF";
private static final Integer SALT_LENGTH = 12;
/**
* 將16進制字符串轉換成字節數組
* @param hex
* @return
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] hexChars = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4
| HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
}
return result;
}
/**
* 將指定byte數組轉換成16進制字符串
* @param b
* @return
*/
public static String byteToHexString(byte[] b) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hexString.append(hex.toUpperCase());
}
return hexString.toString();
}
/**
* 驗證口令能否合法
* @param password
* @param passwordInDb
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static boolean validPassword(String password, String passwordInDb)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
//將16進制字符串格式口令轉換成字節數組
byte[] pwdInDb = hexStringToByte(passwordInDb);
//聲明鹽變量
byte[] salt = new byte[SALT_LENGTH];
//將鹽從數據庫中保管的口令字節數組中提取出來
System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);
//創立音訊摘要對象
MessageDigest md = MessageDigest.getInstance("MD5");
//將鹽數據傳入音訊摘要對象
md.update(salt);
//將口令的數據傳給音訊摘要對象
md.update(password.getBytes("UTF-8"));
//生成輸出口令的音訊摘要
byte[] digest = md.digest();
//聲明一個保管數據庫中口令音訊摘要的變量
byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];
//獲得數據庫中口令的音訊摘要
System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length);
//比擬依據輸出口令生成的音訊摘要和數據庫中音訊摘要能否相反
if (Arrays.equals(digest, digestInDb)) {
//口令正確前往口令婚配音訊
return true;
} else {
//口令不正確前往口令不婚配音訊
return false;
}
}
/**
* 取得加密後的16進制方式口令
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static String getEncryptedPwd(String password)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
//聲明加密後的口令數組變量
byte[] pwd = null;
//隨機數生成器
SecureRandom random = new SecureRandom();
//聲明鹽數組變量
byte[] salt = new byte[SALT_LENGTH];
//將隨機數放入鹽變量中
random.nextBytes(salt);
//聲明音訊摘要對象
MessageDigest md = null;
//創立音訊摘要
md = MessageDigest.getInstance("MD5");
//將鹽數據傳入音訊摘要對象
md.update(salt);
//將口令的數據傳給音訊摘要對象
md.update(password.getBytes("UTF-8"));
//取得音訊摘要的字節數組
byte[] digest = md.digest();
//由於要在口令的字節數組中寄存鹽,所以加上鹽的字節長度
pwd = new byte[digest.length + SALT_LENGTH];
//將鹽的字節拷貝到生成的加密口令字節數組的前12個字節,以便在驗證口令時取出鹽
System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);
//將音訊摘要拷貝到加密口令字節數組從第13個字節開端的字節
System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);
//將字節數組格式加密後的口令轉化為16進制字符串格式的口令
return byteToHexString(pwd);
}
}
測試類——Client,代碼如下:
package com.zyg.security.md5;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class Client {
private static Map users = new HashMap();
public static void main(String[] args){
String userName = "zyg";
String password = "123";
registerUser(userName,password);
userName = "changong";
password = "456";
registerUser(userName,password);
String loginUserId = "zyg";
String pwd = "1232";
try {
if(loginValid(loginUserId,pwd)){
System.out.println("歡送登陸!!!");
}else{
System.out.println("口令錯誤,請重新輸出!!!");
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 注冊用戶
*
* @param userName
* @param password
*/
public static void registerUser(String userName,String password){
String encryptedPwd = null;
try {
encryptedPwd = MyMD5Util.getEncryptedPwd(password);
users.put(userName, encryptedPwd);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 驗證登陸
*
* @param userName
* @param password
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static boolean loginValid(String userName,String password)
throws NoSuchAlgorithmException, UnsupportedEncodingException{
String pwdInDb = (String)users.get(userName);
if(null!=pwdInDb){ // 該用戶存在
return MyMD5Util.validPassword(password, pwdInDb);
}else{
System.out.println("不存在該用戶!!!");
return false;
}
}
}