使用Jasypt对SpringBoot配置文件加密(数据源为SpringBoot默认的数据源HikariDataSource)

  • 引入Jasypt依赖
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
  • 将要加密的数据进行加密,例如数据库名,数据库密码
  public static void main(String[] args) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        //加密所需的salt(盐),随便写
        textEncryptor.setPassword("G0CvDz7oJn6");
        //要加密的数据(数据库的用户名或密码)
        String username = textEncryptor.encrypt("root");
        String password = textEncryptor.encrypt("root123");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
    }
  • 输出信息为
username:i8QgEN4uOy2E1rHzrpSTYA==
password:6eaMh/RX5oXUVca9ignvtg==
  • 配置yml文件,将生成的加密字符加入到ENC(加密字符串)
spring:
  datasource:
    username: ENC(i8QgEN4uOy2E1rHzrpSTYA==)
    password: ENC(6eaMh/RX5oXUVca9ignvtg==)
    url: jdbc:oracle:thin:@localhost:1521:data
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: oracle.jdbc.driver.OracleDriver
 
 
#\u52A0\u5BC6\u5DE5\u5177
jasypt:
  encryptor:
    password: G0CvDz7oJn6
    algorithm: PBEWithMD5AndDES
    poolSize: 1
    saltGeneratorClassname: org.jasypt.salt.RandomSaltGenerator
    stringOutputType: base64

下面就可以连接数据库了。此文章为转载文章,转载的目的是为了备注此加密的数据源为HikariDataSource