SpringBoot配置文件中的内容通常情况下是明文显示,安全性就比较低一些。打开application.properties或application.yml,比如mysql登陆密码,redis登陆密码以及第三方的密钥等等一览无余。
1.
这里介绍一个加解密组件,提高一些属性配置的安全性。
jasypt是一个Springboot下的工具包
以数据库用户名和数据库密码加密为例
步骤如下:
(1)引入maven依赖
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>2.1.0</version></dependency>
(2)application.properties配置文件中增加如下内容(加解密时使用)
#jasypt加密的密匙jasypt.encryptor.password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7
(3)在测试用例中生成加密后的秘钥
package com.ljq.house.web;import org.jasypt.encryption.StringEncryptor;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.context.web.WebAppConfiguration;/*** @Author: ljq* @Date: 18-12-28 下午9:04*/@RunWith(SpringRunner.class)@SpringBootTest@WebAppConfigurationpublic class JasyptTest {@AutowiredStringEncryptor encryptor;@Testpublic void getResult() {String url = encryptor.encrypt("jdbc:mysql://127.0.0.1:3306/houses?useSSL=true&characterEncoding=utf-8" +"&zeroDateTimeBehavior=convertToNull&useUnicode=true");String name = encryptor.encrypt("root");String password = encryptor.encrypt("root");System.out.println(url);System.out.println(name);System.out.println(password);Assert.assertTrue(name.length() > 0);Assert.assertTrue(password.length() > 0);}}
下面是第一次加密后的输出结果
BA9uZ35umFic6NbuaLdGzZBodw/wSqvztMt9UGdlOtxxs/fr/W5kf8Bs6GzzHklNfkcU30g8aQ/XdihsZtqRz1J34zNIQxuH3BCG1kknFayp13G8RhkeF4ptBfx6i6nqnP4Uc0UKpjcsxxfTZImHBVvcTY0RDANk26IGBPZvQry7qKuna/RTMQ==kyMvAncHqzcvGAildsK67w==7QCSL5/HKjxFQRPLGgGH7kAElrmf/mgQ
每次加密的结果还不同,更加增加了可靠性。
(4)将上面生成的url,name和password替换配置文件中的url,数据库账户和密码,替换后如下:
spring.datasource.url=ENC(BA9uZ35umFic6NbuaLdGzZBodw/wSqvztMt9UGdlOtxxs/fr/W5kf8Bs6GzzHklNfkcU30g8aQ/XdihsZtqRz1J34zNIQxuH3BCG1kknFayp13G8RhkeF4ptBfx6i6nqnP4Uc0UKpjcsxxfTZImHBVvcTY0RDANk26IGBPZvQry7qKuna/RTMQ==)spring.datasource.username=ENC(kyMvAncHqzcvGAildsK67w==)spring.datasource.password=ENC(7QCSL5/HKjxFQRPLGgGH7kAElrmf/mgQ)
ENC( )是固定写法,( )里面是加密后的信息。
springboot配置文件里的敏感信息加密的第一种方法就是这样。