在Spring boot开发中,需要在application.yml文件里配置数据库的连接信息,或者在启动时传入数据库密码,如果不加密,传明文,数据库就直接暴露了,相当于"裸奔"了,因此需要进行加密处理才行。
第一步:引入jar包【版本随意】
如果使用@SpringBootApplication注解启动的项目,只需增加maven依赖:
pom添加依赖
<!-- 数据库加密配置-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
我们对信息加解密是使用这个jar包的:

第二步:获取加密串
package com.test;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;
public class JasyptTest {
@Test
public void testEncrypt() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,这个算法是默认的
config.setPassword("密钥"); // 加密的密钥,必须为ASCll码
standardPBEStringEncryptor.setConfig(config);
String plainText = "明文字符串"; //如:数据库密码
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
@Test
public void testDe() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("密钥");
standardPBEStringEncryptor.setConfig(config);
String encryptedText = "加密串"; //执行上面方法得到的加密串
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println(plainText);
}
}
第三步:配置数据库信息
加密串拿到了,现在来修改application.yml的配置,我们把加密串放在ENC(加密串)即可:
spring:
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: 数据库地址
username: 用户名
password: ENC(密码加密串)
第四步:配置自动解密密钥
启动时需要配置 秘钥
方案一:在yml中加这个密钥的配置,在项目启动的时候,会根据密钥自动解密ENC(加密串)所代表的数据信息:
jasypt:
encryptor:
password: 密钥
..........................................
方案二:将秘钥加入启动参数


发布:应用发布Linux系统的Tomcat配置
打开tomcat的bin目录下的catalina.sh文件,添加jasypt盐值

配置如下
JAVA_OPTS="-Djasypt.encryptor.password=dkycs"
[图片上传中...(image.png-c4abb9-1641289038991-0)]

【注】github上参考项目地址:https://github.com/chyanwu/erp-framework
网友评论