AES对称加解密
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Aes { public static final String algorithm = "AES"; // AES/CBC/NOPaddin // AES 默认模式 // 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new // IvParameterSpec(key.getBytes()); // NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍 public static final String transformation = "AES/CBC/NOPadding"; public static final String key = "1111111111111111"; /*** * BASE64解密 * @param key * @return * @throws Exception */ public static byte[] decryBASE64(String key) throws Exception{ return (new BASE64Decoder()).decodeBuffer(key); } /*** * BASE64加密 * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception{ return (new BASE64Encoder()).encode(key); } /*** * 加密 * @param original 需要加密的参数(注意必须是16位) * @return * @throws Exception */ public static String encryptByAES(String original) throws Exception { // 获取Cipher Cipher cipher = Cipher.getInstance(transformation); // 生成密钥 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm); // 指定模式(加密)和密钥 // 创建初始化向量 IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // cipher.init(Cipher.ENCRYPT_MODE, keySpec); // 加密 byte[] bytes = cipher.doFinal(original.getBytes()); return encryptBASE64(bytes); } /** * 解密 * @param encrypted 需要解密的参数 * @return * @throws Exception */ public static String decryptByAES(String encrypted) throws Exception { // 获取Cipher Cipher cipher = Cipher.getInstance(transformation); // 生成密钥 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm); // 指定模式(解密)和密钥 // 创建初始化向量 IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); // cipher.init(Cipher.DECRYPT_MODE, keySpec); // 解密 byte[] bytes = cipher.doFinal(decryBASE64(encrypted)); return new String(bytes); } }