AES加密的正确姿势如下(已验证,没问题):
import com.ucar.supergw.common.exception.SupergwException;
import com.ucar.supergw.common.exception.code.SystemErrorCode;
import com.ucar.supergw.common.exception.util.AssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
/** 日志记录器 */
private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);
/**
*
* @param sSrc 明文字符串
* @param keyStr 加密秘钥
* @param ivStr 加密向量
* @param charset 编码
* @return
*/
public static String encrypt(String sSrc, String keyStr, String ivStr, String charset) {
AssertUtil.isNotBlank(sSrc, SystemErrorCode.ILLEGAL_PARAMETER, "加密字符串为空");
try {
SecretKeySpec skeySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
// "算法/模式/补码方式"
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes(charset));
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
String str = new BASE64Encoder().encode(encrypted);
//注意:linux环境下加密时,会自动补\r \n到加密数据里面
//str = str.replaceAll("\r\n", "");
//str = str.replaceAll("\n", "");
str = str.replaceAll(System.getProperty("line.separator"), "");
return str;
} catch (Exception e) {
LOGGER.error("AESUtil 加密失败",e);
throw new SupergwException(SystemErrorCode.ENCRYPT_ERROR, "加密失败", e);
}
}
/**
* AES 解密
*
* @param sSrc 密文字符串
* @param sKey 加密秘钥
* @param ivStr 加密向量
* @param charset 编码
* @return
*/
public static String decrypt(String sSrc, String sKey, String ivStr, String charset) {
AssertUtil.isNotBlank(sSrc, SystemErrorCode.ILLEGAL_PARAMETER, "解密字符串为空");
try {
byte[] raw = sKey.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, charset);
//originalString = originalString.replaceAll("\r\n", "");
//originalString = originalString.replaceAll("\n", "");
originalString = originalString.replaceAll(System.getProperty("line.separator"), "");
return originalString;
} catch (Exception ex) {
LOGGER.error("AESUtil 解密失败",ex);
throw new SupergwException(SystemErrorCode.DECRYPT_ERROR, "解密失败", ex);
}
}
}