`

java加密解密

 
阅读更多
package cn.etuo.share.xwap.buyflow.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class Base64Util {
	private static char[] base64EncodeChars = new char[]{
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
        'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3',
        '4', '5', '6', '7', '8', '9', '+', '/'};

	private static byte[] base64DecodeChars = new byte[]{
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
        -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};


	public static String encode(String str) {
		byte[] data = str.getBytes();
	    StringBuffer sb = new StringBuffer();
	    int len = data.length;
	    int i = 0;
	    int b1, b2, b3;
	    while (i < len) {
	        b1 = data[i++] & 0xff;
	        if (i == len) {
	            sb.append(base64EncodeChars[b1 >>> 2]);
	            sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
	            sb.append("==");
	            break;
	        }
	        b2 = data[i++] & 0xff;
	        if (i == len) {
	            sb.append(base64EncodeChars[b1 >>> 2]);
	            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
	            sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
	            sb.append("=");
	            break;
	        }
	        b3 = data[i++] & 0xff;
	        sb.append(base64EncodeChars[b1 >>> 2]);
	        sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
	        sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
	        sb.append(base64EncodeChars[b3 & 0x3f]);
	    }
	    return sb.toString();
	}

	public static String decode(String str) throws UnsupportedEncodingException {
	    StringBuffer sb = new StringBuffer();
	    byte[] data = str.getBytes("US-ASCII");
	    int len = data.length;
	    int i = 0;
	    int b1, b2, b3, b4;
	    while (i < len) {
	       
	        do {
	            b1 = base64DecodeChars[data[i++]];
	        } while (i < len && b1 == -1);
	        if (b1 == -1) break;
	       
	        do {
	            b2 = base64DecodeChars
	                    [data[i++]];
	        } while (i < len && b2 == -1);
	        if (b2 == -1) break;
	        sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
	       
	        do {
	            b3 = data[i++];
	            if (b3 == 61) return new String(sb.toString().getBytes("iso8859-1"));
	            b3 = base64DecodeChars[b3];
	        } while (i < len && b3 == -1);
	        if (b3 == -1) break;
	        sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
	       
	        do {
	            b4 = data[i++];
	            if (b4 == 61) return new String(sb.toString().getBytes("iso8859-1"));
	            b4 = base64DecodeChars[b4];
	        } while (i < len && b4 == -1);
	        if (b4 == -1) break;
	        sb.append((char) (((b3 & 0x03) << 6) | b4));
	    }
	    return new String(sb.toString().getBytes("iso8859-1"));
	}
	
	public static String decode(String str,String charset ) throws UnsupportedEncodingException {
	    StringBuffer sb = new StringBuffer();
	    byte[] data = str.getBytes("US-ASCII");
	    int len = data.length;
	    int i = 0;
	    int b1, b2, b3, b4;
	    while (i < len) {
	       
	        do {
	            b1 = base64DecodeChars[data[i++]];
	        } while (i < len && b1 == -1);
	        if (b1 == -1) break;
	       
	        do {
	            b2 = base64DecodeChars
	                    [data[i++]];
	        } while (i < len && b2 == -1);
	        if (b2 == -1) break;
	        sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
	       
	        do {
	            b3 = data[i++];
	            if (b3 == 61) return new String(sb.toString().getBytes(charset));
	            b3 = base64DecodeChars[b3];
	        } while (i < len && b3 == -1);
	        if (b3 == -1) break;
	        sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
	       
	        do {
	            b4 = data[i++];
	            if (b4 == 61) return new String(sb.toString().getBytes(charset));
	            b4 = base64DecodeChars[b4];
	        } while (i < len && b4 == -1);
	        if (b4 == -1) break;
	        sb.append((char) (((b3 & 0x03) << 6) | b4));
	    }
	    return new String(sb.toString().getBytes(charset));
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
	    String s = "1234567890";
	    System.out.println("加密前:" + s);
	    String x = encode(s);
	    System.out.println("加密后:" + x);
	    System.out.println("解密后:" + decode(x));
	}
	
}

 

package cn.etuo.share.xwap.buyflow.service;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.Security;

/**
 * 密码加密工具类<br/>
 * 2010-9-7 15:40:57:poplar 增加单例模式
 * Time:2010-8-17 11:41:57
 *
 * @author <a href="mailto:heshucha@139.com">schell</a>
 * @version Ver 0.1
 * @since IceFis 0.1
 */
public class DESPlus {

    static class Instance {
        private static DESPlus DPLUS = new DESPlus();
    }

    public static DESPlus getInstance() {
        return Instance.DPLUS;
    }

    private static String strDefaultKey = "national";

    private Cipher encryptCipher = null;

    private Cipher decryptCipher = null;

    public String byteArr2HexStr(byte[] arrB) throws Exception {
        int iLen = arrB.length;
        // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
        StringBuffer sb = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            // 把负数转换为正数
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            // 小于0F的数需要在前面补0
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

    /**
     * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)
     * 互为可逆的转换过程
     *
     * @param strIn 需要转换的字符串
     * @return 转换后的byte数组
     * @throws Exception 本方法不处理任何异常,所有异常全部抛出
     */
    public byte[] hexStr2ByteArr(String strIn) throws Exception {
        byte[] arrB = strIn.getBytes();
        int iLen = arrB.length;

        // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
        byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

    /**
     * 默认构造方法,使用默认密钥
     */
    private DESPlus() {
        this(strDefaultKey);
    }

    /**
     * 指定密钥构造方法
     *
     * @param strKey 指定的密钥
     */
    private DESPlus(String strKey) {
        try {
            Security.addProvider(new com.sun.crypto.provider.SunJCE());
            Key key = getKey(strKey.getBytes());
            encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key);
            decryptCipher = Cipher.getInstance("DES");
            decryptCipher.init(Cipher.DECRYPT_MODE, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密字节数组
     *
     * @param arrB 需加密的字节数组
     * @return 加密后的字节数组
     */
    public byte[] encrypt(byte[] arrB) throws Exception {
        return encryptCipher.doFinal(arrB);
    }

    /**
     * 加密字符串
     *
     * @param strIn 需加密的字符串
     * @return 加密后的字符串
     */
    public String encrypt(String strIn) {
        try {
            return byteArr2HexStr(encrypt(strIn.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密字节数组
     *
     * @param arrB 需解密的字节数组
     * @return 解密后的字节数组
     * @throws Exception 异常
     */
    public byte[] decrypt(byte[] arrB) throws Exception {
        return decryptCipher.doFinal(arrB);
    }

    /**
     * 解密字符串
     *
     * @param strIn 需解密的字符串
     * @return 解密后的字符串
     */
    public String decrypt(String strIn) {
        try {
            return new String(decrypt(hexStr2ByteArr(strIn)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
     *
     * @param arrBTmp 构成该字符串的字节数组
     * @return 生成的密钥
     * @throws Exception 异常
     */
    private Key getKey(byte[] arrBTmp) throws Exception {
        // 创建一个空的8位字节数组(默认值为0)
        byte[] arrB = new byte[8];

        // 将原始字节数组转换为8位
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }

        // 生成密钥
        return new javax.crypto.spec.SecretKeySpec(arrB, "DES");
    }
    
    public static void main(String[] args) {
    	String t = new DESPlus().encrypt("1234567890");
    	String s = new DESPlus().decrypt(t);
    	System.out.println(t);
    	System.out.println(s);
	}
    
    
}



 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics