Spring Boot中使用MyBatis-Plus和MyBatis拦截器来实现对带有特定注解的字段进行AES加密。

devtools/2024/10/21 8:05:44/

1. 添加依赖
首先,在pom.xml文件中添加必要的依赖项:

xml
深色版本
<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis-Plus Spring Boot Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>

    <!-- AES加密库 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>
</dependencies>
2. 创建自定义注解
创建一个自定义注解@Encrypt,用于标记需要加密的字段:

java
深色版本
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Encrypt {
}
3. 创建AES加密工具类
创建一个AES加密工具类,用于加密和解密数据:

java
深色版本
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesUtil {

    private static final String KEY = "your-secret-key"; // 16位秘钥
    private static final String IV = "your-init-vector"; // 16位初始向量

    public static String encrypt(String value) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String value) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(value));
        return new String(original);
    }
}
4. 创建MyBatis拦截器
创建一个MyBatis拦截器,用于在插入数据前对带有@Encrypt注解的字段进行加密:

java
深色版本
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Field;

public class EncryptionInterceptor implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Class<?> entityClass = metaObject.getOriginalObject().getClass();
            for (Field field : entityClass.getDeclaredFields()) {
                if (field.isAnnotationPresent(Encrypt.class)) {
                    field.setAccessible(true);
                    Object value = field.get(metaObject.getOriginalObject());
                    if (value != null) {
                        String encryptedValue = AesUtil.encrypt(value.toString());
                        field.set(metaObject.getOriginalObject(), encryptedValue);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Encryption failed", e);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 如果需要在更新时也进行加密,可以在这里实现
    }
}
5. 配置拦截器
在Spring Boot的配置类中注册拦截器:

java
深色版本
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    @Bean
    public EncryptionInterceptor encryptionInterceptor() {
        return new EncryptionInterceptor();
    }
}
6. 创建实体类和Mapper
创建实体类TestPayRecord,并在需要加密的字段上加上@Encrypt注解:

java
深色版本
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

@TableName("test_pay_record")
public class TestPayRecord {

    @TableField("request_no")
    private String requestNo;

    @TableField("card_number")
    @Encrypt
    private String cardNumber;

    @TableField("card_phone")
    @Encrypt
    private String cardPhone;

    // Getters and Setters
    public String getrequestNo() {
        return requestNo;
    }

    public void setrequestNo(String requestNo) {
        this.requestNo = requestNo;
    }

    public String getCardNumber() {
        return cardNumber;
    }

    public void setCardNumber(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    public String getCardPhone() {
        return cardPhone;
    }

    public void setCardPhone(String cardPhone) {
        this.cardPhone = cardPhone;
    }
}
创建Mapper接口:

java
深色版本
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.TestPayRecord;

public interface TestPayRecordMapper extends BaseMapper<TestPayRecord> {
}
7. 创建Service和Controller
创建Service类:

java
深色版本
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.TestPayRecord;
import com.example.demo.mapper.TestPayRecordMapper;
import org.springframework.stereotype.Service;

@Service
public class TestPayRecordService extends ServiceImpl<TestPayRecordMapper, TestPayRecord> {
}
创建Controller类:

java
深色版本
import com.example.demo.entity.TestPayRecord;
import com.example.demo.service.TestPayRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PaymentController {

    @Autowired
    private TestPayRecordService TestPayRecordService;

    @PostMapping("/payment")
    public String createPayment(@RequestBody TestPayRecord record) {
        TestPayRecordService.save(record);
        return "Payment record created successfully";
    }
}
8. 配置数据源
确保你在application.properties或application.yml中正确配置了数据源:

properties
深色版本
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis-Plus配置
mybatis-plus.type-aliases-package=com.example.demo.entity
mybatis-plus.mapper-locations=classpath:mapper/*.xml
9. 启动应用
启动Spring Boot应用,并使用Postman或其他工具发送POST请求来测试插入功能:

json
深色版本
{
    "requestNo": "123456",
    "cardNumber": "1234567890123456",
    "cardPhone": "13800000000"
}
这样,cardNumber和cardPhone字段在插入数据库之前会被自动加密。


http://www.ppmy.cn/devtools/127508.html

相关文章

MySQL【知识改变命运】10

联合查询 0.前言1.联合查询在MySQL里面的原理2.练习一个完整的联合查询2.1.构造练习案例数据2.2 案例&#xff1a;⼀个完整的联合查询的过程2.2.1. 确定参与查询的表&#xff0c;学⽣表和班级表2.2.2. 确定连接条件&#xff0c;student表中的class_id与class表中id列的值相等2.…

【c++篇】:解析c++类--优化编程的关键所在(一)

文章目录 前言一.面向过程和面向对象二.c中的类1.类的引入2.类的定义3.类的封装和访问限定符4.类的作用域5.类的实例化6.类对象模型 三.this指针1.this指针的引出2.this指针的特性3.C语言和c实现栈Stack的对比 前言 在程序设计的广袤宇宙中&#xff0c;C以其强大的功能和灵活性…

Vscode 插件开发 - TreeView

树状视图很多插件都可能用到&#xff0c;通常作为一个简单的列表使用&#xff0c;比如管理项目依赖、展示搜索结果。那么 Vscode 的 TreeView 具体怎么玩呢&#xff1f; 基础操作 1.创建视图 在 package.json 的 contributes.views 节点下定义视图&#xff1a; {"name…

SqlDbx连接oracle(可用)

解压SqlDbx.zip,将SqlDbx放到C:盘根目录 1.Path里面增加&#xff1a;C:\SqlDbx Path是为了找tnsnames.ora 2.增加系统变量&#xff1a;ORACLE_HOME&#xff0c;路径&#xff1a;C:\SqlDbx ORACLE_HOME是为了找oci.dll 3.用sqlDbx查询时&#xff0c;如果出现中文乱码&#xf…

【Vue.js】vue2 项目在 Vscode 中使用 Ctrl + 鼠标左键跳转 @ 别名导入的 js 文件和 .vue 文件

js 文件跳转 需要安装插件 Vetur 然后需要我们在项目根目录下添加 jsconfig.json 配置&#xff0c;至于配置的作用&#xff0c;可以参考我的另外一篇博客&#xff1a; 【React 】react 创建项目配置 jsconfig.json 的作用 它主要用于配置 JavaScript 或 TypeScript 项目的根…

Java五子棋小游戏

这个代码是简单的五子棋代码&#xff0c;下一个是进阶版的&#xff0c;可以看看&#xff0c;从简单开始上手 第一步&#xff1a;创建项目 打开你的IDE&#xff08;如Eclipse、IntelliJ IDEA等&#xff09;。创建一个新的Java项目。在项目中创建一个新的Java类&#xff0c;命名…

TypeScript中 interface接口 type关键字 enum枚举类型

type interface总是傻傻分不清~~~ Type Aliases (type) type 关键字用于为类型定义一个别名。这可以是基本类型、联合类型、元组、数组、函数等。type 定义的类型在编译后的 JavaScript 代码中会被移除&#xff0c;不会留下任何运行时的代码。 //联合类型 type StringOrNumbe…

4、.Net 快速开发框架:DncZeus - 开源项目研究文章

DncZeus 是一个基于 ASP.NET Core 和 Vue.js 的前后端分离的通用后台管理系统框架&#xff0c;其愿景是成为一个易于使用且功能丰富的 .NET Core 通用后台权限管理模板系统基础框架。项目名称 "DncZeus" 由 "Dnc"(.NET Core 的缩写)和 "Zeus"(古…