The springboot project configuration file does not allow the solution of plaintext passwords (jasypt usage method)

I. Introduction

For security reasons, plaintext passwords are not allowed in java project configuration files;

In order to solve this problem, you can use jasyptthis jar package. This jar package can encrypt and decrypt strings. After importing into the project, just write the encrypted password in the configuration file. When the project starts, this jar package will encrypt and decrypt the password. Decryption does not affect the normal use of the project.

Plaintext passwords are also not allowed in the java class, and this jar package can also be used for encryption and decryption.

Two, the solution

1. In the springboot project, pom.xmlintroduce:

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

2. In the startup class Application.java, introduce:

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;

@EnableEncryptableProperties

3. You can write a ENC_Util.javatool class to encrypt and decrypt strings (it can be used to obtain encrypted strings and decrypt passwords in java classes, but not to decrypt passwords in configuration files), the content is as follows:


import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;


public class ENC_Util {

    private static final String SALT = "mysalt";

    /**
     * jasypt-1.9.3 加解密工具类( jasypt-spring-boot-starter 是 2.1.2 )
     */

        private static final String PBEWITHMD5ANDDES = "PBEWithMD5AndDES";
        private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";

    public static String encryptWithMD5(String plainText) {
        return encryptWithMD5(plainText,SALT);
    }

    public static String decryptWithMD5(String plainText) {
        //java项目里用的解密方法,解密时,需要把ENC()去掉才行
        if(plainText == null || plainText.length()<=5){
            return "";
        }else{
            //截取字符串,把ENC()去掉
            plainText = plainText.substring(4,plainText.length()-1);
        }
        return decryptWithMD5(plainText,SALT);
    }

        /**
         * Jasyp2.x 加密(PBEWithMD5AndDES)
         * @param		 plainText      待加密的原文
         * @param		 factor         加密秘钥
         * @return       java.lang.String
         */
        public static String encryptWithMD5(String plainText, String factor) {
            // 1. 创建加解密工具实例
            StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
            // 2. 加解密配置
            EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
            config.setAlgorithm(PBEWITHMD5ANDDES);
            config.setPassword(factor);
            encryptor.setConfig(config);
            // 3. 加密
            return encryptor.encrypt(plainText);
        }

        /**
         * Jaspy2.x 解密(PBEWithMD5AndDES)
         * @param		 encryptedText      待解密密文
         * @param		 factor             解密秘钥
         * @return       java.lang.String
         */
        public static String decryptWithMD5(String encryptedText, String factor) {
            // 1. 创建加解密工具实例
            StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
            // 2. 加解密配置
            EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
            config.setAlgorithm(PBEWITHMD5ANDDES);
            config.setPassword(factor);
            encryptor.setConfig(config);
            // 3. 解密
            return encryptor.decrypt(encryptedText);
        }

        /**
         * Jasyp3.x 加密(PBEWITHHMACSHA512ANDAES_256)
         * @param		 plainText  待加密的原文
         * @param		 factor     加密秘钥
         * @return       java.lang.String
         */
        public static String encryptWithSHA512(String plainText, String factor) {
            // 1. 创建加解密工具实例
            PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
            // 2. 加解密配置
            SimpleStringPBEConfig config = new SimpleStringPBEConfig();
            config.setPassword(factor);
            config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
            // 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
            config.setKeyObtentionIterations( "1000");
            config.setPoolSize("1");
            config.setProviderName("SunJCE");
            config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
            config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
            config.setStringOutputType("base64");
            encryptor.setConfig(config);
            // 3. 加密
            return encryptor.encrypt(plainText);
        }

        /**
         * Jaspy3.x 解密(PBEWITHHMACSHA512ANDAES_256)
         * @param		 encryptedText  待解密密文
         * @param		 factor         解密秘钥
         * @return       java.lang.String
         */
        public static String decryptWithSHA512(String encryptedText, String factor) {
            // 1. 创建加解密工具实例
            PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
            // 2. 加解密配置
            SimpleStringPBEConfig config = new SimpleStringPBEConfig();
            config.setPassword(factor);
            config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
            // 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
            config.setKeyObtentionIterations("1000");
            config.setPoolSize("1");
            config.setProviderName("SunJCE");
            config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
            config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
            config.setStringOutputType("base64");
            encryptor.setConfig(config);
            // 3. 解密
            return encryptor.decrypt(encryptedText);
        }

        public static void main(String[] args) {
            //待加密字符串
            String plainText = "123456";
            //这个每次跑的结果不一样
            String encryptWithMD5Str = encryptWithMD5(plainText, SALT);
            //虽然不一样,这个也能正常执行
            String decryptWithMD5Str = decryptWithMD5(encryptWithMD5Str, SALT);

            System.out.println("加密前:"+plainText);
            System.out.println("加密后:"+encryptWithMD5Str);
            System.out.println("解密后:"+decryptWithMD5Str);

            //String encryptWithSHA512Str = encryptWithSHA512(plainText, factor);
            //String decryptWithSHA512Str = decryptWithSHA512(encryptWithSHA512Str, factor);

            //System.out.println("采用SHA512加密前原文密文:" + encryptWithSHA512Str);
            //System.out.println("采用SHA512解密后密文原文:" + decryptWithSHA512Str);
        }

}

4. For example, the above password is 123456, the salt value is mysalt, and the result after encryption is dLJEFB7/7QJYan40UefGvQ==;
the result after each encryption is different, but the result after decryption is the same, both are123456

5. Modify the configuration file application.yml, first add jasyptthe configuration information:

jasypt:
  encryptor:
    algorithm: PBEWithMD5AndDES
    pool-size: 1
    salt-generator-classname: org.jasypt.salt.RandomSaltGenerator
    password: mysalt

Note that the password here is the salt value. If the security personnel are not allowed to write it here, it can be written in the startup command, for example:

jasypt:
  encryptor:
    algorithm: PBEWithMD5AndDES
    pool-size: 1
    salt-generator-classname: org.jasypt.salt.RandomSaltGenerator

Then add to the project startup command:

java -jar -Djasypt.encryptor.password=mysalt

6. Modify the configuration file application.yml, where the previous plaintext password is ENC(密文密码)replaced with, for example:

spring.datasource:
  url: jdbc:mysql://10.123.123.123:3306/mydbname?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
  username: root
  password: ENC(dLJEFB7/7QJYan40UefGvQ==)
  driver-class-name: com.mysql.cj.jdbc.Driver

After the project is started, the jar package will be dLJEFB7/7QJYan40UefGvQ==decrypted 123456and connected to the database correctly.

7. If there is a plaintext password in the java file, you can also replace it with a ciphertext password, and then use the above ENC_Util.javato decrypt it, for example:

    private static Connection getConnection() {
        Connection conn = null;
        try {
        
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://10.123.123.123:3306/mydbname?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
            String username = "root";
            
            //这里是util里截取字符串后才解密的,也可以不加ENC(),然后util里也不截取字符串
            String password = ENC_Util.decryptWithMD5("ENC(dLJEFB7/7QJYan40UefGvQ==)");
            //String password = ENC_Util.decryptWithMD5("dLJEFB7/7QJYan40UefGvQ==");
            
            Properties props = new Properties();
            props.setProperty("user", username);
            props.setProperty("password", password);
            conn = DriverManager.getConnection(url, props);
            
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return conn;
    }

おすすめ

転載: blog.csdn.net/BHSZZY/article/details/130155852