jasypt对mysql数据库配置进行账号密码加密

439 阅读1分钟
  1. 引入依赖

       <!--数据库加密解密-->
            <dependency>
                <groupId>com.github.ulisesbocchio</groupId>
                <artifactId>jasypt-spring-boot-starter</artifactId>
                <version>1.14</version>
            </dependency>  
             <!--数据库加密解密结束-->
            <dependency>
                <groupId>com.github.ulisesbocchio</groupId>
                <artifactId>jasypt-spring-boot</artifactId>
                <version>1.14</version>
            </dependenc     
    
  2. yml配置添加盐值

    # jasypt
    jasypt:
      encryptor:
        password: Kl+GRtuL2GAMEFlah1F+W+PS0I2yEE7RLb7iiEBQlXU=
    
  3. 生成加密后的密匙

       public static void main(String[] args) {
            BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
            //加密所需的 salt(盐)
            textEncryptor.setPassword("Kl+GRtuL2GAMEFlah1F+W+PS0I2yEE7RLb7iiEBQlXU=");
            //要加密的数据(数据库的用户名或密码)
            String username = textEncryptor.encrypt("root");
            String password = textEncryptor.encrypt("ilEs52817a665f37");
            System.out.println("username:" + username);
            System.out.println("password:" + password);
        }
    
  4. 将测试用例中生成的密匙添加到 application (应用) .yml配置中,数据库密文使用ENC进行标识

spring:
  # 数据库配置
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: localhost:3306
      username: ENC(9yyRfS8ljI2kh422XHra0g==)
      password: ENC(nCZrXZJSahl2xkXbu9+C/Q==)