1. 需求讲解
对配置文件的组件密码加密,比如数据库redis等密码加密
2. 开发
2.1 依赖引入
<!-- jasypt 加解密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
2.2 加密解密代码
package com.imooc.test;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class JasyptTest {
@Test
public void testPwdEncrypt() {
// 实例化加密器
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
// 配置加密算法和秘钥
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setPassword("fengjianyingyue"); // 用于加密的秘钥(盐),可以是随机字符串,或者固定,一定要存储好,不要被其他人知道
config.setAlgorithm("PBEWithMD5AndDES"); // 设置加密算法,默认
encryptor.setConfig(config);
// 对密码进行加密
String myPwd = "imooc";
String encryptedPwd = encryptor.encrypt(myPwd);
System.out.println("++++++++++++++++++++++++++++++");
System.out.println("+ 原密码为:" + myPwd);
System.out.println("+ 加密后的密码为:" + encryptedPwd);
System.out.println("++++++++++++++++++++++++++++++");
}
}
2.3 配置文件配置jasypt属性
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES
password: fengjianyingyue
2.4 加密密码
在ENC()里面写加密后的密码即可,开箱即用
rabbitmq:
host: 121.43.139.228
port: 5672
virtual-host: /
username: imooc
password: ENC(UnoiHtPp84zMjjwLoJe/Kg==)