前言
SpringBoot项目配置文件一般是properties或者yml文件,项目打包的时候JVM是不进行编译处理的,目前项目中关于类似数据库地址、用户名、密码等都是明文,很容易泄露,造成损失。此文针对于这个问题提供一种解决方案,仅供参考。
技术方案
这里提供一种加解密的技术方案,来提高属性配置的安全性。利用到jasypt包,GitHub地址:https://github.com/ulisesbocchio/jasypt-spring-boot
这个组件需要在项目种配置加密密钥,每次对信息加密后都会得到不同的密文,但是解密都会得到相同的明文,非常适合数据库敏感配置信息的加密。
从项目启动信息来看,jasypt包使用的是默认的PBEWithMD5AndDES算法。
最佳实践
-
引入依赖包
Gradle:
compile group: 'com.github.ulisesbocchio', name: 'jasypt-spring-boot-starter', version: '2.1.1'Maven:
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> -
配置密钥
密钥可以配置在properties或者yml文件中,但是这种是不安全的,最佳实践是配置在springboot启动类中,由JVM进行编译。代码如下:@SpringBootApplication public class JiraApiApplication { public static void main(String[] args) { //配置密钥 System.setProperty("jasypt.encryptor.password", "123456789"); SpringApplication.run(JiraApiApplication.class, args); } } -
配置自定义ENC
ENC是jasypt识别配置属性是否是加密后的,如果是,则会进行自动解密。
默认是例如:datasource.username = ENC(用户名密文) 这样的形式。
jasypt 支持自定义配置,需要在配置文件中配置。具体代码如下.这样配置属性的时候. datasource.username = ENC@{用户名密文},遇到ENC@{}这种配置会自动解密。#jasypt加密前缀后缀 jasypt.encryptor.property.prefix = ENC@{ jasypt.encryptor.property.suffix = } -
敏感信息加密
利用StringEncryptor的encrypt和decrypt进行加密和解密,把加密后的字符串赋值出来配置在原来配置的地方,例如 datasource.username = ENC@{密文},注意:ENC@{}必须带,不然不会解密。例子如下:@Autowired private StringEncryptor stringEncryptor; @GetMapping("/test") public String test() { String password = "jdbc:mysql://10.67.7.08:3306/txtx_api?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String url = stringEncryptor.encrypt(password); System.out.println("数据库地址加密:" + url); System.out.println("数据库地址解密:" + stringEncryptor.decrypt(url)); String user = "df"; String useren = stringEncryptor.encrypt(user); System.out.println("用户名加密:" + useren); System.out.println("用户名解密:" + stringEncryptor.decrypt(useren)); String p = "fgf"; String pern = stringEncryptor.encrypt(p); System.out.println("密码加密:" + pern); System.out.println("密码解密:" + stringEncryptor.decrypt(pern)); System.out.println(jiraInfoConfig.getServer().toString()); System.out.println(this.url); System.out.println(this.username); System.out.println(this.password); return ""; }#database spring.datasource.url = ENC@{AFAg9VNoh+Mftsh6OunDPjCUgD9WlV1mki5fSwKKllmhWdtr2VkGEvOrOka54B6lYN5MKkhq2FJq7ney7x8l7F16nhKMJQy3fDKLe6Ik7JK3T9U21AwCt6WeTVfRnEzYp62OmQInhds=} spring.datasource.username = ENC@{2/Jb2ViwegnruYtkjBC3ZA==} spring.datasource.password = ENC@{ladm0Gt6Vdm+D8JScT2ifqbmEUOADPyc}
本文探讨了SpringBoot项目中配置文件的敏感信息如数据库凭证明文存储带来的风险,并提出使用jasypt库进行加密的解决方案。通过设置加密密钥并确保密钥的安全存储,可以增强属性配置的安全性。文章还推荐了将密钥配置在启动类中以提高安全性,并介绍了如何自定义ENC标记以实现加密属性的自动解密。

5841

被折叠的 条评论
为什么被折叠?



