Introducing the jasypt

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
Copy the code

Generate the string to encrypt

Encrypt the user name and password of the database

    public static void main(String[] args) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        // Encrypt the required salt(salt)
        textEncryptor.setPassword("G0CvDz7oJn6");
        // The data to be encrypted (database username or password)
        String username = textEncryptor.encrypt("root");
        String password = textEncryptor.encrypt("root123");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
    }
Copy the code

The output information is as follows:

username:i8QgEN4uOy2E1rHzrpSTYA==
password:6eaMh/RX5oXUVca9ignvtg==
Copy the code

Or use Maven to encrypt \ maven.org \jasypt\jasypt\ 1.9.2jasypt-1.9.2.jar

Java - cp jasypt - 1.9.2. Jar org. Jasypt. Intf. Cli. JasyptPBEStringEncryptionCLI password = G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=rootCopy the code

The output information is as follows:

----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11

----ARGUMENTS-------------------
input: root
algorithm: PBEWithMD5AndDES
password: G0CvDz7oJn6

----OUTPUT----------------------
Gvkoz+sbFWiRe3ECtizV1A==
Copy the code

Copy the result of -output –

Configure the Properties file

Configure the generated encryption string **ENC(encryption string)** to application.properties

# Salt required for encryption (salt)
jasypt.encryptor.password=G0CvDz7oJn6
The default encryption mode is PBEWithMD5AndDES, which can be changed to PBEWithMD5AndTripleDES
# jasypt.encryptor.algorithm=PBEWithMD5AndDES
spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==)
spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)
Copy the code

The corresponding classes for encryption are BasicTextEncryptor and StrongTextEncryptor

public BasicTextEncryptor() {
    super();
    this.encryptor = new StandardPBEStringEncryptor();
    this.encryptor.setAlgorithm("PBEWithMD5AndDES");
}

public StrongTextEncryptor() {
    super();
    this.encryptor = new StandardPBEStringEncryptor();
    this.encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
}
Copy the code

Configure the salt value at deployment time

To prevent salt from leaking, reverse solve the password. The salt(salt) value can be passed in using the command at project deployment time

java -jar -Djasypt.encryptor.password=G0CvDz7oJn6 xxx.jar
Copy the code

Or configure it in the server’s environment variables to further improve security

Open the /etc/profile file vim /etc/profile. Insert export JASYPT_PASSWORD = G0CvDz7oJn6 at the end of the /etc/profile file. Compile source /etc/profile -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jarCopy the code

Official address: github.com/ulisesbocch…