import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* AES加解密
* @author :
* @date :
* @version : key为16位
*/
public class AESUtil {
/**
*
* @Description:加密
* @param content
* @param key
* @return: 返回结果描述
* @return String: 返回值类型
* @throws
*/
public static String encrypt(String content, String key) {
try {
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
//BASE64转码
String other = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(encrypted);
return other;
} catch (Exception e) {
return "";
}
}
/**
*
* @Description:解密
* @param content
* @param key为16位
* @return: 返回结果描述
* @return String: 返回值类型
* @throws
*/
public static String decrypt(String content, String key) {
try {
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//base64转码
byte[] encrypted1 = new Base64().decode(content);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}