import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Scanner;
public class MD5{
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++) {
//0XFF表示十進制的255,其中0X是java中用來申明16進制字符使用的,此時表示取當前字節的反碼
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hexString.append(hex.toUpperCase());
}
return hexString.toString();
}
/**
* 得到加密後的16進制形式字符串
* @param password
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static String getEncryptedPwd(String sourceString)
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(sourceString.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);
}
/**
* 驗證口令是否合法
* @param password
* @param passwordInDb
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static boolean validPassword(String sourceString, String md5String)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
//將16進制字符串格式口令轉換成字節數組
byte[] pwdInDb = hexStringToByte(md5String);
//聲明鹽變量
byte[] salt = new byte[SALT_LENGTH];
//將鹽從數據庫中保存的口令字節數組中提取出來
System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);
//建立消息摘要對象
MessageDigest md = MessageDigest.getInstance("MD5");
//將鹽數據傳入消息摘要對象
md.update(salt);
//將口令的數據傳給消息摘要對象
md.update(sourceString.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;
}
}
public static void main(String[] args){
System.out.println("-----------------MD5加密 start--------------------");
try {
System.out.print("-----------------請輸入您要加密的內容按enter鍵後執行:");
Scanner scanner = new Scanner(System.in);
String sourceString = scanner.nextLine();
String md5String = getEncryptedPwd(sourceString);
System.out.println("----------加密前:"+sourceString);
System.out.println("----------加密後:"+md5String);
boolean falg = validPassword(sourceString,md5String);
System.out.println("----------輸入字符串校驗結果:"+falg);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("-----------------MD5加密 end--------------------");
}
}java