MybatisPlus-配置加密

配置加密

目前配置文件中的很多参数都是明文,如果开发人员发生流动,很容易导致敏感信息的泄露。所以MybatisPlus支持配置文件的加密和解密功能。

我们以数据库的用户名和密码为例。

生成秘钥

首先,我们利用AES工具生成一个随机秘钥,然后对用户名、密码加密:

Java 复制代码
package com.itheima.mp;

import com.baomidou.mybatisplus.core.toolkit.AES;
import org.junit.jupiter.api.Test;

class MpDemoApplicationTests {
    @Test
    void contextLoads() {
        // 生成 16 位随机 AES 密钥
        String randomKey = AES.generateRandomKey();
        System.out.println("randomKey = " + randomKey);

        // 利用密钥对用户名加密
        String username = AES.encrypt("root", randomKey);
        System.out.println("username = " + username);

        // 利用密钥对用户名加密
        String password = AES.encrypt("1234", randomKey);
        System.out.println("password = " + password);
    }
}

打印结果如下:

SQL 复制代码
randomKey = 6234633a66fb399f
username = px2bAbnUfiY8K/IgsKvscg==
password = FGvCSEaOuga3ulDAsxw68Q==

修改配置

修改application.yaml文件,把jdbc的用户名、密码修改为刚刚加密生成的密文

YAML 复制代码
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: mpw:QWWVnk1Oal3258x5rVhaeQ== # 密文要以 mpw:开头
    password: mpw:EUFmeH3cNAzdRGdOQcabWg== # 密文要以 mpw:开头

测试

在启动项目的时候,需要把刚才生成的秘钥添加到启动参数中,像这样:

--mpw.key=6234633a66fb399f

单元测试的时候不能添加启动参数,所以要在测试类的注解上配置:

然后随意运行一个单元测试,可以发现数据库查询正常。

相关推荐
AA-代码批发V哥5 小时前
MyBatisPlus之CRUD接口(IService与BaseMapper)
mybatis
_码农121388 小时前
spring boot 使用mybatis简单连接数据库+连表查询
数据库·spring boot·mybatis
我科绝伦(Huanhuan Zhou)15 小时前
【故障案例】Redis缓存三大难题:雪崩、击穿、穿透解析与实战解决方案
redis·缓存·mybatis
喜欢敲代码的程序员16 小时前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:日志管理(四)集成Spring Security
spring boot·mysql·spring·vue·mybatis
AA-代码批发V哥19 小时前
MyBatisPlus之核心注解与配置
mybatis
波波玩转AI19 小时前
MyBatis核心
数据库·mybatis
飞翔的佩奇1 天前
基于SpringBoot+MyBatis+MySQL+VUE实现的经方药食两用服务平台管理系统(附源码+数据库+毕业论文+部署教程+配套软件)
数据库·vue.js·spring boot·mysql·毕业设计·mybatis·经方药食两用平台
_码农121382 天前
spring boot + mybatis + mysql 只有一个实体类的demo
spring boot·mysql·mybatis
_码农121382 天前
使用mybatis生成器生成实体类mapper和查询参数文件,简单spring mvc 项目。使用log4j输出日志到控制台和文件中。使用配置文件注册Bean
spring·mvc·mybatis
cleble2 天前
(转)mybatis和hibernate的 缓存区别?
mybatis·hibernate