SpringBoot configuration file database account password encryption

For security reasons, the plaintext database account password has security risks and needs to be encrypted

Here, jasypt is used for processing

  1. Introduce jasypt dependency

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
  1. Add password information to the configuration file

jasypt:
    encryptor:
        password: silen
  1. Write the test code and get the encrypted result

import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JasyptApplicationTests {
    @Autowired
    private StringEncryptor encryptor;

    @Test
    public void testEncrypt() {
        System.out.println(encryptor.encrypt("root")); // iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A
        System.out.println("解密:"+encryptor.decrypt("iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A"));
    }
}
  1. Fill in the corresponding data into the configuration file

username: ENC(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
password: ENC(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
  1. Do not want to use the default ENC(), you can customize the settings, add code to the configuration file

jasypt:
    encryptor:
        password: silen
        property:
            prefix: silen(
            suffix: )

#对应加密位置则为
username: silen(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
password: silen(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
  1. Putting the password in the configuration file still has the risk of being cracked. You can consider adding this parameter when executing the jar file. The execution command is as follows

 java -jar admin.jar --jasypt.encryptor.password=silen
  1. If an error message appears when executing the test code of 3

org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction

solution:

After going to the official website to download two security-related packages, the problem was solved.

Download address: https://www.oracle.com/java/technologies/javase-jce8-downloads.html

After downloading, place it under the JAVA_HOME\jdk1.8.0_72\jre\lib\security directory, and re-run the encryption and decryption code to solve the problem.

Guess you like

Origin blog.csdn.net/qq_38387996/article/details/128663288