[JAVA] 如何给yml配置文件的密码加密(SpringBoot)

2541 0
黑夜隐士 2022-11-9 09:51:44 | 显示全部楼层 |阅读模式
目录

    1.低版本2.x
      1)引入jar包2)生成密码3)测下解密4)yml配置5)测测登录
    2.高版本 3.x
      1)引入jar包2)生成密码3)yml配置


最近在忙着解决规约扫描的问题,其一就是这个明文密码必须加密的问题,一般是数据库的配置。首先我用的是默认的PBEWithMD5AndDES默认的MD5加密方式,
弄好之后有要求使用AES_256/SM2/SM4等高级的算法加密,于是后来又升级了jar包使用默认的PBEWITHHMACSHA512ANDAES_256.
JDK版本-1.8

1.低版本2.x

先记录低版本的加密方式-----PBEWithMD5AndDES


1)引入jar包
  1. <dependency>
  2.             <groupId>com.github.ulisesbocchio</groupId>
  3.             <artifactId>jasypt-spring-boot-starter</artifactId>
  4.             <version>2.1.0</version>
  5.         </dependency>
复制代码
如上一个启动类,在联网的情况下就能自动下载其余加密需要的jar包。
如果是在内网的情况下,可以手动在项目的lib目录引入所需jar包,如下:
  1. <dependency>
  2.     <groupId>org.jasypt</groupId>
  3.     <artifactId>jasypt</artifactId>
  4.     <version>1.9.2</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>com.github.ulisesbocchio</groupId>
  8.     <artifactId>jasypt-spring-boot</artifactId>
  9.     <version>2.1.0</version>
  10. </dependency>
复制代码

2)生成密码
  1. @Test
  2.     public void testEncrypt() {
  3.         StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
  4.         EnvironmentPBEConfig config = new EnvironmentPBEConfig();
  5.         config.setAlgorithm("PBEWithMD5AndDES");          // 加密的算法,这个算法是默认的
  6.         config.setPassword("Angel");                        // 加密的密钥,随便自己填写,很重要千万不要告诉别人
  7.         standardPBEStringEncryptor.setConfig(config);
  8.         String plainText = "123456";         //自己的密码
  9.         String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
  10.         System.out.println(encryptedText);
  11.     }
复制代码
如图,数据库密码为123456,密钥为Angel,加密算法也如上;
运行如图:4o+eS8OaWQ7HcjVgrkoX0A==



3)测下解密
  1. @Test
  2.     public void testDe() {
  3.         StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
  4.         EnvironmentPBEConfig config = new EnvironmentPBEConfig();
  5.         config.setAlgorithm("PBEWithMD5AndDES");
  6.         config.setPassword("Angel");
  7.         standardPBEStringEncryptor.setConfig(config);
  8.         String encryptedText = "4o+eS8OaWQ7HcjVgrkoX0A==";   //加密后的密码
  9.         String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
  10.         System.out.println(plainText);
  11.     }
复制代码
运行如图:



4)yml配置

记好加密好的密码,在yml文件里将数据源那里用ENC套上,如下:
  1. spring:
  2. datasource:
  3.   username: root
  4.   password: ENC(4o+eS8OaWQ7HcjVgrkoX0A==)
  5.   url: jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  6.   driver-class-name: com.mysql.cj.jdbc.Driver
  7. jasypt:
  8. encryptor:
  9.   password: Angel
  10.   algorithm: PBEWithMD5AndDES
复制代码
5)测测登录

题外话,启动类上无需开启加密注解(@EnableEncryptableProperties)



2.高版本 3.x

1)引入jar包
  1. <dependency>
  2.             <groupId>com.github.ulisesbocchio</groupId>
  3.             <artifactId>jasypt-spring-boot-starter</artifactId>
  4.             <version>3.0.3</version>
  5.         </dependency>
复制代码
与前面 一致,没有外网的条件,引入如下jar包
  1. <!-- https://mvnrepository.com/artifact/org.jasypt/jasypt -->
  2. <dependency>
  3.     <groupId>org.jasypt</groupId>
  4.     <artifactId>jasypt</artifactId>
  5.     <version>1.9.3</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot -->
  8. <dependency>
  9.     <groupId>com.github.ulisesbocchio</groupId>
  10.     <artifactId>jasypt-spring-boot</artifactId>
  11.     <version>3.0.3</version>
  12. </dependency>
复制代码
2)生成密码

