数据库连接加密(SpringBoot+jasypt加密)
SpringBoot项目经常将连接数据库的密码明文放在配置文件里,安全性就比较低一些,尤其在一些企业对安全性要求很高,因此我们就考虑如何对密码进行加密。 jasypt 是一个简单易用的加解密Java库,可以快速集成到 Spring Boot 项目中,并提供了自动配置,使用非常简单。步骤如下:1)引入maven依赖<dependency><groupId>com.git
·
SpringBoot项目经常将连接数据库的密码明文放在配置文件里,安全性就比较低一些,尤其在一些企业对安全性要求很高,因此我们就考虑如何对密码进行加密。
jasypt 是一个简单易用的加解密Java库,可以快速集成到 Spring Boot 项目中,并提供了自动配置,使用非常简单。
步骤如下:
- 1)引入maven依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.17</version>
</dependency>
- 2)再配置文件application.yml
jasypt:
encryptor:
password: 123456 # jasypt加密的盐值
- 3)测试用例中生成加密后的密匙
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.junit.jupiter.api.Test;
public class TestEncryptorTest {
@Test
public void test() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("123456");//yml文件里设置的key
String url = encryptor.encrypt("jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true");
String name = encryptor.encrypt("root");
String password = encryptor.encrypt("root");
String url1 = encryptor.decrypt(url);
String name1 = encryptor.decrypt(name);
String password1 = encryptor.decrypt(password);
System.out.println("url密文:"+url);
System.out.println("url明文:"+url1);
System.out.println("username密文:"+name);
System.out.println("username明文:"+name1);
System.out.println("password密文:"+password);
System.out.println("password明文:"+password1);
}
}
/*输出:
url密文:1L+DJGp6GKaSjXWQDGafQdjPrxEvOebftER88SsTAux/zJsaWSHs4K61s7QNyBwdKd0UEYVmnNaFtVMXHkj7nFh8UlvpmvgmtPSscC+Qeww=
url明文:jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true
username密文:TeRrFJqzQGcsuIsQ20ANsg==
username明文:root
password密文:2HhGPhzjfTCdPiLGBZuY53DIHAMNTNRe
password明文:root
*/
- 4)将上面的生成的密匙添加到application.yml配置中,此处主要是数据库密码密文使用ENC进行标识
spring:
datasource:
url: ENC(1L+DJGp6GKaSjXWQDGafQdjPrxEvOebftER88SsTAux/zJsaWSHs4K61s7QNyBwdKd0UEYVmnNaFtVMXHkj7nFh8UlvpmvgmtPSscC+Qeww=)
username: ENC(TeRrFJqzQGcsuIsQ20ANsg==)
password: ENC(2HhGPhzjfTCdPiLGBZuY53DIHAMNTNRe)
- 5)运行程序,可以连上数据库的。配置文件上是看不见具体连接信息的,相对安全。
补充:API接口进行数据加密
同样可以对接口传递的数据进行加密。后端对传递数据的接口进行加密,并提供对应的解密接口,前端在调用传递数据接口的同时,也调用解密接口,便实现了对数据的加密解密。这样做的好处是,前端只能看见想要看见并能看见的数据,使得数据相对安全。
更多推荐
所有评论(0)