展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 数据库 > 编程开发 > springboot项目数据库密码怎么实现加密

springboot项目数据库密码怎么实现加密

方案一、使用druid数据库连接池对数据库密码加密1、pom.xml引入druid包为了方便其他的操作,这边直接引入druid的startercom.alibabadruid-spring-boot-starter${druid.version}2、利用com.alibaba.druid.filter.config.ConfigTools生成公私钥ps:生成的方式有两种,一种利用命令行生成,一种直接写个工具类生成。本文示例直接采用工具类生成工具类代码如下/***alibabadruid加解密规则:*明文密

本文目录

    方案一、使用druid数据库连接池对数据库密码加密

    1、pom.xml引入druid包

    为了方便其他的操作,这边直接引入druid的starter

    
       com.alibaba
       druid-spring-boot-starter
       ${druid.version}
      

    2、利用com.alibaba.druid.filter.config.ConfigTools生成公私钥

    ps: 生成的方式有两种,一种利用命令行生成,一种直接写个工具类生成。本文示例直接采用工具类生成

    工具类代码如下

    /**
     * alibaba druid加解密规则:
     * 明文密码+私钥(privateKey)加密=加密密码
     * 加密密码+公钥(publicKey)解密=明文密码
     */
    public final class DruidEncryptorUtils {
    
        private static String privateKey;
    
        private static String publicKey;
    
        static {
            try {
                String[] keyPair = ConfigTools.genKeyPair(512);
                privateKey = keyPair[0];
                System.out.println(String.format("privateKey-->%s",privateKey));
                publicKey = keyPair[1];
                System.out.println(String.format("publicKey-->%s",publicKey));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 明文加密
         * @param plaintext
         * @return
         */
        @SneakyThrows
        public static String encode(String plaintext){
            System.out.println("明文字符串:" + plaintext);
            String ciphertext = ConfigTools.encrypt(privateKey,plaintext);
            System.out.println("加密后字符串:" + ciphertext);
            return ciphertext;
        }
    
        /**
         * 解密
         * @param ciphertext
         * @return
         */
        @SneakyThrows
        public static String decode(String ciphertext){
            System.out.println("加密字符串:" + ciphertext);
            String plaintext = ConfigTools.decrypt(publicKey,ciphertext);
            System.out.println("解密后的字符串:" + plaintext);
    
            return plaintext;
        }

    3、修改数据库的配置文件内容信息

    a 、 修改密码
    把密码替换成用DruidEncryptorUtils这个工具类生成的密码

     password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}

    b、 filter开启config

     filter:
                    config:
                        enabled: true

    c、配置connectionProperties属性

     connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}

    ps: spring.datasource.publickey为工具类生成的公钥

    附录: 完整数据库配置

    spring:
        datasource:
            type: com.alibaba.druid.pool.DruidDataSource
            driverClassName: com.mysql.cj.jdbc.Driver
            url: ${DATASOURCE_URL:jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}
            username: ${DATASOURCE_USERNAME:root}
            password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
            publickey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvP9xF4RCM4oFiu47NZY15iqNOAB9K2Ml9fiTLa05CWaXK7uFwBImR7xltZM1frl6ahWAXJB6a/FSjtJkTZUJECAwEAAQ==
            druid:
                # 初始连接数
                initialSize: 5
                # 最小连接池数量
                minIdle: 10
                # 最大连接池数量
                maxActive: 20
                # 配置获取连接等待超时的时间
                maxWait: 60000
                # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
                timeBetweenEvictionRunsMillis: 60000
                # 配置一个连接在池中最小生存的时间,单位是毫秒
                minEvictableIdleTimeMillis: 300000
                # 配置一个连接在池中最大生存的时间,单位是毫秒
                maxEvictableIdleTimeMillis: 900000
                # 配置检测连接是否有效
                validationQuery: SELECT 1 FROM DUAL
                testWhileIdle: true
                testOnBorrow: false
                testOnReturn: false
                webStatFilter:
                    enabled: true
                statViewServlet:
                    enabled: true
                    # 设置白名单,不填则允许所有访问
                    allow:
                    url-pattern: /druid/*
                    # 控制台管理用户名和密码
                    login-username:
                    login-password:
                filter:
                    stat:
                        enabled: true
                        # 慢SQL记录
                        log-slow-sql: true
                        slow-sql-millis: 1000
                        merge-sql: true
                    wall:
                        config:
                            multi-statement-allow: true
                    config:
                        enabled: true
                connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}

    方案二:使用jasypt对数据库密码加密

    1、pom.xml引入jasypt包

    
       com.github.ulisesbocchio
       jasypt-spring-boot-starter
       ${jasypt.verison}
      

    2、利用jasypt提供的工具类对明文密码进行加密

    加密工具类如下

    public final class JasyptEncryptorUtils {
    
    
        private static final String salt = "lybgeek";
    
        private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
    
        static {
            basicTextEncryptor.setPassword(salt);
        }
    
        private JasyptEncryptorUtils(){}
    
        /**
         * 明文加密
         * @param plaintext
         * @return
         */
        public static String encode(String plaintext){
            System.out.println("明文字符串:" + plaintext);
            String ciphertext = basicTextEncryptor.encrypt(plaintext);
            System.out.println("加密后字符串:" + ciphertext);
            return ciphertext;
        }
    
        /**
         * 解密
         * @param ciphertext
         * @return
         */
        public static String decode(String ciphertext){
            System.out.println("加密字符串:" + ciphertext);
            ciphertext = "ENC(" + ciphertext + ")";
            if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)){
                String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext,basicTextEncryptor);
                System.out.println("解密后的字符串:" + plaintext);
                return plaintext;
            }
            System.out.println("解密失败");
            return "";
        }
    }

    3、修改数据库的配置文件内容信息

    a、 用ENC包裹用JasyptEncryptorUtils 生成的加密串

    password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}

    b、 配置密钥和指定加解密算法

    jasypt:
        encryptor:
            password: lybgeek
            algorithm: PBEWithMD5AndDES
            iv-generator-classname: org.jasypt.iv.NoIvGenerator

    因为我工具类使用的是加解密的工具类是BasicTextEncryptor,其对应配置加解密就是PBEWithMD5AndDES和org.jasypt.iv.NoIvGenerator

    ps: 在生产环境中,建议使用如下方式配置密钥,避免密钥泄露

    java -jar -Djasypt.encryptor.password=lybgeek

    附录: 完整数据库配置

    spring:
        datasource:
            type: com.alibaba.druid.pool.DruidDataSource
            driverClassName: com.mysql.cj.jdbc.Driver
            url: ${DATASOURCE_URL:ENC(kT/gwazwzaFNEp7OCbsgCQN7PHRohaTKJNdGVgLsW2cH67zqBVEq7mN0BTIXAeF4/Fvv4l7myLFx0y6ap4umod7C2VWgyRU5UQtKmdwzQN3hxVxktIkrFPn9DM6+YahM0xP+ppO9HaWqA2ral0ejBCvmor3WScJNHCAhI9kHjYc=)}
            username: ${DATASOURCE_USERNAME:ENC(rEQLlqM5nphqnsuPj3MlJw==)}
            password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}
            druid:
                # 初始连接数
                initialSize: 5
                # 最小连接池数量
                minIdle: 10
                # 最大连接池数量
                maxActive: 20
                # 配置获取连接等待超时的时间
                maxWait: 60000
                # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
                timeBetweenEvictionRunsMillis: 60000
                # 配置一个连接在池中最小生存的时间,单位是毫秒
                minEvictableIdleTimeMillis: 300000
                # 配置一个连接在池中最大生存的时间,单位是毫秒
                maxEvictableIdleTimeMillis: 900000
                # 配置检测连接是否有效
                validationQuery: SELECT 1 FROM DUAL
                testWhileIdle: true
                testOnBorrow: false
                testOnReturn: false
                webStatFilter:
                    enabled: true
                statViewServlet:
                    enabled: true
                    # 设置白名单,不填则允许所有访问
                    allow:
                    url-pattern: /druid/*
                    # 控制台管理用户名和密码
                    login-username:
                    login-password:
                filter:
                    stat:
                        enabled: true
                        # 慢SQL记录
                        log-slow-sql: true
                        slow-sql-millis: 1000
                        merge-sql: true
                    wall:
                        config:
                            multi-statement-allow: true
    jasypt:
        encryptor:
            password: lybgeek
            algorithm: PBEWithMD5AndDES
            iv-generator-classname: org.jasypt.iv.NoIvGenerator

    方案三:自定义实现

    实现原理: 利用spring后置处理器修改DataSource

    1、自定义加解密工具类

    /**
     * 利用hutool封装的加解密工具,以AES对称加密算法为例
     */
    public final class EncryptorUtils {
    
        private static String secretKey;
    
    
    
        static {
            secretKey = Hex.encodeHexString(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
            System.out.println("secretKey-->" + secretKey);
            System.out.println("--------------------------------------------------------------------------------------");
        }
    
        /**
         * 明文加密
         * @param plaintext
         * @return
         */
        @SneakyThrows
        public static String encode(String plaintext){
            System.out.println("明文字符串:" + plaintext);
            byte[] key = Hex.decodeHex(secretKey.toCharArray());
            String ciphertext =  SecureUtil.aes(key).encryptHex(plaintext);
            System.out.println("加密后字符串:" + ciphertext);
    
            return ciphertext;
        }
    
        /**
         * 解密
         * @param ciphertext
         * @return
         */
        @SneakyThrows
        public static String decode(String ciphertext){
            System.out.println("加密字符串:" + ciphertext);
            byte[] key = Hex.decodeHex(secretKey.toCharArray());
            String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
            System.out.println("解密后的字符串:" + plaintext);
    
            return plaintext;
        }
    
        /**
         * 明文加密
         * @param plaintext
         * @return
         */
        @SneakyThrows
        public static String encode(String secretKey,String plaintext){
            System.out.println("明文字符串:" + plaintext);
            byte[] key = Hex.decodeHex(secretKey.toCharArray());
            String ciphertext =  SecureUtil.aes(key).encryptHex(plaintext);
            System.out.println("加密后字符串:" + ciphertext);
    
            return ciphertext;
        }
    
        /**
         * 解密
         * @param ciphertext
         * @return
         */
        @SneakyThrows
        public static String decode(String secretKey,String ciphertext){
            System.out.println("加密字符串:" + ciphertext);
            byte[] key = Hex.decodeHex(secretKey.toCharArray());
            String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
            System.out.println("解密后的字符串:" + plaintext);
    
            return plaintext;
        }
    }

    2、编写后置处理器

    public class DruidDataSourceEncyptBeanPostProcessor implements BeanPostProcessor {
    
        private CustomEncryptProperties customEncryptProperties;
    
        private DataSourceProperties dataSourceProperties;
    
        public DruidDataSourceEncyptBeanPostProcessor(CustomEncryptProperties customEncryptProperties, DataSourceProperties dataSourceProperties) {
            this.customEncryptProperties = customEncryptProperties;
            this.dataSourceProperties = dataSourceProperties;
        }
    
    
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if(bean instanceof DruidDataSource){
                if(customEncryptProperties.isEnabled()){
                    DruidDataSource druidDataSource = (DruidDataSource)bean;
                    System.out.println("--------------------------------------------------------------------------------------");
                    String username = dataSourceProperties.getUsername();
                    druidDataSource.setUsername(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),username));
                    System.out.println("--------------------------------------------------------------------------------------");
                    String password = dataSourceProperties.getPassword();
                    druidDataSource.setPassword(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),password));
                    System.out.println("--------------------------------------------------------------------------------------");
                    String url = dataSourceProperties.getUrl();
                    druidDataSource.setUrl(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),url));
                    System.out.println("--------------------------------------------------------------------------------------");
                }
    
            }
            return bean;
        }
    }

    3、修改数据库的配置文件内容信息

    a 、 修改密码
    把密码替换成用自定义加密工具类生成的加密密码

      password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}

    b 、 指定密钥和开启加密功能

    custom:
        encrypt:
            enabled: true
            secret-key: 2f8ba810011e0973728afa3f28a0ecb6

    ps: 同理secret-key最好也不要直接暴露在配置文件中,可以用-Dcustom.encrypt.secret-key指定
    附录: 完整数据库配置

    spring:
        datasource:
            type: com.alibaba.druid.pool.DruidDataSource
            driverClassName: com.mysql.cj.jdbc.Driver
            url: ${DATASOURCE_URL:dcb268cf3a2626381d2bc5c96f94fb3d7f99352e0e392362cb818a321b0ca61f3a8dad3aeb084242b745c61a1d3dc244ed1484bf745c858c44560dde10e60e90ac65f77ce2926676df7af6b35aefd2bb984ff9a868f1f9052ee9cae5572fa015b66a602f32df39fb1bbc36e04cc0f148e4d610a3e5d54f2eb7c57e4729c9d7b4}
            username: ${DATASOURCE_USERNAME:61db3bf3c6d3fe3ce87549c1af1e9061}
            password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
            druid:
                # 初始连接数
                initialSize: 5
                # 最小连接池数量
                minIdle: 10
                # 最大连接池数量
                maxActive: 20
                # 配置获取连接等待超时的时间
                maxWait: 60000
                # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
                timeBetweenEvictionRunsMillis: 60000
                # 配置一个连接在池中最小生存的时间,单位是毫秒
                minEvictableIdleTimeMillis: 300000
                # 配置一个连接在池中最大生存的时间,单位是毫秒
                maxEvictableIdleTimeMillis: 900000
                # 配置检测连接是否有效
                validationQuery: SELECT 1 FROM DUAL
                testWhileIdle: true
                testOnBorrow: false
                testOnReturn: false
                webStatFilter:
                    enabled: true
                statViewServlet:
                    enabled: true
                    # 设置白名单,不填则允许所有访问
                    allow:
                    url-pattern: /druid/*
                    # 控制台管理用户名和密码
                    login-username:
                    login-password:
                filter:
                    stat:
                        enabled: true
                        # 慢SQL记录
                        log-slow-sql: true
                        slow-sql-millis: 1000
                        merge-sql: true
                    wall:
                        config:
                            multi-statement-allow: true
    custom:
        encrypt:
            enabled: true
            secret-key: 2f8ba810011e0973728afa3f28a0ecb6
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    数据库 编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。