Springboot - druid 数据库密码加密

Druid的ConfigTools工具类使用了RSA非对称加密算法来进行密码加密。它通过生成公钥和私钥对来进行加密和解密操作。具体的加密原理如下:

1、通过ConfigTools会生成一对RSA公钥和私钥。
static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("privateKey:" + privateKey);
            publicKey = keyPair[1];
            System.out.println("publicKey:" + publicKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

2、原始密码会使用私钥进行加密,生成密文。ConfigTools.encrypt(String key, String plainText)
public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }
3、原始密码会使用公钥进行解密,生成明文。ConfigTools.decrypt(String key, String encryptText)
public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt:" + decrypt);
        return decrypt;
    }
4、示例如下:

5、密文保存在配置文件进行解密。

        说明:durid配置配置以后会自动进行解密,原理就是通过2中所示的方法进行解密。

6、配置文件
spring:
  datasource:
    username: root
    password: b6/R50FChU0r52ry8ioP0NJN59WOvPi3Hm0sIvdvL6jbXshPoXTYA2AIKledgApHNSbn7XaUOrMZ1bpsQwaC3g==  #加密后的密码
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jrlyt_sub?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      connectionProperties: config.decrypt=true;config.decrypt.key=${publicKey}; #公钥自动扫描
    filter:
      config:
        enabled: true #开启属性是扫描
#加密公钥
publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ2mWVq2XZ1IKrtlPwHiTITWZ5vOS0DkTxwPJydxARhR94LAU4K4nUs7LclI9Pa+gBiewC/Wp2DHj4c8Lsdq9vUCAwEAAQ==

注:别忘记导入依赖哦。

感谢小伙伴的观看,希望对你有帮助!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值