在我们的服务中不可避免的需要使用到一些密码(数据库、redis等)
开发和测试环境还好,但生产环境如果采用明文配置讲会有安全问题,jasypt是一个通用的加解密库,我们可以使用它。
1. 修改maven配置文件pom.xml
加入依赖
1 2 3 4 5 6
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
|
2. 在配置文件中对盐进行配置
1 2 3 4
| jasypt: encryptor: password: thisissalt
|
3. 创建工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
public class JasyptUtils {
public static void main(String[] args) { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); config.setPassword("thisissalt"); encryptor.setConfig(config);
encrypt(encryptor, "root****1234"); decrypt(encryptor, "CDwEmbi*******Zz39Lg="); }
public static void encrypt(StandardPBEStringEncryptor encryptor, String plaintext){ String ciphertext=encryptor.encrypt(plaintext); System.out.println("加密结果: " + ciphertext); }
public static void decrypt(StandardPBEStringEncryptor encryptor, String ciphertext){ String plaintext=encryptor.decrypt(ciphertext); System.out.println("解密结果: " + plaintext); } }
|
4. 修改配置文件中的密码
此时就可以把在上一步中生成的密码在配置文件中进行配置了,配置成ENC(CDwEmbi*******Zz39Lg=)
,如下,是对数据库密码进行加密的配置:
1 2 3 4 5 6 7
| spring: datasource: name: saas_**** url: jdbc:mysql://127.0.0.1:3306/saas_****?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true username: **** password: ENC(CDwEmbi*******Zz39Lg=) driver-class-name: com.mysql.cj.jdbc.Driver
|