package com.java.test; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; public class Test { private static final Integer SALT_LENGTH = 12; /** * 16進制數字 */ private static final String HEX_NUMS_STR="0123456789abcdef"; /*----------------md5普通加密*/ /*** * MD5加密 生成32位md5碼 * @param 待加密字符串 * @return 返回32位md5碼 */ public static String md5Encode(String inStr) throws Exception { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); return ""; } byte[] byteArray = inStr.getBytes("UTF-8"); byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } /*----------------md5加鹽加密和解密*/ /** * 得到加密後的16進制形式口令 * @param password * @return * @throws Exception * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String getEncryptedPwd(String password) throws Exception{ try{ //聲明加密後的口令數組變量 byte[] pwd = null; //隨機數生成器 SecureRandom random = new SecureRandom(); //聲明鹽數組變量 byte[] salt = new byte[SALT_LENGTH]; //將隨機數放入鹽變量中 random.nextBytes(salt); //得到加密的數據 byte[] digest = encrypte(salt,password); //由於要在口令的字節數組中存放鹽,因此加上鹽的字節長度 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); }catch(Exception e){ throw new Exception("獲取加密密碼失敗",e); } } /** * * 根據鹽生成密碼 * @param salt * @param passwrod * @return * @throws Exception * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException */ public static byte[] encrypte(byte[] salt,String passwrod) throws Exception{ try{ //聲明消息摘要對象 MessageDigest md = null; //建立消息摘要 md = MessageDigest.getInstance("MD5"); //將鹽數據傳入消息摘要對象 md.update(salt); //將口令的數據傳給消息摘要對象 md.update(passwrod.getBytes("UTF-8")); //得到消息摘要的字節數組 return md.digest(); }catch(Exception e){ throw new Exception("Md5解密失敗",e); } } /** * 將指定byte數組轉換成16進制字符串(大寫) * @param b * @return */ public static String byteToHexString(byte[] bytes) { StringBuffer md5str = new StringBuffer(); //把數組每一字節換成16進制連成md5字符串 int digital; for (int i = 0; i < bytes.length; i++) { digital = bytes[i]; if(digital < 0) { digital += 256; } if(digital < 16){ md5str.append("0"); } md5str.append(Integer.toHexString(digital)); } return md5str.toString(); } /** * 驗證口令是否合法 * @param password * @param passwordInDb * @return * @throws Exception * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static boolean validPassword(String password, String passwordInDb) throws Exception { try{ //將16進制字符串格式口令轉換成字節數組 byte[] pwdInDb = hexStringToByte(passwordInDb); //聲明鹽變量 byte[] salt = new byte[SALT_LENGTH]; //將鹽從數據庫中保存的口令字節數組中提取出來 System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); //得到加密的數據 byte[] digest = encrypte(salt,password); //聲明一個保存數據庫中口令消息摘要的變量 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; } }catch(Exception e){ throw new Exception("密碼驗證失敗",e); } } /** * 將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; } public static void main(String[] args) throws Exception { //通過md5加鹽加密的123字符串爲str123 // System.out.println(getEncryptedPwd("123")); String str123_1 = "3fc7ed92dfb924f56ece855e74bf9c5c0c1f6f72a4dcc4a7db943bf0";//123加鹽加密 String str123_2 = "7dd3e5af8b373221a9864df5c2b46208fb819a256398a59deec5cb09";//123加鹽加密 //比對 輸入登陸祕密 和 數據庫加鹽加密密碼 boolean isTrue1 = validPassword("123",str123_1); boolean isTrue2 = validPassword("123",str123_2); boolean isTrue3 = validPassword("1231",str123_2); System.out.println("驗證密碼結果:"+isTrue1);//true System.out.println("驗證密碼結果:"+isTrue2);//true System.out.println("驗證密碼結果:"+isTrue3);//fase } }