使用过SpringBoot配置文件的朋友都知道,资源文件中的内容通常情况下是明文显示,安全性就比较低一些。打开application.properties或application.yml,比如mysql登陆密码,redis登陆密码以及第三方的密钥等等一览无余,这里介绍一个加解密组件,提高一些属性配置的安全性。
jasypt,官方给出的释意是:
Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.
simplemall项目也采用此加密组件,结合Spring Boot使用。国外大神Ulises Bocchio写了一个Spring Boot下用的工具包,Github地址:https://github.com/ulisesbocchio/jasypt-spring-boot,下面介绍下jasypt在Spring Boot的用法。
1、引入maven依赖
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter --><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>1.14</version></dependency>
2、配置加密参数
在application.yml 中增加配置
jasypt:encryptor:#这里可以理解成是加解密的时候使用的密钥password: your password
在application.properties中增加配置
jasypt.encryptor.password=your password
此处密码的生成可以通过两种方式生成,写main函数生成和直接采用jar命令方式。本处采用main函数的方式,此代码位于account-serv的test包中。
package com.simplemall.account.test;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.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import com.simplemall.account.AccountServApplication;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@SpringBootTest(classes = AccountServApplication.class)public class Jasyptest {@AutowiredStringEncryptor encryptor;@Testpublic void getPass() {String result = encryptor.encrypt("root");System.out.println(result);Assert.assertTrue(result.length() > 0);}}
3、升级application.properties/yml中相应的配置项
旧有配置
#mysql database configspring.datasource.url=jdbc:mysql://localhost:3306/micro_account?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull#use jasypt to encrypt username/passwordspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driverClassName=com.mysql.jdbc.Driver
升级后配置
#mysql database configspring.datasource.url=jdbc:mysql://localhost:3306/micro_account?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull#use jasypt to encrypt username/passwordspring.datasource.username=ENC(BnBr3/idF0PH9nd20A9BXw==)spring.datasource.password=ENC(BnBr3/idF0PH9nd20A9BXw==)spring.datasource.driverClassName=com.mysql.jdbc.Driver
至此,配置完成,效果就如你在simplemall源码中看到的那样,针对配置文件中相关属性做了一次安全升级。
源码:https://github.com/backkoms/simplemall
扩展阅读: