在之前的系列教程中,咱们曾经介绍了十分多对于Spring Boot配置文件中的各种用法。
这些配置相干的常识都是Spring Boot原生就提供的,而明天咱们将介绍的性能并非Spring Boot原生就反对,但却十分有用:配置内容的加密。
为什么要加密?
个别状况下,为了不便切换环境,咱们会将对于环境的信息寄存在配置文件中,例如mysql的账号密码,redis的账号密码,支付宝、微信的密钥等等。
这些信息是极为敏感的信息,一旦泄露,会造成很大的损失。因而,个别开发者会将配置文件中进一步加密,防止这些敏感信息让不法分子间接获取。
一. 引入 jasypt
上面咱们将应用 https://github.com/ulisesbocchio/jasypt-spring-boot
这个开源我的项目提供的实现和插件,来帮忙咱们轻松的实现配置信息的加密。
第一步:创立一个根底的Spring Boot我的项目(如果您还不会,能够参考这篇文章:疾速入门)
第二步:引入 jasypt
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
第三步:将数据库的用户名和明码进行加密
@Test
public void contextLoads() {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
// 加密所需的salt(盐)
textEncryptor.setPassword("10qyubgc");
// 要加密的数据(数据库的用户名或明码)
String username = textEncryptor.encrypt("root");
String password = textEncryptor.encrypt("password");
System.out.println("username:"+username);
System.out.println("password:"+password);
}
控制台输入:
username:xkPw7rH78Y+4VORyB/7Rhw==
password:DTlViR/goGloKmaFI1DBE17+lchmiA3O
应用 jasypt jar包进行加密
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=10qyubgc algorithm=PBEWithMD5AndDES input=root
控制台输入:
----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11
----ARGUMENTS-------------------
input: root
algorithm: PBEWithMD5AndDES
password: 10qyubgc
----OUTPUT----------------------
xkPw7rH78Y+4VORyB/7Rhw==
拷贝-OUTPUT-下的后果即可
2. 配置properties文件
将生成的加密串配置ENC(加密串)到 application.yml
中
server:
port: 8090
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: ENC(xkPw7rH78Y+4VORyB/7Rhw==)
password: ENC(DTlViR/goGloKmaFI1DBE17+lchmiA3O)
data-username: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
database: MYSQL
hibernate:
ddl-auto: update
jasypt:
encryptor:
password: 10qyubgc # 加密所需的salt(盐)
#algorithm: PBEWithMD5AndDES # 默认加密形式 PBEWithMD5AndDES,能够更改为 PBEWithMD5AndTripleDES
加密形式对应的类为 BasicTextEncryptor 和 StrongTextEncryptor
private final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
public BasicTextEncryptor() {
this.encryptor.setAlgorithm("PBEWithMD5AndDES");
}
private final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
public StrongTextEncryptor() {
this.encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
}
3. 部署时配置 salt (盐值)
为了避免salt(盐)泄露,反解出明码.能够在我的项目部署的时候应用命令传入salt(盐)值
java -jar -Djasypt.encryptor.password=10qyubgc xxx.jar
在环境变量中配置 salt 值
关上/etc/profile文件
vim /etc/profile
文件开端插入
export JASYPT_PASSWORD = 10qyubgc
编译
source /etc/profile
运行
java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar
而此时,配置文件中曾经是加密内容了,敏感信息失去了爱护。
发表回复