实际项目中经常会遇到设置数据库账号密码明文,容易泄露的问题,如何解决?
方法有很多,本文通过jasypt对密码等敏感信息进行加密
操作步骤:
1、添加依赖
xml
<!-- 添加依赖 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、application.yml文件增加配置
yml
jasypt:
encryptor:
#默认加密算法:PBEWITHHMACSHA512ANDAES_256,sha512+AES算法,安全性更高,但是需要 Java JDK 1.9+
#本服务使用jdk1.8,所以使用 PBEWithMD5AndDES md5+des算法
#默认使用 com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor 进行加解密 ,PooledPBEStringEncryptor可以对 其加密的内容进行解密
algorithm: PBEWITHHMACSHA512ANDAES_256
# 加密的盐值,为了安全,该配置可以放在启动参数或者命令行参数中
password: 密钥
property:
# 默认值前缀、后缀、iv-generator-classname
prefix: ENC(
suffix: )
iv-generator-classname: org.jasypt.iv.RandomIvGenerator
3、生成加密后的密钥
java
package com.controller;
import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
public class Demo {
@Resource
StringEncryptor encryptor;
@Test
public void encrypt() {
String url = encryptor.encrypt("jdbc:mysql://ip:3306/db_name?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
String username = encryptor.encrypt("账号");
String pwd = encryptor.encrypt("密码1");
String redisPwd = encryptor.encrypt("密码2");
System.out.println("url = " + url);
System.out.println("username = " + username);
System.out.println("pwd = " + pwd);
System.out.println("redisPwd = " + redisPwd);
}
@Test
public void decrypt() {
String url = encryptor.decrypt("Va4TJO3......=");
String username = encryptor.decrypt("hL8Ii......g");
String pwd = encryptor.decrypt("KkKK......e0bSLw");
System.out.println("url = " + url);
System.out.println("username = " + username);
System.out.println("pwd = " + pwd);
}
}
4、替换数据库密码,ENC()为固定格式,()里面为加密后的密钥
yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: ENC(WIFxYiNZ......)
username: ENC(x2354......)
password: ENC(VNtd8sAx......)
redis:
#single单机 sentinel哨兵
mode: single
host: ip
port: 6379
password: ENC(IyOYR......)
database: 1
timeout: 3000
5、启动测试
sh
# 将盐值放在启动参数中
$ java -jar jasypt-demo.jar --jasypt.encryptor.password=密钥
# 将盐值放在命令行参数中
$ java -Djasypt.encryptor.password=密钥 -jar jasypt-demo.jar
# 也可以将盐值放在系统环境变量中,此处不再展示
6、至此,配置完成,特别需要注意的是密钥千万不要泄露