上一篇文章中说道数据加密分两种场景
分别是:
- 新上线业务
- 已上线业务
这篇我们对已上线业务进行模拟实验。
已上线业务改造
系统迁移前
建表语句和配置文件
CREATE TABLE `t_cipher_old` (
`id` bigint(20) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`pwd` varchar(100) DEFAULT NULL,
`mobile` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
为了模拟已经上线的业务,我们为表中造一些测试数据,并编写业务接口实现 CURD
然而需要在数据库表 t_user 里新增一个字段叫做 pwd_cipher,即 cipherColumn,用于存放密文数据,同时我们把 plainColumn 设置为 pwd,用于存放明文数据,而把 logicColumn 也设置为 pwd。
ALTER TABLE test.t_cipher_old ADD pwd_cipher varchar(100) NULL;
由于之前的代码 SQL 就是使用 pwd 进行编写,即面向逻辑列进行 SQL 编写,所以业务代码无需改动。 通过 Apache ShardingSphere,针对新增的数据,会把明文写到 pwd 列,并同时把明文进行加密存储到 pwd_cipher 列。 此时,由于 queryWithCipherColumn 设置为 false,对业务应用来说,依旧使用 pwd 这一明文列进行查询存储,却在底层数据库表 pwd_cipher 上额外存储了新增数据的密文数据
配置文件如下(本文只需要关注 encrypt
节点部分):
spring:
profiles:
include: common-local
shardingsphere:
datasource:
names: write-ds,read-ds-0
write-ds:
jdbcUrl: jdbc:mysql://mysql.local.test.glzhapp.com:23306/test?allowPublicKeyRetrieval=true&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: Qq2e66hxnNd9MdNc
connectionTimeoutMilliseconds: 3000
idleTimeoutMilliseconds: 60000
maxLifetimeMilliseconds: 1800000
maxPoolSize: 50
minPoolSize: 1
maintenanceIntervalMilliseconds: 30000
read-ds-0:
jdbcUrl: jdbc:mysql://mysql.local.test.read1.glzhapp.com:23306/test?allowPublicKeyRetrieval=true&useSSL=false&allowMultiQueries=true&serverTimezon