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

}

}