解决springboot yml文件明文显示密码的问题 Published on Oct 15, 2022 in 随笔 with 0 comment Java springboot yml 加密 1.pom添加 加密依赖 ```yaml com.github.ulisesbocchio jasypt-spring-boot-starter 3.0.4 ``` 2.编写工具类 ``` package com.jeesite.modules.utils; import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * 配置文件加解密工具类 * https://blog.csdn.net/qq_41617261/article/details/121448939 */ @Component public class JasyptUtil { private static String password; @Value("${jasypt.encryptor.password}") public static void setPassword(String password) { JasyptUtil.password = password; } private static final String PBEWITHMD5ANDDES = "PBEWithMD5AndDES"; private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256"; public static void main(String[] args) { JasyptUtil.password = "+oE67TSCE/j7=="; // 加密 String username = encyptPwd("123"); String password = encyptPwd("678"); System.out.println(username); System.out.println(password); } /** * 加密方法 * * @param value 需要加密的值 */ public static String encyptPwd(String value) { // 1. 创建加解密工具实例 PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); // 2. 加解密配置 SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(password); config.setAlgorithm(PBEWITHMD5ANDDES); // 3. 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置 config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName("SunJCE"); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); encryptor.setConfig(config); String result = encryptor.encrypt(value); return result; } /** * 解密方法 * * @param value 需要解密的值 */ public static String decryptPwd(String value) { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(password); config.setAlgorithm(PBEWITHMD5ANDDES); config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName("SunJCE"); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); encryptor.setConfig(config); String result = encryptor.decrypt(value); return result; } } ``` 3.yml文件添加必要内容 ``` #数据库密码加密 jasypt: encryptor: #加密盐 password: +oE67TSCE/j7+ algorithm: PBEWithMD5AndDES iv-generator-classname: org.jasypt.iv.NoIvGenerator ``` 因为3.x的版本里面的加密方式默认是别的所以yml文件需要指定一下 4. ``` jdbc: # Mysql 数据库配置 type: mysql driver: com.mysql.jdbc.Driver username: ENC(Y1dsy3NNUuDHERMyfT8jJRMNeBdg3l8U) password: ENC(SDQcQ+7C6/6H1eO4AoTwLmrmOWc4uOhfI0MG/llr1KA=) ``` 先用工具类把明文加密然后在填进去 密文用ENC(密文字符串) 这种类型填入 本文由 admin 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。