JAVA 字串加密、密碼加密實現方法_java

來源:互聯網
上載者:User

在我們的程式設計中,我們經常要加密一些特殊的內容,今天總結了幾個簡單的加密方法,分享給大家!

如何用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"));}}

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.