使用jasypt对springboot的datasource密码等敏感信息加密-安全

1.pom.xml需要添加依赖

		
			com.github.ulisesbocchio
			jasypt-spring-boot-starter
			1.14
		
		
			org.jasypt
			jasypt
			1.9.2
		

版本可以自己定
2.配置加密参数
application.yml的文件下

jasypt:
  encryptor:
    password: cptbtptp
    #chiputaobutuputaopi

3.加密密码

public class JasyptUtils {

    /**
     * Jasypt生成加密结果
     *
     * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待加密值
     * @return
     */
    public static String encryptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        String result = encryptOr.encrypt(value);
        return result;
    }

    /**
     * 解密
     *
     * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待解密密文
     * @return
     */
    public static String decyptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        String result = encryptOr.decrypt(value);
        return result;
    }

    public static SimpleStringPBEConfig cryptOr(String password) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        return config;
    }

    public static void main(String[] args) {
        // 加密
        System.out.println(encryptPwd("panther", "root"));
        // 解密
        System.out.println(decyptPwd("panther", "yRZy44Zv44U6bbFEI1+1Lg=="));
    }

}

4.写入配置文件里

spring:
    #mysql配置    
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://125.1.21.20:5506/user?characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true
    username: ENC(yRZ44U6bbFE+1Lg==)
    password: ENC(MK4HwLN8lOxnvw==)
    driver-class-name: com.mysql.jdbc.Driver

5.启动工程,若成功启动则OK,不成功,检查用户名,密码是否正确。

转载于https://blog.csdn.net/harris135/article/details/76653172

你可能感兴趣的:(学习)