2021.2.24 update

1 overview

Jasypt is an encryption library. There is a Spring Boot library on Github that integrates Jasypt, called jasypt-spring-boot. This article demonstrates how to use jasypt-spring-boot to encrypt configuration files.

2 rely on

First add dependencies:

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

Gradle:

implementation("Com. Making. Ulisesbocchio: jasypt - spring - the boot - starter: 3.0.3." ")
Copy the code

3 Simple Encryption

Simple encryption is to write the encrypted password in plain text in the configuration file. The procedure is as follows:

  • Configuration file Configures the encryption password
  • Obtain ciphertext
  • Replace clear

3.1 Encryption Password

Add the following parameters to the configuration file:

jasypt:
  encryptor:
    password: test
Copy the code

Test is the encrypted password.

3.2 Obtaining ciphertext

For example, the configuration file needs to be encrypted as follows:

test: value
Copy the code

Inject the StringEncryptor in the test class and use the encrypt in it to encrypt the Value obtained via @Value:

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private StringEncryptor encryptor;

    @Value("${test}")
    private String value;

    @Test
    void contextLoads(a) { System.out.println(encryptor.encrypt(value)); }}Copy the code

Click the small green triangle next to it to run, and the output is as follows:

This is the corresponding ciphertext.

3.3 Replacing plaintext

To replace plain text with the prefix ENC(and suffix) :

test: ENC(IlEvyvcULhZJrHLDtPun2ut433RvAdpaNJ9IZt9uNUk3hDSKQsdOXLEkWyiK6QR3)
Copy the code

This completes the encryption of the property test.

3.4 test

Values obtained directly through @value are plaintext:

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private StringEncryptor encryptor;

    @Value("${test}")
    private String value;

    @Test
    void contextLoads(a) {
        System.out.println(encryptor.encrypt(value));
    }

    @Test
    void decrypt(a)
    { System.out.println(value); }}Copy the code

Run decrypt directly to output the plaintext.

4 Customize encryption

4.1 Customizing Encryption Classes

The default encryption algorithm is THE PBE algorithm. You can customize an encryption class if the algorithm does not meet the requirements.

To implement the StringEncrypto interface, write the Bean name in the configuration file:

@Component
public class Encryptor implements StringEncryptor{

    @Override
    public String encrypt(String s) {
        return s+"111";
    }

    @Override
    public String decrypt(String s) {
        return s.substring(0,s.indexOf("111")); }}Copy the code

The encryption here is very simple, just add 111 to the end of the plaintext, decryption to remove 111. Also write the Bean name on the configuration file:

jasypt:
  encryptor:
# password: test
    bean: encryptor
Copy the code

You can also comment out the password, since password encryption is no longer required.

Testing:

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private StringEncryptor encryptor;

    @Value("${test}")
    private String value;

    @Test
    void contextLoads(a) {
        System.out.println(encryptor.encrypt(value));
    }

    @Test
    void decrypt(a)
    { System.out.println(encryptor.decrypt(value)); }}Copy the code

4.2 Asymmetric Encryption

Hutool is used to generate public and private keys. The dependencies are as follows:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-crypto</artifactId>
    <version>5.4.3</version>
</dependency>

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.66</version>
</dependency>
Copy the code

Gradle:

