spring配置文件加密处理

spring配置文件加密处理

概述

配置文件中如果包含敏感的数据,例如数据库密码,会留下安全隐患,正确的做法是对配置文件中的敏感数据进行加密,使用的时候再进行解密。
本文演示如何读取spring配置文件中的加密数据。

基本原理

jasypt-spring-boot框架可以实现在读取spring配置文件时,进行解密的功能。

  1. 引入jasypt-spring-boot包:
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
  1. 实现解密类Resolver:
@Slf4j
public class ConfigDecryptResolver implements EncryptablePropertyResolver {

 private static final String ENCRYPT_PREFIX = "(ENC)";

 /**
  * 进行解密
  * @param s 加密的字符串
  * @return 解密后的字符串
  */
 @Override
 public String resolvePropertyValue(String s) {
   if (StringUtils.isEmpty(s)) {
     return s;
   }

   if (encrypted(s)) {
     return SensitiveDataEncrypter.decrypt(s.substring(ENCRYPT_PREFIX.length() - 1));
   } else {
     return s;
   }

 }

 /**
  * 判断是否是加密后的数据
  *
  * @param str 字符串
  * @return 判断字符串是否是加密后的数据
  */
 private boolean encrypted(String str) {
   if (str.startsWith(ENCRYPT_PREFIX)) {
     return true;
   } else {
     return false;
   }
 }
}
  1. 加载解密类:
@EnableAutoConfiguration
@SpringBootApplication
@EnableEncryptableProperties
public class TestEncrypt {

 /**
  * 加载解密类
  */
 @Bean
 public EncryptablePropertyResolver encryptablePropertyResolver() {
   return new ConfigDecryptResolver();
 }

 public static void main(String[] args) {
   SpringApplication springApplication = new SpringApplication(TestEncrypt.class);
   // 非web方式启动
   springApplication.setWebEnvironment(false);
   springApplication.run(args);
 }

}
  1. 测试:
//  ---------------------------------------------------------配置文件的内容为:
encrypt:
 test1: (ENC)ucSL5R/jQigQ1dxzsWi2kg==
 test2: 12345678
 
// ---------------------------------------------------------配置文件的加载:

@Component
public class TestConfig {

 @Value("${encrypt.test1}")
 private String test1;
 @Value("${encrypt.test2}")
 private String test2;

 @PostConstruct
 public void init() {
   System.out.println("test1:" + test1);
   System.out.println("test2:" + test2);
 }
}

// ---------------------------------------------------------打印结果:
test1:abc
test2:12345678

参考

https://github.com/ulisesbocchio/jasypt-spring-boot

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值