Spring boot如何使用jasypt加密解密数据库密码(代码)
话不多说,直接上
一、加密
首先得引入依赖包吧
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
加密Java代码
//引入需要的包
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
//--------------------------------------------
public static void main(String[] args) {
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
//基本默认都是使用这个"PBEWithMD5AndDES"
config.setAlgorithm("PBEWithMD5AndDES");
//这里你可以加入你想要的盐salt
config.setPassword("x6bdfPVbe1ndeZP3D7cX3U3gcXS7NFXD");
//应用配置
encryptor.setConfig(config);
//需要加密的密码
String plaintext = "root";
//加密
String ciphertext = encryptor.encrypt(plaintext);
System.out.println(plaintext + " : " + ciphertext);
}
运行后得出结果(每次运行都会产生不同的base64加密后的字符串):
root : 2PVO2mYxjLyxd3fh5FjgDM/rO2U4teopVTc0ktZSb+M=
Process finished with exit code 0
然后在数据库配置文件中password:用ENC()括起来,例:password: ENC(2PVO2mYxjLyxd3fh5FjgDM/rO2U4teopVTc0ktZSb+M=)
二、解密
首先也是得看是否引入了包,如果纯粹的解密则直接在加密的项目里面写代码即可(注:如果是自己新建的工程将无法获得你想要的密码或者为空)
//引入需要的包
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
//--------------------------------------------
public static void main(String[] args) {//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
//这里的参数默认为PBEWithMD5AndDES,可以找到JasyptEncryptorConfigurationProperties类中看默认的
config.setAlgorithm("PBEWithMD5AndDES");
//这里的参数为salt,也就是在配置文件中jasypt.encryptor.password中填写的值
config.setPassword("6xbdfPVbe1ndeZPyD7cX3U3gcXS7NFXA");
//应用配置
encryptor.setConfig(config);
//这里的参数为数据库连接上的password,如ENC(eidumReGpawkCC3QaEadJMbLXB2JgnQg),需要去掉ENC()
String ciphertext = "eidumReGpawkCC3QaEadJMbLXB2JgnQg";
//解密
String plaintext = encryptor.decrypt(ciphertext);
System.out.println(ciphertext + " : " + plaintext);
}