在日常开发工作中,我们经常需要使用到各种敏感配置,如数据库密码、各厂商的 SecretId、SecretKey 等敏感信息。
通常情况下,我们会将这些敏感信息明文放到配置文件中,或者放到配置中心中。
然而,这种做法存在严重的安全隐患!
学会用Jasypt 库来加密配置文件!
Jasypt 是一个开源的 Java 加密库,可以为应用程序提供加密和解密功能
<properties>
<jasypt-spring-boot-starter.version>3.0.4jasypt-spring-boot-starter.version>
properties>
<dependency>
<groupId>com.github.ulisesbocchiogroupId>
<artifactId>jasypt-spring-boot-starterartifactId>
<version>${jasypt-spring-boot-starter.version}version>
dependency>
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Value;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JasyptUtil {
/**
* 加密时的密钥
*/
private static String PRIVATE_KEY = "Evw3vbDt";
private static final String PREFIX = "ENC(";
private static final String SUFFIX = ")";
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(PRIVATE_KEY);
}
/**
* 明文加密
*/
public static String encrypt(String plaintext) {
return basicTextEncryptor.encrypt(plaintext);
}
/**
* 解密
*/
public static String decrypt(String ciphertext) {
ciphertext = PREFIX + ciphertext + SUFFIX;
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
return plaintext;
}
return "";
}
}
@Test
public void testEncrypt() {
String encrypt = JasyptUtil.encrypt("CSNZ");
System.out.println(encrypt);
}
@Test
public void testDecrypt() {
String decrypt = JasyptUtil.decrypt("OJsBWVePwbelr5XKuWXhYw==");
System.out.println(decrypt);
}
@Value("${jasypt.passKey}")
private static String PRIVATE_KEY;
server:
port: 8080
encrypt:
test:
# 此处是密码的密文(文中示例的就是CSNZ的密文),要用 ENC() 进行包裹
name: ENC(OJsBWVePwbelr5XKuWXhYw==)
# 加密配置
jasypt:
encryptor:
# 指定加密密钥,生产环境需要放到启动参数
password: ${jasypt.passKey}
# 指定解密算法,需要和加密时使用的算法一致
algorithm: PBEWithMD5AndDES
# 指定 initialization vector 类型
iv-generator-classname: org.jasypt.iv.NoIvGenerator
@SpringBootApplication
public class Application implements InitializingBean {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Value("${encrypt.test.name}")
private String name;
@Override
public void afterPropertiesSet() throws Exception {
System.err.println("程序启动...");
System.out.println(name);
}
}