package cn.**.util.encryption;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
public class AesEncryption {
private static Logger logger = Logger.getLogger(AesEncryption.class);
public final static String KEY = "*********";
/**
* 算法/模式/补码方式
*/
public static final String SECRET = "AES/ECB/PKCS5Padding";
/**
* AES 加密
* @param sSrc
* @param sKey
* @return
* @throws Exception
* @see [类、类#方法、类#成员]
*/
public static String Encrypt(String sSrc, String sKey){
try {
//判断Key是否为空
if (sKey == null) {
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
return null;
}
byte[] raw = sKey.getBytes("utf8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance(SECRET);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return Base64.encodeBase64String(encrypted);//此处使用BAES64做转码功能,同时能起到2次加密的作用。
} catch (Exception e) {
logger.error("AesEncryption.Encrypt(" + sSrc + ", sKey) error...", e);
return null;
}
}
/**
* AES 解密
* @param sSrc
* @param sKey
* @return
* @throws Exception
* @see [类、类#方法、类#成员]
*/
public static String Decrypt(String sSrc, String sKey){
try {
// 判断Key是否正确
if (sKey == null) {
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
return null;
}
byte[] raw = sKey.getBytes("utf8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance(SECRET);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//先用bAES64解密
byte[] encrypted1 = Base64.decodeBase64(sSrc);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
logger.error("AesEncryption.Encrypt(" + sSrc + ", sKey) error...", e);
return null;
}
}
}
安全篇-AES/RSA加密机制:
https://www.jianshu.com/p/ec7bb7325ff2
http://www.cnblogs.com/makemelike/articles/3802518.html