这里用的是一个工具类,CV大法。
  1. package com.example.demo.utils;
  2. /**
  3. * @author 杨帅帅
  4. * @time 2021/12/5 - 1:00
  5. */
  6. import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
  7. import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
  8. public class JasypUtil {
  9.     private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";
  10.     /**
  11.      * @Description: Jasyp 加密(PBEWITHHMACSHA512ANDAES_256)
  12.      * @Author:      Rambo
  13.      * @CreateDate:  2020/7/25 14:34
  14.      * @UpdateUser:  Rambo
  15.      * @UpdateDate:  2020/7/25 14:34
  16.      * @param                 plainText  待加密的原文
  17.      * @param                 factor     加密秘钥
  18.      * @return       java.lang.String
  19.      * @Version:     1.0.0
  20.      */
  21.     public static String encryptWithSHA512(String plainText, String factor) {
  22.         // 1. 创建加解密工具实例
  23.         PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  24.         // 2. 加解密配置
  25.         SimpleStringPBEConfig config = new SimpleStringPBEConfig();
  26.         config.setPassword(factor);
  27.         config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
  28.         // 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
  29.         config.setKeyObtentionIterations( "1000");
  30.         config.setPoolSize("1");
  31.         config.setProviderName("SunJCE");
  32.         config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
  33.         config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
  34.         config.setStringOutputType("base64");
  35.         encryptor.setConfig(config);
  36.         // 3. 加密
  37.         return encryptor.encrypt(plainText);
  38.     }
  39.     /**
  40.      * @Description: Jaspy解密(PBEWITHHMACSHA512ANDAES_256)
  41.      * @Author:      Rambo
  42.      * @CreateDate:  2020/7/25 14:40
  43.      * @UpdateUser:  Rambo
  44.      * @UpdateDate:  2020/7/25 14:40
  45.      * @param                 encryptedText  待解密密文
  46.      * @param                 factor         解密秘钥
  47.      * @return       java.lang.String
  48.      * @Version:     1.0.0
  49.      */
  50.     public static String decryptWithSHA512(String encryptedText, String factor) {
  51.         // 1. 创建加解密工具实例
  52.         PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  53.         // 2. 加解密配置
  54.         SimpleStringPBEConfig config = new SimpleStringPBEConfig();
  55.         config.setPassword(factor);
  56.         config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
  57.         // 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
  58.         config.setKeyObtentionIterations( "1000");
  59.         config.setPoolSize("1");
  60.         config.setProviderName("SunJCE");
  61.         config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
  62.         config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
  63.         config.setStringOutputType("base64");
  64.         encryptor.setConfig(config);
  65.         // 3. 解密
  66.         return encryptor.decrypt(encryptedText);
  67.     }
  68.     public static void main(String[] args) {
  69.         String factor = "Angel";
  70.         String plainText = "123456";
  71.         String encryptWithSHA512Str = encryptWithSHA512(plainText, factor);
  72.         String decryptWithSHA512Str = decryptWithSHA512(encryptWithSHA512Str, factor);
  73.         System.out.println("采用AES256加密前原文密文:" + encryptWithSHA512Str);
  74.         System.out.println("采用AES256解密后密文原文:" + decryptWithSHA512Str);
  75.     }
  76. }
复制代码
执行这个main方法,来,见证奇迹的时刻


Exception in thread "main" org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine
    at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.handleInvalidKeyException(StandardPBEByteEncryptor.java:1207)
    at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.encrypt(StandardPBEByteEncryptor.java:996)
    at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:655)
    at org.jasypt.encryption.pbe.PooledPBEStringEncryptor.encrypt(PooledPBEStringEncryptor.java:465)
    at com.example.demo.utils.JasypUtil.encryptWithSHA512(JasypUtil.java:41)
    at com.example.demo.utils.JasypUtil.main(JasypUtil.java:78)
这个错,很有意思,在加密的时候,手动配置了JCE的方法来支持加密的程序,然而jasypt3.x版本的对于jdk8自带的jce的包不兼容,需要升级一下,所以到网上下载jdk8对应的JCE包jce_policy-8。
下载后解压有两个jar包,如图:


到该目录下替换即可:C:\Program Files\Java\jdk1.8.0_25\jre\lib\security


然后运行main方法:8jLUdq0Fr7UhJGNwK/Nc6i6/WV4+UBpvtfBLDh4e3jZMJZAhPqfZdGlpFEUk24UZ


成功。

3)yml配置
  1. spring:
  2. datasource:
  3.   username: root
  4.   password: ENC(8jLUdq0Fr7UhJGNwK/Nc6i6/WV4+UBpvtfBLDh4e3jZMJZAhPqfZdGlpFEUk24UZ)
  5.   url: jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  6.   driver-class-name: com.mysql.cj.jdbc.Driver
  7. jasypt:
  8. encryptor:
  9.   password: Angel
  10.   algorithm: PBEWITHHMACSHA512ANDAES_256
复制代码


改个登录密码:


很顺利,不妨再来验证加密算法,如图我如果改为
  1. jasypt:
  2. encryptor:
  3.   password: Angel
  4.   algorithm: PBEWithMD5AndDES
复制代码
运行项目则报错,图略。
yml文件里面需要配置密钥以及算法,才能正确解密访问数据库,那你看这个Angel密钥是用password来修饰的,是否会被外行的人认作密码呢?
答案是肯定的,所以呀需要使用写小手段,把密钥也写成ENC()这种格式的就OK了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行