SpringBoot+ENC implements key encryption and usage principles

😊 @ Author: It’s a flash in the past

💖 @Homepage: https://blog.csdn.net/zhuocailing3390

🎊 @ Community: Java Technology Stack Exchange

🎉 @ Topic: SpringBoot+ENC implements key encryption and usage principles

⏱️ @ Creation time: June 23, 2024

Insert image description here

Table of contents

  • Preface
    1. Integrate SpringBoot
    • 1.1、POM
  • 1.2. Encryption salt value configuration
  • 1.3. Use of tools
  • 1.4. Encryption configuration and use
  • 1.5. Testing
    1. ENC loading principle

Preface

ENC (Environment-Neutral Configuration) is used in Spring Boot mainly to separate configuration information from application code to improve security and maintainability. The main advantages of ENC include:

  1. Security enhancement: Sensitive information (such as database passwords, API keys, etc.) should not be hard-coded in the code, but should be stored in the configuration file in an encrypted manner, and then decrypted and used through ENC , thereby reducing the risk of leakage.
  2. Maintainability: Separate configuration information from code so that configurations can be modified and managed independently without the need to recompile and deploy applications. This reduces maintenance costs and makes the application easier to manage.
  3. Flexibility: Using ENC can provide different configurations according to different environments (development, testing, production, etc.) without modifying the application code, thus improving the flexibility and portability of deployment.

1. Integrate SpringBoot

1.1、POM

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

1.2. Encryption salt value configuration

When integrating SpringBoot, the configuration of salt value&#39; is best written in the file ofConfiguration Center, and thesalt value' is written to a local file, which can be easily decrypted after being leaked.

jasypt:
  encryptor:
    # passwordAny value,Best random characters
    password: hhX4FzbwcT 

1.3. Use of tools

Use tool classes to encrypt the plaintext data that needs to be processed, and then write the encryption results into the configuration file.

Note: After using the tool class, you should delete the encryption salt

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class JasyptTest {

    /**
     * Crypto salt,Delete after use,or cannot be submitted to`Production Environment`,for example:
     */
    private final static String PASSWORD = "hhX4FzbwcT";

    public static void main(String[] args) {

        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();

        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        // Used to set encryption keys。A key is the key information used to encrypt and decrypt a string。
        config.setPassword(PASSWORD);
        // Encryption algorithm name,jasypt-3.0.5Default encryption method after version
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        // Used to set the number of iterations during encryption,Increasing the number of iterations can make password cracking more difficult for attackers。
        config.setKeyObtentionIterations("1000");
        // Encryptor pool size。A pool is a group of encryptor instances,Ensures concurrency of cryptographic operations。
        config.setPoolSize("1");
        // for settingJCE(Java Cryptography Extension)provider name。
        config.setProviderName("SunJCE");
        // Class name used to set the generated salt。In this configuration,we usedorg.jasypt.salt.RandomSaltGenerator,Indicates using a randomly generated salt。
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        // for settingJasyptinitialization vector to use(IV)generator class name。The initialization vector is a fixed-length random number used in the encryption process,Used to encrypt data blocks,Make the encryption result of each data block unique。In this configuration,we usedorg.jasypt.iv.RandomIvGeneratorkind,This class is a random generator,Used to generate real-time randomIVExample of。This ensures that each encryptedIVare all unique,thereby increasing encryption strength。
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        // Specify encrypted output type。In this configuration,we chosebase64Output type。
        config.setStringOutputType("base64");
        encryptor.setConfig(config);

        // plain text1
        String name_encrypt = "root";
        // plain text2
        String password_encrypt = "123456";

        // plaintext encryption
        String encrypt1 = encryptor.encrypt(name_encrypt);
        String encrypt2 = encryptor.encrypt(password_encrypt);
        System.out.println("plaintext encryption1:" + encrypt1);
        System.out.println("plaintext encryption2:" + encrypt2);

        // Cipher text decryption
        String decrypt1 = encryptor.decrypt(encrypt1);
        String decrypt2 = encryptor.decrypt(encrypt2);
        System.out.println("Cipher text decryption1:" + decrypt1);
        System.out.println("Cipher text decryption2:" + decrypt2);
    }
} 

Insert image description here

1.4. Encryption configuration and use

YAML:

sys:
 name: ENC(Yt36hceu3xGXEzrz2jCPjvalaXQ5yIHE04SVT6lIkcktrxqtBZrlivkAkA9/9oZ2)
 password: ENC(0Ci6irPOko9IG+hBZJAGoguIuE52gF/XiigCV4DwLm6NfkoyvV4Etgc9FzKK3MYl) 

1.5. Testing

The project starts successfully, the ciphertext text is set in Yaml, and the Controller prints the plaintext information normally, it means that the ENC configuration is successful.

@RestController
public class TestController {

    @Value("{sys.name}")
    private String name;

    @Value("{sys.password}")
    private String password;

    @GetMapping("/test")
    public void test() {
        System.out.println("name = " + name);
        System.out.println("password = " + password);
    }
} 

2. ENC loading principle

  1. In the automatic configuration class JasyptSpringBootAutoConfiguration of the jasypt-spring-boot-starter package, the EnableEncryptablePropertiesConfiguration configuration class is introduced through the @Import annotation. The environment parameter in this class stores yaml file metadata;

  2. In the postProcessBeanFactory method, call the environment.getPropertySources() method to obtain the yaml configuration item;
    Insert image description here

  3. Use convertPropertySources to perform data conversion and modify the configuration item value in yaml. The specific implementation is to call the instantiatePropertySource() method. In this method, match propertySource instanceof MapPropertySource and convert it into an EncryptableMapPropertySourceWrapper object;

Insert image description here
Insert image description here
Insert image description here
Insert image description here
Insert image description here

  1. In the EncryptableMapPropertySourceWapper class, match through the getProperty(name) method. After successful matching, call resolver.resolvePropertyValue to decrypt the ENC configuration and replace the original propertySource value;

Insert image description here

Insert image description here