jasypt-spring-boot encrypts sensitive information

1. Introduction

There are a lot of sensitive information in back-end development, such as database user name and password, third-party Apikey, cloud service provider’s secretKey, etc. If you don’t want to use plain text to configure in application.yml, you can use jasypt to encrypt these fields.

Another very important point is that if you open source something yourself and upload the code to some code hosting platform, you must hide sensitive information. Encrypting with jasypt can simplify each upload and drop-down code to modify sensitive information.

Official document: https://github.com/ulisesbocchio/jasypt-spring-boot , the usage method of the official document is clearly described and applicable to various situations. Let me briefly record the method of encrypting MySQL username and password

2. Import dependencies

    <dependencies>
        <!-- jasypt 敏感数据加密,如:数据库密码,阿里云短信服务等-->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
            <scope>runtime</scope>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- springboot 启动包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

3. Encrypted field tool class

Encrypt the mysql user name and password, pass the user name and password into the fields array, and save the printed results and configure it in the application.yaml file below

public class JasyptUtil {
    
    
    private static PooledPBEStringEncryptor encryptor;

    static{
    
    
        encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword("This is a secret key"); // 秘钥
        config.setAlgorithm("PBEWithMD5AndDES");
        //config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
    }

    public static void main(String[] args) {
    
    
    	// 需要加密的字段
        String[] fields = {
    
    "root","123456"};
        for (String field : fields) {
    
    
            System.out.println(field+"---->"+encryptorField(field));
        }
    }

    public static String encryptorField(String field){
    
    
       return  encryptor.encrypt(field);
    }
    public static String decryptField(String field){
    
    
        return encryptor.decrypt(field);
    }
}

You can see that the encrypted string is as follows
insert image description here

Four, application.yaml configuration

The data source username and password use the encrypted fields generated above

spring:
  datasource:
    username: ENC(J5GOvO1FBgtiwEytIjU/4WdzHUgbJq/W)
    password: ENC(SqCHgntWcYnthvtWGA3+GAycDle/qCBx)
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/oauth?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
# jasypt 敏感数据加密配置
# 详细用法可参考 https://github.com/ulisesbocchio/jasypt-spring-boot
jasypt:
  encryptor:
    password: 123456 # 秘钥,除了该项,下面都是默认值,该项建议设置 JVM 启动参数,如:-Djasypt.encryptor.password=123456
    algorithm: PBEWithMD5AndDES # 加密算法
    key-obtention-iterations: 1000 # 迭代次数,值越大越复杂,相对越安全
    pool-size: 1
    provider-name: SunJCE
    salt-generator-classname: org.jasypt.salt.RandomSaltGenerator
    iv-generator-classname: org.jasypt.iv.RandomIvGenerator
    string-output-type: base64
    proxy-property-sources: false
    property:
      prefix: ENC( # 默认前缀
      suffix: ) # 默认后缀

5. Start-up test

Query the user table of MySQL to print the user name and password

package com.ye;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@SpringBootApplication
public class Test2Application {
    
    

    public static void main(String[] args) throws SQLException {
    
    
        ConfigurableApplicationContext context = SpringApplication.run(Test2Application.class, args);

        DataSource dataSource = (DataSource) context.getBean("dataSource");
        Connection connection = dataSource.getConnection();
        try {
    
    
            PreparedStatement ps = connection.prepareStatement("select * from user;");
            ResultSet rs = ps.executeQuery();
            System.out.println("<----------  user 表数据  ----------->");
            while (rs.next()) {
    
    
                String userName = rs.getString("user_name");
                String password = rs.getString("password");
                System.out.printf("userName: %s, password: %s%n", userName, password);
            }
        } catch (SQLException ex) {
    
    
            ex.printStackTrace();
            connection.close();
        }
    }
}

Click Edit Configurations to add VM startup parameters -Djasypt.encryptor.password="This is a secret key". This password is consistent with the encryption tool JasyptUtil password.

insert image description here

After the successful operation, the printed results are as
insert image description here
follows After the above operations, we have encrypted the sensitive information

Guess you like

Origin blog.csdn.net/qq_41538097/article/details/127075430