栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

java工具类按环境读取配置

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java工具类按环境读取配置

@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;
    }

}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1040872.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号