diff --git a/cf-framework/cf-common/src/main/java/com/cf/imes/framework/common/util/encrypt/AesUtils.java b/cf-framework/cf-common/src/main/java/com/cf/imes/framework/common/util/encrypt/AesUtils.java new file mode 100644 index 000000000..77a3b4733 --- /dev/null +++ b/cf-framework/cf-common/src/main/java/com/cf/imes/framework/common/util/encrypt/AesUtils.java @@ -0,0 +1,99 @@ +package com.cf.imes.framework.common.util.encrypt; + +import cn.hutool.core.util.CharsetUtil; +import lombok.extern.slf4j.Slf4j; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Base64; + +/** + * AES对称加密工具 + * + * @author Gqr + * @since 2024/8/23 16:38 + */ +@Slf4j +public class AesUtils { + + private static final String AES_ALG = "AES"; + + private static final String AES_CBC_PCK_ALG = "AES/CBC/PKCS5Padding"; + + + /** + * 解密 + * + * @param content + * @param aesKey + * @return + * @throws Exception + */ + public static String decrypt(String content, String aesKey) { + try { + Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG); + IvParameterSpec iv = new IvParameterSpec(initIv(AES_CBC_PCK_ALG)); + cipher.init(Cipher.DECRYPT_MODE, generateKey(aesKey.getBytes()), iv); + + byte[] cleanBytes = cipher.doFinal(Base64.getDecoder().decode(content.getBytes())); + return new String(cleanBytes, CharsetUtil.UTF_8); + } catch (Exception e) { + log.error("[AesUtils][decrypt]解密失败:{}", e.getMessage(), e); + // nacos热发布配置,空字符串会导致nacos轮训刷新配置 + return "default"; + } + } + + /** + * 生成key + * + * @param bytes + * @return + * @throws NoSuchAlgorithmException + */ + private static SecretKey generateKey(byte[] bytes) throws NoSuchAlgorithmException { + // 生成随机数 + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + // 设置随机数种子 + random.setSeed(bytes); + + // aes算法生成器 + KeyGenerator keyGen = KeyGenerator.getInstance(AES_ALG); + keyGen.init(128, random); // 使用128位的密钥 + return keyGen.generateKey(); + } + + + /** + * 初始向量的方法, 全部为0. 这里的写法适合于其它算法,针对AES算法的话,IV值一定是128位的(16字节). + * + * @param fullAlg + * @return + * @throws GeneralSecurityException + */ + private static byte[] initIv(String fullAlg) { + + try { + Cipher cipher = Cipher.getInstance(fullAlg); + int blockSize = cipher.getBlockSize(); + byte[] iv = new byte[blockSize]; + for (int i = 0; i < blockSize; ++i) { + iv[i] = 0; + } + return iv; + } catch (Exception e) { + + int blockSize = 16; + byte[] iv = new byte[blockSize]; + for (int i = 0; i < blockSize; ++i) { + iv[i] = 0; + } + return iv; + } + } +}