Spring Boot + MyBatis + Jasypt 实现敏感数据加密存储方案
一、前言
在当今数据驱动的时代,数据安全已成为系统设计中不可忽视的重要环节。特别是对于用户隐私数据如手机号、身份证号、银行卡号等敏感信息,如何在数据库中安全存储是每个开发者必须面对的问题。本文将详细介绍如何在 Spring Boot + MyBatis 技术栈中,利用 Jasypt 实现敏感数据的自动加解密功能。
二、技术选型
1. Jasypt 简介
Jasypt(Java Simplified Encryption)是一个简单易用的 Java 加密库,具有以下特点:
- 支持多种加密算法(PBE、AES、RSA等)
- 与 Spring Boot 无缝集成
- 提供配置文件加密功能
- 支持 Hibernate 和 MyBatis 数据加密
2. 为什么选择 Jasypt?
相比自己实现加密方案,Jasypt 具有以下优势:
- 成熟的加密算法实现
- 丰富的集成方案
- 活跃的社区支持
- 简单的配置方式
三、实现方案
1. 基础环境搭建
1.1 添加依赖
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- Jasypt Starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- 其他依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
1.2 配置文件
application.yml
配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db?useSSL=false
username: root
password: ENC(加密后的密码) # 使用Jasypt加密的数据库密码
driver-class-name: com.mysql.cj.jdbc.Driver
jasypt:
encryptor:
password: ${
JASYPT_ENCRYPTOR_PASSWORD:defaultKey} # 推荐使用环境变量
algorithm: PBEWithHMACSHA512AndAES_256
iv-generator-classname: or