Spring boot如何使用jasypt加密解密数据库密码(代码)

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);
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值