“This is the 26th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

Hi everyone, I believe a lot of friends in access to the project, if the query project configuration file, most of the database of IP, port, account name and password are clear, so if the package release out, if after decompression, direct extraction of plaintext message to a database, so it is not safe, Today we will learn a Spring Boot database link and account information security protection method based on Mybatis-Plus database configuration security protection example.

Quick start

Mybatis-Plus provides a way to protect database configuration and data security, which can reduce the problem of sensitive information leakage caused by database configuration to a certain extent. It is important to note that Mybatis-Plus3.3.2 and above is required to start support. Please take good care of the random key, of course, the fewer people know the better, so as to better protect.

Introduction of depend on

When using Mybatis-Plus to encrypt the perceptual information of database configuration, the corresponding dependency files need to be introduced first. The dependency information demonstrated based on version 3.3.2 is as follows.

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2 rainfall distribution on 10-12</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2 rainfall distribution on 10-12</version>
        </dependency>
Copy the code

Initialize the key and encrypt the database configuration file

Once the configuration file is introduced, we can set up the initialization key. We need to put the initialization key in the responsibility of someone, and remember not to lose it. Get the random secret key for encryption by calling AES.generateRandomKey. We encrypt database URLS, database user names and database instructions. The following is the plaintext information to be encrypted.

public static void main(String[] args) {
        // Public id: Java full stack architect
        // Generate 16-bit random AES key
        String randomKey = AES.generateRandomKey();
        String url = "jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
        // Author: Jie Xiao
        String userName = "test";
        String passWord = "123456";

        / / encrypted url
        String urlInfo = AES.encrypt(url, randomKey);
        / / encryption userName
        String userNameInfo = AES.encrypt(userName, randomKey);
        / / encrypted passWord
        String passWordInfo = AES.encrypt(passWord, randomKey);
        System.out.println("密钥 == " + randomKey);
        System.out.println("Encrypted URL ==" + urlInfo);
        System.out.println("Encrypted userName ==" + userNameInfo);
        System.out.println("Encrypted passWord ==" + passWordInfo);

    }
Copy the code

After the encryption is complete, we can set the encrypted database configuration information into the configuration file. The following is the initial database configuration encryption information.

Key == THE encrypted URL == 0wq5dyXkP3uy16ZUWOarD8DFRVGqy6pxlEZRp13CF2JpCxMN4vExc+no9zVbdFhVXYuGeM6UFqYP74tja18ja70oh0xR4EkDp+3hhRW8xHmJdhIBCoKxx1Bu D609sySUhL1k /eyBSdW+QOsHe21dbg== Encrypted userName == kBUIivUbkYU/fbowlKuDrQ== Encrypted passWord == uVM2hxgda3In1YBTD+R8kg==Copy the code

Setting the configuration file

We have encrypted the plaintext of the database above, and put the encrypted information into the configuration file. Note that the encrypted information configuration must begin with an MPW: string. As follows:

server.port=8888
swagger.enable=true
mybatis.mapper-locations=classpath*:mapper/ * * /*.xml spring.datasource.url=mpw:0wq5dyXkP3uy16ZUWOarD8DFRVGqy6pxlEZRp13CF2JpCxMN4vExc+no9zVbdFhVXYuGeM6UFqYP74tja18ja70oh0xR4E kDp+3hhRW8xHmJdhIBCoKxx1Bud609sySUhL1k/eyBSdW+QOsHe21dbg== spring.datasource.username=mpw:kBUIivUbkYU/fbowlKuDrQ== spring.datasource.password=mpw:uVM2hxgda3In1YBTD+R8kg== spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
Copy the code

Start the class

There is nothing special about the rest, just follow the normal project development. Write a startup class.

@SpringBootApplication
@MapperScan(value = "com.example.demo.mapper")
public class DemoBootMybatisDataSecurityApplication {
    / / small ajie
    public static void main(String[] args){ SpringApplication.run(DemoBootMybatisDataSecurityApplication.class, args); }}Copy the code

Sample UserController

Write a test interface for user management, consisting of two get users by username and get all users.

@Api(description = "User Management")
@RequestMapping("user")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    / / small ajie
    @ApiOperation(value = "Get user by username")
    @RequestMapping(value = "getAllUser",method = RequestMethod.POST)
    public User getAllUser(@RequestBody UserDto userDto){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getNickName,userDto.getUserName());
        User user = userService.getOne(queryWrapper);
        return user;
    }

    // Public id: Java full stack architect
    @ApiOperation(value = "Get all users")
    @GetMapping(value = "getUserList")
    public List<User> getUserList(){
        List<User> user = userService.getUserList();
        returnuser; }}Copy the code

Start the project

When the project development is completed and the project is started, we need to set the specified parameters as our secret key information. Jar startup parameters can be set differently in different environments. In the development environment, idea can be set to Program arguments, and in the server, startup environment variables can be set. IDEA is set up in the development environment. If you edit the startup configuration

In the boot parameter setting area, set Program arguments to the specified secret key information. You need to replace the value of = with your own secret key information. Click Apply to launch the project.

--mpw.key=c0c7f05fb1a43687
Copy the code

test

After the project is started, access interface, two interfaces can query the specified information, good database configuration based on Mybatis-Plus security protection example is completed.

conclusion

Ok, the above is the Spring Boot database configuration and account information security protection example, thank you for reading, I hope you like, if it is helpful to you, welcome to like favorites. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.