@Slf4j @Component public class AESUtil { private static final String KEY_ALGORITHM = "AES"; private static String DEFAULT_CIPHER_ALGORITHM ; private static String KEY; private static String IV; @Autowired private Environment env; private AESUtil() { } @PostConstruct public void init() { KEY = env.getProperty("emmp.aesencrypt.key"); IV = env.getProperty("emmp.aesencrypt.iv"); DEFAULT_CIPHER_ALGORITHM = env.getProperty("emmp.aesencrypt.defaultPadding"); } public static byte[] encrypt(String content, String key, String iv) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider()); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec); byte[] byteContent = content.getBytes(StandardCharsets.UTF_8); return cipher.doFinal(byteContent); } catch (Exception ex) { log.error(ex.getMessage(), ex); } return new byte[0]; } public static String decrypt(byte[] content, String key, String iv) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, new BouncyCastleProvider()); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec); byte[] result = cipher.doFinal(content); return new String(result, StandardCharsets.UTF_8); } catch (Exception ex) { log.error(ex.getMessage(), ex); } return null; } public static String getDecode(String content) { String decrypt; try { byte[] bytes = Hex.decodeHex(content); decrypt = decrypt(bytes, getKey(), getIv()); return decrypt; } catch (DecoderException e) { log.error("加密内容转换失败:" + e.getMessage()); decrypt = content; } return decrypt; } private static String getKey() { return KEY; } private static String getIv() { return IV; } }