SpringBoot配置文件yml敏感信息加密,防偷窥

java项目使用SpringBoot很方便,但SpringBoot的配置文件朋友们都知道,资源文件中的内容通常情况下是明文显示,安全性就比较低一些。打开application.properties或application.yml,比如mysql登陆密码,redis登陆密码以及第三方的密钥等等一览无余,这里介绍一个加解密组件,提高一些属性配置的安全性,相对而言。jasypt是由一个国外哥们儿大神写了一个springboot下的工具包,可以加密配置文件中的敏感数据。如下是实例:
以数据用户名和数据库密码加密为例

一,使用maven引入jar

<dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot-starter</artifactId>
        <version>2.1.0</version>
</dependency>

2.1.0版本是其中的一个版本,适用于SpringBoot2.1版本的项目。查看最新版本可以到
https://github.com/ulisesbocchio/jasypt-spring-boot查看

二,application.yml或application.properties配置文件中增加如下内容(加解密时使用)

#jasypt加密的密匙
jasypt:
  encryptor:
    password: abcdabcdabcd #这里是自定义的密钥

三,可以在测试用例中生成加密后的秘钥

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class testTest {
    @Autowired
    StringEncryptor encryptor;

    @Test
    public void getPass() {
        String url = encryptor.encrypt("jdbc:mysql://127.0.0.1:3306/dogdb?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8");
        String name = encryptor.encrypt("你的数据库名");
        String password = encryptor.encrypt("你的数据库密码");
        System.out.println(url);
        System.out.println(name);
        System.out.println(password);
    }
}

下面是加密后的输出结果
jbmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPta=
lbmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPtb=
ibmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPtc=

四,将上面生成的name和password替换配置文件中的数据库账户和密码,在yml中替换后如下:

spring:
  #数据库相关配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    #这里加上后缀用来防止mysql乱码,serverTimezone=GMT%2b8设置时区
    url: ENC(jbmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPta=)
    username: ENC(lbmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPtb=)
    password: ENC(ibmabcdefgDKQRPewabcefqZuxMatGoTghaMwwaQrPtc=)

server:
  port: 6666
#jasypt加密的密匙
jasypt:
  encryptor:
    password: abcdabcdabcd

以上实例和SpringBoot的版本有一定关系,适用于SpringBoot2.1的版本,SpringBoot2.2的版本则需要加另外的参数,如下:

#jasypt加密的密匙
jasypt:
  encryptor:
    # 密钥
    password: abcdabcdabcd
    # 指定加密方式
    algorithm: PBEWithMD5AndDES
    iv-generator-classname: org.jasypt.iv.NoIvGenerator

另注意上面的 ENC()是固定写法,()里面是加密后的信息。到此,我们就实现了springboot配置文件里的敏感信息加密。是不是很简单。当然这个密钥如果暴露的话,也是不安全的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值