implementation("Cn. Hutool: hutool - crypto: 5.4.3." ")
implementation("Org. Bouncycastle: bcprov - jdk15on: 1.66")
Copy the code

Generate public and private keys:

KeyPair pair = SecureUtil.generateKeyPair("RSA");
System.out.println(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
System.out.println(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
Copy the code

After generating, add to jasypt.encryptor.public-key-string with jasypt.encryptor.private-key-string:

jasypt:
  encryptor:
# password: test
# bean: encryptor
    public-key-string: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZV5U0+Ck4AEpawUoiHOkG4ZNC6EeEvFZVCcyaIM0MiusGMM6ye9ZT6Ok756/vQsJbsYDGDtIDX82TsmYb ZkN7QPuclABSL5SmaDYdJM/MeYKfMwrDb0lWARqF5ql9Rgol7Agq4ef8yQEbSmUDW/LQe+xXtCTer5MoJViUHV56MwIDAQAB
    private-key-string: MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJlXlTT4KTgASlrBSiIc6Qbhk0LoR4S8VlUJzJogzQyK6wYwzrJ71lPo6Tvnr+9CwluxgMYO 0gNfzZOyZhtmQ3tA+5yUAFIvlKZoNh0kz8x5gp8zCsNvSVYBGoXmqX1GCiXsCCrh5/zJARtKZQNb8tB77Fe0JN6vkyglWJQdXnozAgMBAAECgYA8syFCrwtt +ht00ne8ijIqQagP/6+z2PPZxL/DsUFJ+kGvmSlxGLlOTO/qgTuxG/2g22JsxFgY8tcHZMKrjO8f4TLKPsaFgX1OwNhJO4SoMlfUUAR9HSMv49vx5mOvh2QU rC5+4rIQI1Rm8zbKyAqCjHIKr8hA6bIKEHO2qXK05QJBANhAA+djwrr3orIIBTRp+H6/JChH76XtoQfcQyT+CrEu/4tHVkbO2cEqcdKDScswHyTPu5UaSU2H FW/0Lj8Kg40CQQC1h1YMysd51djCf/Ud7L2sSIduy3DUSLc6XRX1IWAqxO+8gkvknDW7QztNES9YqwYEkLNLAjp1v8Gq+o2JQKS/AkAENCpfQycz70BwaYuA W1cDT7/qMIvOE/J/bp63h2C51QoOsRJSSg8dnC+eQgMbOhJA6vDgkyQ9p5SZGowTmaa5AkEAneQAIZJC3KL3LX20ivm+pFpVijXjhpFU5avPjG4iQjEXQISo VEjWp3G747V91Aa1bkUZ3bUref13Cytw7h/O6wJBAJHNIHKKTAkmslguJU5hll1HqrzyI9lcB5XqcgvdsxijUkZ95FThk6hNQuNV0sO/itUijQsJAtNdDITK mdcPMWg=
Copy the code

Then you can get ciphertext like encryption and replace plain text.

5 Non-plaintext password

For jasypt. The encryptor. Password, you can use the plaintext password, the password of transmission way has three:

  • Pass by command line arguments
  • Pass by applying environment variables
  • Pass through system environment variables

5.1 Transferring Parameters through the CLI

First write the password in plain text to get the ciphertext:

jasypt:
  encryptor:
    password: test
test: value
Copy the code

After replacing plain text with prefix and suffix, the encrypted password is removed:

#jasypt:
# encryptor:
# password: test

test: ENC(quCu1b+Z7SPHmgVsmbkeyNZmNe1LJw+SxjmwwLjNaWoH/ce3r6iHGvaMN5eQcu0P)
Copy the code

Add to the parameter class of the test class

--jasypt.encryptor.password=test
Copy the code

Since the command line parameters of the test class cannot be added, they can be added to the startup class:

This is going to skip the demo.

For Gradle, tests need to be in the build. Gradle/build Gradle. KTS add parameters:

tasks.withType<Test> {
    useJUnitPlatform()
    jvmArgs("-Djasypt.encryptor.password=test")
    / / can't be jvmArgs (" -- jasypt. The encryptor. Password = test ")
}
Copy the code

5.2 Transfer by Application environment Variables

Same as the first method, the first method is set in Program Arguments, which is set in VM Options:

-Djasypt.encryptor.password=test
Copy the code

5.3 Transferring system environment Variables

Passed through the system environment variable ways jasypt. The encryptor. Password, you need to specify which environment variables are:

jasypt:
  encryptor:
    password: ${ENCRYPT}
Copy the code

For example, the ENCRYPT environment variable is specified. After setting the environment variable, you can ENCRYPT and decrypt it directly.

6 Deployment precautions

6.1 packaging

Because in the configuration file is missing jasypt. The encryptor. Password, so use Maven error when packaging:

Add parameters to the Maven packaging configuration:

Gradle packaging does not require additional parameters.

6.2 the deployment

These days it is usually deployed directly through the JAR, that is, through

java -jar demo.jar
Copy the code

Deploy, then add the corresponding parameters as required, such as:

java -jar demo.jar --jasypt.encryptor.password=test
java -Djasypt.encryptor.password=test -jar demo.jar
Copy the code

If the password is obtained using system variables, ensure that the corresponding environment variables exist.

In addition, if Docker is deployed, please add corresponding parameters to ENTRYPOINT, such as:

ENTRYPOINT ["java"."-Djasypt.encryptor.password=test"."-jar"."demo.jar"]
ENTRYPOINT ["java"."-jar"."demo.jar"."--jasypt.encryptor.password=test",]
Copy the code

Get from system environment variables with ENV:

ENV ENCRYPT="test"
Copy the code

7 Reference Source code

Java version:

  • Github
  • Yards cloud
  • CODECHINA

Kotlin version:

  • Github
  • Yards cloud
  • CODECHINA