package cn.gistack.system.user.sync.util;
|
|
import cn.gistack.system.user.sync.constant.CimsConstants;
|
import cn.gistack.system.user.sync.exception.BusinessException;
|
import cn.gistack.system.user.sync.exception.ErrorCode;
|
import org.springframework.util.StringUtils;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.SecretKeySpec;
|
|
/**
|
* AES加密解密
|
*
|
* @author wd
|
*/
|
public class SecurityUtil {
|
|
private SecurityUtil() {
|
}
|
|
/**
|
* AES加密
|
*
|
* @param content 明文
|
* @return 密文
|
*/
|
public static String encryptAES(String content, String secretKey) {
|
checkParam(content, secretKey);
|
//AES加密
|
return encrypt(content, secretKey);
|
}
|
|
/**
|
* AES解密
|
*
|
* @param encryptResultStr 密文
|
* @return 明文
|
*/
|
public static String decryptAES(String encryptResultStr, String secretKey) {
|
checkParam(encryptResultStr, secretKey);
|
try {
|
// BASE64位解密
|
byte[] decryptFrom = Base64.getDecoder().decode(encryptResultStr);
|
|
//AES解密
|
byte[] decryptResult = decrypt(decryptFrom, secretKey);
|
return new String(decryptResult);
|
} catch (Exception e) {
|
// 当密文不规范时会报错,可忽略,但调用的地方需要考虑
|
throw new BusinessException(ErrorCode.CONTENT_EMPTY_ERROR);
|
}
|
}
|
|
/**
|
* 校验参数
|
*/
|
private static void checkParam(String encryptResultStr, String secretKey) {
|
if (StringUtils.isEmpty(encryptResultStr)) {
|
throw new BusinessException(ErrorCode.CONTENT_EMPTY_ERROR);
|
}
|
if (!secretKey.matches(CimsConstants.SECRET_KEY_REGEX)) {
|
throw new BusinessException(ErrorCode.SECRET_KEY_ERROR);
|
}
|
}
|
|
|
/**
|
* 加密
|
*
|
* @param content 需要加密的内容
|
* @param secretKey 加密密钥
|
* @return
|
*/
|
private static String encrypt(String content, String secretKey) {
|
try {
|
byte[] raw = secretKey.getBytes(CimsConstants.SECRET_KEY_ENCODING);
|
SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//NOSONAR sonar扫描忽略这段代码
|
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
|
byte[] bytes = cipher.doFinal(content.getBytes(CimsConstants.SECRET_KEY_ENCODING));
|
return Base64.getEncoder().encodeToString(bytes);
|
} catch (Exception e) {
|
throw new BusinessException(ErrorCode.CONTENT_ENCODE_ERROR);
|
}
|
}
|
|
/**
|
* 解密
|
*
|
* @param content 待解密内容
|
* @param secretKey 解密密钥
|
* @return
|
*/
|
private static byte[] decrypt(byte[] content, String secretKey) {
|
try {
|
byte[] raw = secretKey.getBytes(CimsConstants.SECRET_KEY_ENCODING);
|
SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//NOSONAR sonar扫描忽略这段代码
|
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
return cipher.doFinal(content);
|
} catch (Exception e) {
|
throw new BusinessException(ErrorCode.SECRET_DECODE_ERROR);
|
}
|
}
|
}
|