工具类:
package com.valueaddedservices.web.utils;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import com.snake.bsys.common.support.DateUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 类名称:AESUtils 类描述: AES加解密工具类 创建人:qiuying
* 创建时间:2018年11月28日 9:07:01
*
* @version
*/
public class AESUtils {
private static String algorithm = "AES";
/**
* 加密
* @param str
* @param key
* @return
* @throws Exception
*/
public static String aesEncrypt(String str, String key) throws Exception {
if (str == null || key == null)
return null;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec(key.getBytes("utf-8"), algorithm));
byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
return new BASE64Encoder().encode(bytes);
}
/**
* 解密
* @param str
* @param key
* @return
* @throws Exception
*/
public static String aesDecrypt(String str, String key) throws Exception {
if (str == null || key == null)
return null;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(key.getBytes("utf-8"), algorithm));
byte[] bytes = new BASE64Decoder().decodeBuffer(str);
bytes = cipher.doFinal(bytes);
return new String(bytes, "utf-8");
}
}
实例:
String aesEncrypt = AESUtils.aesEncrypt(加密内容, 秘钥);