SpringBoot整合Druid,密码加密

1.application.yml配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/jby?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    # 密文
    password: 'f687101570bae7ce4d313c2b4440f4ae'
    initialSize: 100
    minIdle: 100
    maxActive: 200
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 'x' FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: config,stat

2. 构建UmspscDataSource类,继承DruidDataSource类

@Slf4j
public class UmspscDataSource extends DruidDataSource  {
    private String passwordDis;
    /**
     * 密匙
     */
    private final static String Pkey ="1234565437892132";
    @Override
    public String getPassword(){

        if(StringUtils.isNotBlank(passwordDis)){return passwordDis;}
        String encPassword = super.getPassword();
        if(null==encPassword){
            return null;
        }
        log.info("数据库密码加解密,{"+encPassword+"}");
        try{
            //  密文解密,解密方法可以修改
            String key = HexUtil.encodeHexStr(Pkey);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
            passwordDis = aes.decryptStr(encPassword, CharsetUtil.CHARSET_UTF_8);
            return passwordDis;
        }catch (Exception e){
            log.error("数据库密码解密出错,{"+encPassword+"}");
            log.error(LogUtil.e(e));
            throw new AppException("数据库密码解密失败!", e);
        }
    }
}

3.初始化DataSource类

@Component
public class CommonBeanFactory {
    @Bean(name = "dataSource", autowire = Autowire.NO, initMethod = "init")
    @Primary
    @ConfigurationProperties(ignoreUnknownFields = false,prefix="spring.datasource")
    public DruidDataSource dataSource() {
        DruidDataSource druidDataSource = new UmspscDataSource();
        return druidDataSource;
    }
}

*******************************

构建密文

@Slf4j
public class Main {

    public static void main(String[] args) {
        //明文
        String content = "123456";
        //密匙
        String pkey = "1234565437892132";
        log.info("密匙:" + pkey);
        String key = HexUtil.encodeHexStr(pkey);
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());

        //加密为16进制表示
        String encryptHex = aes.encryptHex(content);
        log.info("密文:" + encryptHex);
        //解密为字符串
        String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
        log.info("明文:" + decryptStr);
    }
}

 

转载于:https://www.cnblogs.com/ljb161108/p/11334256.html

你可能感兴趣的:(SpringBoot整合Druid,密码加密)