涉及内容
PropertyPlaceholderConfigurer类
jasypt-1.9.2

package com.hand.hdmp.cux.utils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

public class EncryptPropertyCfg extends PropertyPlaceholderConfigurer {

    /**
     * :是否开启加密
     */
    private static Boolean encryOrDecry = false;
    /**
     * :加密所使用的算法
     */
    private static String algorithm = "";
    /**
     * :加密所使用的盐值
     */
    private static String solt = "";
    /**
     * 存放需要解密的key
     */
    private static Set<String> encryptSet = new HashSet<String>(16);

    private static final Logger logger = LoggerFactory.getLogger(EncryptPropertyCfg.class);

    static {
        // 存放解密的key
        encryptSet.add("redis.password");
        loadPropertiesFile();
    }

    /**
     * convertProperty : 重写convertProperty方法用于spring加载时配置文件中值回显
     *
     * @param propertyName  配置的名称 key
     * @param propertyValue 配置的值 value
     * @return java.lang.String
     * @author admin
     * @version 1.0
     * @date 2022/9/21 14:38
     * @since JDK 1.8
     */
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (checkData(propertyName, propertyValue)) {
            System.out.println("=============Start Redis password decryption ===============");
            logger.info("algorithm is: {} and solt is :{}", algorithm, solt);
            logger.info("propertyName is: {} and propertyValue is :{}", propertyName, propertyValue);
            return decodeByJasypt(algorithm, solt, propertyValue);
        }
        return super.convertProperty(propertyName, propertyValue);
    }

    /**
     * processProperties : 重写processProperties方法,通过map来进行承接配置项
     *
     * @param beanFactoryToProcess
     * @param props
     * @return void
     * @author admin
     * @version 1.0
     * @date 2022/9/21 14:53
     * @since JDK 1.8
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        String keyStr = "";
        String value = "";
        for (Object key : props.keySet()) {
            keyStr = key.toString();
            if (ObjectUtils.isNotEmpty(keyStr) && ObjectUtils.isNotEmpty(props.getProperty(keyStr))) {
                value = props.getProperty(keyStr);
                HashMap ctxPropertiesMap = new HashMap();
                ctxPropertiesMap.put(keyStr, value);
            }
        }
    }

    /**
     * decodeByJasypt :用于解密操作
     *
     * @param algorithm  解密算法
     * @param pwd        解密的盐值
     * @param decryptStr 需要解密得字符串
     * @return java.lang.String
     * @author admin
     * @version 1.0
     * @date 2022/9/21 14:30
     * @since JDK 1.8
     */
    private String decodeByJasypt(String algorithm, String pwd, String decryptStr) {
        StandardPBEStringEncryptor stringEncryptor = new StandardPBEStringEncryptor();
        /*选用的加密算法:配置文件中配置如下的算法*/
        stringEncryptor.setAlgorithm(algorithm);
        /*加密得盐值:配置文件中配置的solt*/
        stringEncryptor.setPassword(pwd);
        /*要加密的文本*/
        String decrypt = stringEncryptor.decrypt(decryptStr);
        return decrypt;
    }

    /**
     * checkData : 相关值校验
     *
     * @param propertyName
     * @param propertyValue
     * @return java.lang.Boolean
     * @author admin
     * @version 1.0
     * @date 2022/9/23 9:33
     * @since JDK 1.8
     */
    private Boolean checkData(String propertyName, String propertyValue) {
        if (encryOrDecry && encryptSet.contains(propertyName)) {
            if (StringUtils.isBlank(propertyName)) {
                throw new IllegalStateException("The propertyName cannot be empty");
            } else if (StringUtils.isBlank(propertyValue)) {
                throw new IllegalStateException("The propertyValue cannot be empty");
            } else if (StringUtils.isEmpty(algorithm)) {
                throw new IllegalStateException("The configuration of Jasypt.encryptor.algorithm item cannot be empty");
            } else if (StringUtils.isEmpty(solt)) {
                throw new IllegalStateException("The configuration of Jasypt.encryptor.solt item cannot be empty");
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * loadPropertiesFile : 读取指定文件
     *
     * @param
     * @return void
     * @author jinhu.wang
     * @version 1.0
     * @date 2022/9/23 9:23
     * @since JDK 1.8
     */
    private static void loadPropertiesFile() {
        Properties props = new Properties();
        FileInputStream in = null;
        BufferedInputStream bf = null;
        try {
            //客户生产环境指定路径,本地开发测试时需改成当前redis所在的配置文件
            String path = "F:\\Developments\\IDEA\\IdeaHome\\安盛分摊\\1\\astp-hpm\\src\\main\\resources\\config.properties";
            in = new FileInputStream(path);
            bf = new BufferedInputStream(in);
            props.load(bf);

            algorithm = props.getProperty("jasypt.encryptor.algorithm");
            solt = props.getProperty("jasypt.encryptor.password");
            String falg = props.getProperty("jasypt.encryOrDecry");
            encryOrDecry = StringUtils.isNotBlank(falg) ? Boolean.valueOf(falg) : false;
        } catch (NullPointerException e) {
            logger.error("读取指定文件异常,",e);
        } catch (IOException e) {
            logger.error("当前操作异常,",e);
        } finally {
            if (null != bf) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in == null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