在我們的程式設計中,我們經常要加密一些特殊的內容,今天總結了幾個簡單的加密方法,分享給大家!
如何用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"));}}
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!