Druid数据库加密实现

Druid数据库连接池中的密码加密功能提供了以下几个主要好处:

增强安全性:最显著的好处是提高了数据库系统的安全性。明文存储数据库密码容易造成安全隐患,一旦配置文件泄露,数据库可能遭受未授权访问。通过加密数据库密码,即使配置文件落入未经授权的人员手中,他们也无法直接获取数据库访问权限,增加了非法访问的难度。

合规性:许多组织必须遵守数据保护法规,如GDPR、HIPAA等,这些法规要求对敏感数据进行保护。加密数据库密码是满足这些合规要求的一种方式,有助于防止数据泄露导致的法律责任。

简化管理:在多环境部署(如开发、测试、生产)中,使用加密密码可以简化配置管理。开发人员不需要知道生产数据库的实际密码,减少了密码泄露的风险。

审计追踪:Druid的StatFilter可以记录SQL执行性能,加密密码并不影响这一功能,反而能更好地支持安全审计,因为密码在日志中不会以明文形式出现。

下面是加密的具体实现

application.yml

server:
  port: 3000
spring:
  datasource:
    username: root
    password: //写入加密后的密码
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.88.131:3306/jc-club?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 20
      min-idle: 20
      connectionProperties: config.decrypt=true;config.decrypt.key=${publicKey};
      max-active: 100
      max-wait: 60000
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: 123456
      filter:
        stat:
          enabled: true
          slow-sql-millis: 2000
          log-slow-sql: true
        wall:
          enabled: true
        config:
          enabled: true
publicKey: 写入公钥

加密文件

package com.jingdianjichi.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密工具
 */
public class DruidEncryptUtil {
    private static String publicKey;

    private static String privateKey;

    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 e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }

    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt:" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("Wing1Q2W#E");
        System.out.println("encrypt:" + encrypt);
    }
}

 数据库成功连接

加密示例

posted @ 2024-07-02 00:07  橘子味芬达水  阅读(12)  评论(0编辑  收藏  举报