700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > SpringBoot配置文件yml敏感信息加密

SpringBoot配置文件yml敏感信息加密

时间:2022-02-26 17:15:43

相关推荐

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版本的项目。查看最新版本可以到

/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配置文件里的敏感信息加密。是不是很简单。当然这个密钥如果暴露的话,也是不安全的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。