SpringBoot configuration file encryption

Most of the projects need to use the configuration file. The configuration file is configured with some necessary information, such as database connection information and cache information, and these information are written in the configuration file in plain text, which is quite dangerous. Next, I will introduce a solution. By encrypting the configuration information and putting it in the configuration file, the risk is greatly reduced.

Not much to say, just go straight to the case, the code is more useful than anything else.

1. Import dependencies

<!--jasypt加密依赖-->
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

2. Create a test class and start encryption

@Test
public void testEnc() {
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    encryptor.setPassword("123456");
    String CloudCoder = encryptor.encrypt("CloudCoder");
    System.out.println("CloudCoder = " + CloudCoder);
}

Encrypted ciphertext string:

oKIdQ2pqK0mat7j/UnWNL+gNtJqWmsNG

3. Replace the original configuration information

# ENC()标识加密串
my.config-username=CloudCoder
    替换成
my.config-username=ENC(oKIdQ2pqK0mat7j/UnWNL+gNtJqWmsNG)

4. Encryption key

As for the encryption key, it is generally configured in the virtual machine parameters, and it can also be configured in the startup parameters if the jar package is started. As some bloggers said, write it in the configuration file, and I strongly don’t recommend it. The configuration information is originally encrypted. Isn’t the encryption of the secret key written in the configuration file equal to deception? This is not recommended. So dry, using my method below is enough.

dev:

picture

Virtual machine parameters

prod:

nohup java -Djasypt.encryptor.password=123456 -jar xxx.jar &

epilogue

视野决定上限,能力决定下限,努力决定空间, Does it feel very simple, yes, it is that easy, because the jar package is packaged by the predecessors, you only need to use it, it is still very convenient.

Guess you like

Origin blog.csdn.net/active_pig/article/details/121238034