Springboot整合Hikari數據庫連接池,密碼加密


1.application.yml配置

 1 spring:
 2   datasource:
 3     jdbcUrl: jdbc:mysql://127.0.0.1:3306/jby?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
 4     username: root
 5     password: 'f687101570bae7ce4d313c2b4440f4ae'
 6     #自動提交
 7     auto-commit: true
 8     #最小連接
 9     minimum-idle: 100
10     #最大連接
11     maximum-pool-size: 200
12     #最大空閑時間
13     idle-timeout: 60000
14     #連接池名
15     pool-name: DatebookHikariCP
16     #最大生命周期
17     max-lifetime: 900000
18     #連接超時時間
19     connection-timeout: 15000
20     #心跳檢測
21     connection-test-query: SELECT 'x' FROM DUAL

2. 構建UmspscDataSource類,繼承HikariDataSource類

 1 @Slf4j
 2 public class UmspscDataSource extends HikariDataSource {
 3     private String passwordDis;
 4     /**
 5      * 密匙
 6      */
 7     private final static String PKEY ="1234565437892132";
 8     @Override
 9     public String getPassword(){
10 
11         if(StringUtils.isNotBlank(passwordDis)){return passwordDis;}
12         String encPassword = super.getPassword();
13         if(null==encPassword){
14             return null;
15         }
16         log.info("數據庫密碼加解密,{"+encPassword+"}");
17         try{
18             //  密文解密,解密方法可以修改
19             String key = HexUtil.encodeHexStr(PKEY);
20             SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
21             passwordDis = aes.decryptStr(encPassword, CharsetUtil.CHARSET_UTF_8);
22             return passwordDis;
23         }catch (Exception e){
24             log.error("數據庫密碼解密出錯,{"+encPassword+"}");
25             log.error(LogUtil.e(e));
26             throw new AppException("數據庫密碼解密失敗!", e);
27         }
28     }
29 }

3.初始化DataSource類

 1 @Component
 2 public class CommonBeanFactory {
 3 
 4     @Bean(name = "dataSource", autowire = Autowire.NO)
 5     @Primary
 6     @ConfigurationProperties(ignoreUnknownFields = false,prefix="spring.datasource")
 7     public HikariDataSource dataSource() {
 8         HikariDataSource druidDataSource = new UmspscDataSource();
 9         return druidDataSource;
10     }
11 }

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

構建密文

 1 @Slf4j
 2 public class Main {
 3 
 4     public static void main(String[] args) {
 5         //明文
 6         String content = "123456";
 7         //密匙
 8         String pkey = "1234565437892132";
 9         log.info("密匙:" + pkey);
10         String key = HexUtil.encodeHexStr(pkey);
11         //構建
12         SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
13 
14         //加密為16進制表示
15         String encryptHex = aes.encryptHex(content);
16         log.info("密文:" + encryptHex);
17         //解密為字符串
18         String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
19         log.info("明文:" + decryptStr);
20     }
21 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM