package com.tu.Security;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

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

/***
 * 对称加密算法-AES
 * 
 * <PRE>
 * DES替代者
 * 
 * 密钥长度:128,192,256 默认128 工作模式:ECB,CBC,PCBC,CTR,CTS,CFB,CFB8到128,OFB,OFB8到128 填充方式:NoPadding,PKCS5Padding,ISO10126Padding 实现方:JDK(256位密钥需要获得无政策限制权限文件)
 * 填充方式:PKCS7Padding,ZeroBytePadding 实现方:BC
 * 
 * 无政策限制权限文件是指,因为某些国家的进口管制限制,Java发布的远行环境包中的加解密有一定的限制
 * </PRE>
 * 
 * @author comtu
 */
public class AES {
	public static void main(String[] args) {
		jdkAES("comtu");
	}

	public static void jdkAES(String src) {
		try {
			// 生成KEY
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.init(128);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] keyBytes = secretKey.getEncoded();

			// key转换
			Key key = new SecretKeySpec(keyBytes, "AES");

			// 加密
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("jdk aes encrypt : " + Base64.encodeBase64String(result));

			// 解密
			cipher.init(Cipher.DECRYPT_MODE, key);
			result = cipher.doFinal(result);
			System.out.println("jdk aes desrypt : " + new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
