springboot整合,用于加密配置文件密码
简介:
在配置文件中,往往会有密码,例如mysql,redis等。如果直接将密码以明文的形式写在项目中,就会有泄露的风险。
所以这里使用jasypt,用于配置文件加密。
应用方式
1、导入依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
2、工具类
package com.walker.tools.utils;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
@Slf4j
public final class JasyptUtils {
public static void main(String[] args) {
String a = encrypt("aaaa");
decrypt(a);
}
/**
* 加密使用密钥
*/
private static final String PRIVATE_KEY = "helloworldforyou";
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(PRIVATE_KEY);
}
/**
* 私有构造方法,防止被意外实例化
*/
private JasyptUtils() {
}
/**
* 明文加密
*
* @param plaintext 明文
* @return String
*/
public static String encrypt(String plaintext) {
log.info("明文字符串为:{}", plaintext);
// 使用的加密算法参考2.2节内容,也可以在源码的类注释中看到
String ciphertext = basicTextEncryptor.encrypt(plaintext);
log.info("密文字符串为:{}", ciphertext);
return ciphertext;
}
/**
* 解密
*
* @param ciphertext 密文
* @return String
*/
public static String decrypt(String ciphertext) {
log.info("密文字符串为:{}", ciphertext);
ciphertext = "ENC(" + ciphertext + ")";
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
log.info("明文字符串为:{}", plaintext);
return plaintext;
}
log.error("解密失败!");
return "";
}
}
3、配置文件 application.yaml
jasypt:
encryptor:
# 指定加密密钥,生产环境请放到启动参数里面
password: helloworldforyou
# 指定解密算法,需要和加密时使用的算法一致
algorithm: PBEWithMD5AndDES
# 指定initialization vector类型
iv-generator-classname: org.jasypt.iv.NoIvGenerator
test:
entry: ENC(KCJWcMKAxNct3H3AN41/Zw==)
algorithm:算法
可以进行配置,例如MD5等
在配置文件中,可以使用ENC(加密内容)
去配置变量,达到加密的效果。防止配置文件直接被获取,起到保护的作用
4、测试
1、使用相同的加密key,对字符串进行加密,然后将字符串赋予到配置文件中
2、编写一个测试类
package com.walker.tools;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WalkerToolsApplicationTests {
@Value("${test.entry}")
private String value;
@Test
void contextLoads() {
System.out.println(value);
}
}
3、执行之后,就能够获取解密后的结果