Microservice nacos or yml configuration content is partially encrypted with jasypt

Written at the top: Because the business needs to encrypt part of the passwords in the nacos configuration and cannot be exposed to the outside world, I wanted to use the official nacos plug-in, nacos-aes-encryption-pluginbut it is more complicated and the official documentation is not clear, so it is abandoned. If you are interested You can refer to it. Link: https://nacos.io/zh-cn/docs/v2/plugin/config-encryption-plugin.html . Then use the second method: jasypt, the following is the specific usage.

1.Introduce dependencies (custom version):

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

2. New configuration in yml:

jasypt:
  encryptor:
    password: U3buwRJdQ2023(随便取)
    algorithm: PBEWithMD5AndDES(固定值)
        //配置格式(不写默认ENC)
    property:
      prefix: "P["
      suffix: "]"

Note: algorithm is an encryption algorithm. The official default encryption algorithm is PBEWITHHMACSHA512ANDAES_256, but if you are using JDK1.8, you can’t use this algorithm. It is only supported after JDK9, so you can change this algorithm to PBEWithMD5AndDES.
The default encryption method of version 2.1.2 is: PBEWithMD5AndDES The
default encryption method of version 3.0.3 is: PBEWITHHMACSHA512ANDAES_256
When the 3.0.3 dependency is introduced, but the relevant jasypt encryption and decryption configuration is not added, and the ciphertext is encrypted by [PBEWithMD5AndDES], an error will be reported when starting.
Need to switch to [PBEWITHHMACSHA512ANDAES_256] mode.

3. Generate encrypted ciphertext:


/**
     * jasypt.encryptor.password 对应 配置中心 application-dev.yml 中的密码
     */
    @Test
    public void testEnvironmentProperties() {
    
    
        System.setProperty(JASYPT_ENCRYPTOR_PASSWORD, "xxx");
        StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());

        //加密方法
        System.out.println(stringEncryptor.encrypt("123456"));
        //解密方法
        System.out.println(stringEncryptor.decrypt("saRv7ZnXsNAfsl3AL9OpCQ=="));
    }

4. Modify nacos or yml configuration to ciphertext (must be in ENC (ciphertext) format, if you want to change the prefix, you need to configure it)

spring:
  datasource:
    password: ENC(密文)

Guess you like

Origin blog.csdn.net/m0_49605579/article/details/132584862