Based on the data source DRUID spring boot password encryption and data source monitoring and control system

Foreword

With the increasing demand for innovation and technology, spring boot framework is becoming increasingly popular, more and more she appeared in our project, of course, the main reason is because spring boot building project is too cool, to build easy to develop simple and efficient. Today we are not to learn specialized spring boot project, we want to say is encrypted and monitoring data sources, to say the monitoring, surveillance is not no problem, but the data source encryption system but comes to our security. For the usual learning tests, we configured a database password in clear text in the project is no problem, because our data is not important, it does not matter, but in reality the production platform, Plain text password is likely to cause our database password leak, eventually leading to our production data leakage, which also reflects the need for encryption of the data source production environment. Here we look at how to implement it to encrypt the data source.

Create a spring boot project

The process of creating not go into details, here is my project dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>io.githu.syske</groupId>
    <artifactId>druid-datasouce-decrypt</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>druid-datasouce-decrypt</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 阿里巴巴druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

If your database is Oracle, then you should mysql database-driven replacement drive into Oracle

Modify spring boot configuration information project
server:
  port: 8083

I used yaml way, and then start your project, because there is no controller and other code, so no effect, but the project can start.

Encrypted data source password, create publickey

There is nothing to talk about, I placed directly Code:

import org.junit.Test;

/**
 * @program: druid-datasouce-decrypt
 * @description:
 * @author: liu yan
 * @create: 2019-12-02 18:34
 */
public class DBencrydtTest {
    @Test
    public void test() {
        String[] args = {"root"};
        try {
            com.alibaba.druid.filter.config.ConfigTools.main(args);
        } catch (Exception e) {

        }

        System.out.println();
    }
}

It should be noted, args array is placed in passwords, run the above code, you will see the console will print the following information:

privateKey:MIIBVAIBADANBgkqhkiFWERAERFrterfgdggE6AgEAAkEAqboz+iNXPv1jgKAhDW7W+L/NwqG6GDTo49BjmlMg3WxBg4w9h4RC3oRO40EOjL7+DtEBBlCZ6OHZfZWKh17FmwIDAQABAkA/azwQszPebX/IiAzRoCDjQYf4ucV3Vg3PUgZlm7okAbsXrxz2xrdnM8Er08YKm3vUOmWQmSvaOI3CqdrK1f2BAiEA4XbEkCOxWVxbDLihyudClvrgLbZZyODlx5E2phn4gXMCIQDAtvMeJiXlGQBxFr/ci0r99FiYUeag/ZFwOjyhIzWBOQIgYg3bEqzTNn/aAUBS7QGCjlLxKDBD//7/L7nRwI9O6k0CIQCdBnUiY8MM4UpS206JzZXVR3vI4TMiinovD8THJ4E5QQIgRM1QlD1PG5YTxBxZMrLm2weBxsqXhvdJuTc1GXmoUxg=
publicKey:MFwwDQYJKoZIhvcewrwerfrrgfg43534M/ojVz79Y4CgIQ1u1vi/zcKhuhg06OPQY5pTIN1sQYOMPYeEQt6ETuNBDoy+/g7RAQZQmejh2X2ViodexZsCAwEAAQ==
password:O9JBjc86r9IhEoIE6jevJtgsgCXZAKCWH2UtO0tbG62zqIK5G5qJOCm1u9ju+lnno15vmq+TO5WqEWGzvkDNGg==

privateKey is your private key, publicKey is the public key, password is encrypted password after you. We used configured with two, one is a public key, a password is, the reason is to configure the public key to decrypt the public key. As the save information, back then spring boot configuration to use.

Increase in the data source configuration

Increase in the data source configuration information:

# 阿里巴巴druid数据源配置
spring:
  datasource:
  # 数据源驱动类型,这里是druid
    type: com.alibaba.druid.pool.DruidDataSource
    # sql脚本编码
    sql-script-encoding: utf-8
    druid:
    # 驱动的类名
      driver-class-name: com.mysql.cj.jdbc.Driver
      # 数据库连接密码
      username: root
      # 数据库地址
      url: jdbc:mysql://127.0.0.1:3307/spring?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
      # 这里配置的是前面我们生成的密码
      password: Y2YOft/vPjw/JFPkevqZZKi8pCHu5ambR2ivSxgipTbL76pOoxNw3Un5Hcarbe9AqUImr+wS7YI6TjJZOVYjzA==
      # 这里设置连接配置,key配置的是我们前面生成的publicKey
      connection-properties: config.decrypt=true;config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJI/xqbyvpVttxfAKulKeSTIb7tZAGaFcPyTnE2r7AHTQ8kOnqKXDda4u59umt9XBFxi7db28KxeVooB138zuRUCAwEAAQ==
      filter:
        config:
        # 启用druid的拦截器
          enabled: true
      # 连接池的配置信息
      # 初始化时建立物理连接的个数
      initial-size: 3
      # 连接池最小连接数
      min-idle: 3
      # 连接池最大连接数
      max-active: 20
      # 获取连接时最大等待时间,单位毫秒
      max-wait: 60000
      # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      test-while-idle: true
      # 既作为检测的间隔时间又作为testWhileIdel执行的依据
      time-between-connect-error-millis: 60000
      # 销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
      min-evictable-idle-time-millis: 30000
      # 用来检测连接是否有效的sql 必须是一个查询语句
      # mysql中为 select 'x'
      # oracle中为 select 1 from dual
      validationQuery: select 'x'
      # 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      test-on-borrow: false
      # 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      test-on-return: false
      # 是否缓存preparedStatement,mysql5.5+建议开启
      pool-prepared-statements: true
      # 当值大于0时poolPreparedStatements会自动修改为true
      max-pool-prepared-statement-per-connection-size: 20
      # 合并多个DruidDataSource的监控数据
      use-global-data-source-stat: false
      # 配置扩展插件
      #监控统计拦截的filters
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 定时输出统计信息到日志中,并每次输出日志会导致清零(reset)连接池相关的计数器。
      time-between-log-stats-millis: 300000
      # 配置DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: '/*'
        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
      # 配置DruidStatViewServlet
      stat-view-servlet:
        # 是否启用StatViewServlet(监控页面)默认值为false(考虑到安全问题默认并未启动,如需启用建议设置密码或白名单以保障安全)
        enabled: true
        url-pattern: '/druid/*'
        # IP白名单(没有配置或者为空,则允许所有访问)
        allow: 127.0.0.1,192.168.0.1
        # IP黑名单 (存在共同时,deny优先于allow)
        deny: 192.168.0.128
        # 禁用HTML页面上的“Reset All”功能
        reset-enable: false
        # 登录名
        login-username: admin
        # 登录密码
        login-password: admin

The above remarks very detailed, it should emphasize two places, one key configuration there is publicKey, not with the wrong one to note here validationQuery mysql and Oracle is not the same, of course, you want to be removed this configuration.

The above configuration also added data source monitored annotation enough detail. The above configuration can be started after the completion of your project, and if there is no error, it means your configuration is no problem, if the start time of the error, indicating a problem with your configuration.

When the project started, to enter the druid data source monitoring page, only you need to enter your project addresses + / druid can, such as my address:

http://localhost:8083/druid

Then you add in the input configuration information inside a user name and password, you can see the monitoring page, if you want to see the sql-related monitoring information, you have to complete their own projects, the introduction of mybatis, configure your sql.

Epilogue

At this point, our project has been completed, according to the above process, we send the core data source encryption and monitoring under is to add the correct configuration information. If you made an error in the actual development process, the most important thing is to check our configuration is correct.

Guess you like

Origin www.cnblogs.com/caoleiCoding/p/12000926.html