天天看點

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"));

本文轉自 沉澱人生 51CTO部落格,原文連結:http://blog.51cto.com/825272560/1863770