SpringBoot configuration file database password encryption

Article directory

foreword

In our daily development, we may easily expose the database password directly in the configuration file in plain text. This can be done in the development environment, but it is not recommended to do so in the production environment. After all, security is no small matter, and no one knows where The day password was inexplicably leaked. Let’s talk about how to encrypt database passwords in the springboot project today

practice

Introduce maven dependency

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

Configure the secret key in the Springboot configuration file

jasypt:
  encryptor:
    password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ7 

It is not safe to write the secret key in the configuration file during testing.
In the IDE tool, we can put the secret key in the startup parameters.
insert image description here

jasypt.encryptor.password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7

Just add parameters when starting the project in the production environment

java -jar  -Djasypt.encryptor.password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7 xxx.jar

generate ciphertext

Build a test class to generate the encrypted ciphertext of the password

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemo {
    
    
    @Autowired
    StringEncryptor stringEncryptor;//密码解码器自动注入

    @Test
    public void test() {
    
    
        String name = encryptor.encrypt("root");
        String password = encryptor.encrypt("123!@#");
        System.out.println(name);//n3UKAujtutC8u9qJaSm1uA==
        System.out.println(password );//bfc7g2lOcAP79kVGo9MmGA==
    }
}

It is also possible to generate input locally through the Java command as the content to be encrypted and password as the secret key

java -cp  E:\repository\org\jasypt\jasypt\2.1.0\jasypt-2.1.0.jar
org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI
input="root" 
password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7

Use in the configuration file
to change the plaintext password in the configuration file to an encrypted password, and wrap an ENC() outside

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/user?serverTimezone=UTC
    username: ENC(n3UKAujtutC8u9qJaSm1uA==)
    password: ENC(bfc7g2lOcAP79kVGo9MmGA==)

Guess you like

Origin blog.csdn.net/qq_29917503/article/details/131665750