AES加密/解密-工具类

  |   0 评论   |   0 浏览
/**
 * AES工具类
 * @author pengzai
 *
 */
public class AESUtil {
	protected static Logger logger = Logger.getLogger(AESUtil.class);
    private static final String CHARSET = "UTF-8";							//编码
    private static final String ALGORITHM = "AES";							//算法
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";	//加密模式:CBC, 填充:PKCS5Padding
    private static final String IV = "d22b0a851e014f7b";					//偏移量

    /**
     * 加密
     * @param data
     * @param key
     * @return
     */
    public static String encryption(String data, String key){
    	logger.info("响应参数	加密前:"+data);
        try {
			return doAES(data, key, IV.getBytes(CHARSET), Cipher.ENCRYPT_MODE);
		} catch (Exception e) {
			logger.error("AES 加密异常",e);
			return null;
		}
    }

    /**
     * 解密
     * @param data
     * @param key
     * @return
     */
    public static String decrypt(String data, String key){
    	logger.info("请求参数	解密前:"+data);
        try {
			return doAES(data, key, IV.getBytes(CHARSET), Cipher.DECRYPT_MODE);
		} catch (Exception e) {
			logger.error("AES 解密异常",e);
			return null;
		}
    }

    public static String doAES(String data, String secretKey, byte[] iv, int mode) throws Exception {
    	boolean encrypt = mode == Cipher.ENCRYPT_MODE;
        byte[] content;
        //true 加密内容 false 解密内容
        if (encrypt) {
            content = data.getBytes(CHARSET);
        } else {
            content = Base64.decodeBase64(data);
        }

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getBytes(CHARSET),ALGORITHM);
        cipher.init(mode, skeySpec, new IvParameterSpec(iv));
        byte[] result = cipher.doFinal(content);
        if (encrypt) {
            return new String(Base64.encodeBase64String(result));
        } else {
            return new String(result, CHARSET);
        }
    }
    
    public static void main(String args[] ) {
    	System.out.println(AESUtil.encryption("ceshi","32d64cff1ab04622"));
    }
}