前言:我们在使用一些数据库或者其他连接工具的时候,为了保证数据安全性,希望对数据库等访问工具的密码进行加解密,比如MySQL、es、kafka等。
我们可以使用jasypt对密码加密解密,具体使用方式如下:
1、添加依赖:
<!--数据库密码加密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、对想要加密的数据库用户名、密码等进行加密
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
//生成秘钥的公钥
//config.setPassword("Romeo&Juliet");
config.setPassword("lilei&hanmeimei");
//应用配置
encryptor.setConfig(config);
//明文密码
String plaintext = "root";
String plainPasstext = "Dog7Cat@2020!7*";
//加密
String ciphertext = encryptor.encrypt(plaintext);
String cipherPasstext = encryptor.encrypt(plainPasstext);
System.out.println(plaintext + "加密后: " + ciphertext);
System.out.println(plainPasstext + "加密后: " + cipherPasstext);
//解密 过程
String pname = encryptor.decrypt("o6Xp+x0JLd+O5p1s+bJyoQ==");
String pass = encryptor.decrypt("CeAMUxhvLiGLSuy+r/7Ja1r9EukLuEd8");
System.out.println( "解密后账号: " + pname);
System.out.println( "解密后密码: " + pass)‘
3、因为我使用的是是nacos,所以是在nacos配置文件中配置 加密配置和生成密钥的公钥,并将加密后的用户名、密码配置到配置文件中。(注意:添加后在启动项目的时候,jasypt会自动使用 加密配置和生成密钥的公钥对加密后的数据解密,然后连接数据库。)
jasypt:
encryptor:
password: PBEWithMD5AndDES
algorithm: lilei&hanmeimei
spring:
datasource:
druid:
url: jdbc:mysql://mysql.ssd.ipaas.cn:8066/test?Unicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2b8
username: ENC(o6Xp+x0JLd+O5p1s+bJyoQ==)
password: ENC(CeAMUxhvLiGLSuy+r/7Ja1r9EukLuEd8)
driver-class-name: com.mysql.cj.jdbc.Driver
注意:如果加密配置和公钥都暴露在配置文件中,其他人是可以通过公钥来解密的,比如上述做法,这样显然是不够安全的。所以我们一般在项目启动的时候,在linus系统中手动输入指令来启动项目。比如
nohup java -jar xxx.jar
--spring.profiles.active= dev
--jasypt.encryptor.password= PBEWithMD5AndDES
--jasypt.encryptor.algorithm= lilei&hanmeimei