在我們的程序設計中,我們經常要加密一些特殊的內容,今天總結了幾個簡單的加密方法,分享給大家!
如何用JAVA實現字符串簡單加密解密?為保證用戶信息安全,系統在保存用戶信息的時候,務必要將其密碼加密保存到數據庫。
需要使用密碼的時候,取出數據,解密處理即可。
避免保存明文密碼。
方案一:
package com.tnt.util; import java.security.MessageDigest; public class StringUtil { private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; /** * 轉換字節數組為16進製字串* * @param b * 字節數組* @return 16進製字串*/ public 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]; } public static String MD5Encode(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = byteArrayToHexString(md.digest(resultString .getBytes())); } catch (Exception ex) { } return resultString; } public static void main(String[] args) { System.err.println(MD5Encode("123456")); } }方案二
package com.shangyu.core.utils;public class MD5 {public static String getMD5(byte[] source) {String s = null;char hexDigits[] = { // 用來將字節轉換成16 進製表示的字符'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f' };try {java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");md.update(source);byte tmp[] = md.digest(); // MD5 的計算結果是一個128 位的長整數,// 用字節表示就是16 個字節char str[] = new char[16 * 2]; // 每個字節用16 進製表示的話,使用兩個字符,// 所以表示成16 進制需要32 個字符int k = 0; // 表示轉換結果中對應的字符位置for (int i = 0; i < 16; i++) { // 從第一個字節開始,對MD5 的每一個字節// 轉換成16 進製字符的轉換byte byte0 = tmp[i]; // 取第i 個字節str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字節中高4 位的數字轉換,// >>>// 為邏輯右移,將符號位一起右移str[k++] = hexDigits[byte0 & 0xf]; // 取字節中低4 位的數字轉換}s = new String(str); // 換後的結果轉換為字符串} catch (Exception e) {e.printStackTrace();}return s;}public static String getMD5(String str) {return getMD5(str.getBytes());}public static void main(String[] args){System.out.println(MD5.getMD5("123456"));}}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!