加密:将明文信息改变为难以读取的密文内容。
解密:将密文内容转化为原来数据。
分类
相关阅读:
说明
- 数据库存储密文字段,内存可见为明文信息
- 可设定字段保存值支持 整体加密(仅可全部匹配查询)、模糊加密(支持模糊查询)
- 相关做法: 数据库隐私字段加密以及加密后的数据如何进行模糊查询? - 业余草
实现做法:常规二,对明文数据进行分词组合,将分词组合的结果集分别进行加密存储,查询时通过 column LIKE '%partial%'
分组规则:按固定长度,根据4位英文字符(半角),2个中文字符(全角)为一个检索条件
分组示例:ningyu1 使用4个字符为一组的加密方式 -> ning + ingy + ngyu + gyu1
整体加密数据库字段长度与保存值长度对应(需要额外存储一个标识符)
| 数据库字段长度 | 字符长度 |
|---|---|
| varchar(49) | 12个中文字符、36个ascii字符 |
| varchar(97) | 24个中文字符、72个ascii字符、3个ascii字符+23个中文字符、68个ascii字符+1个中文字符 |
| varchar(197) | 49个中文字符、145个ascii字符、3个ascii字符+48个中文字符 、 142个ascii字符+1个中文字符 |
| varchar(253) | 63个中文字符、189个ascii字符 、3个ascii字符+62个中文字符 、 186个ascii字符+1个中文字符 |
模糊加密数据库字段长度与保存值长度对应(4个字节加密一次大致对应8个字符+1个标识符),根据4位英文字符(半角),2个中文字符(全角)为一个检索条件
| 数据库字段长度 | 字符长度 |
|---|---|
| varchar(99) | 12个中文字符、14个ascii字符 |
| varchar(198) | 23个中文字符、25个ascii字符 |
| varchar(252) | 29个中文字符、31个ascii字符 |
INSERT VALUE、UPDATE ENTITY、SELECT RESULT
只对数据库和程序之间的数据转换,查询条件不会调用。
整体加密类型处理器
使用示例:
1. MyBatis-Plus 注解(自动生产 ResultMap ,存在场景不生效)
@TableField(typeHandler = OverallCryptoTypeHandler.class)
2. 自定义 ResultMap 配置
<result column="phone" property="phone" typeHandler="cn.eastx.practice.demo.crypto.config.mp.OverallCryptoTypeHandler" />
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
/*
对非null参数值进行加密,需要通过实体类处理方可,支持 INSERT/UPDATE ENTITY
当前处理 INSERT ENTITY,UPDATE ENTITY 会先通过拦截器处理
因为拦截器修改元数据将导致实体类属性值产生变更,所以实体类还是由 TypeHandler 来进行处理
*/
ps.setString(i, CryptoDataUtil.overallEncrypt(parameter));
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 对可为null的结果进行解密
return CryptoDataUtil.decrypt(rs.getString(columnName));
}
模糊加密类型处理器
注意:根据4位英文字符(半角),2个中文字符(全角)为一个检索条件,如果字段值较少查询可能存在问题
使用示例:
1. MyBatis-Plus 注解(自动生产 ResultMap ,存在场景不生效)
@TableField(typeHandler = FuzzyCryptoTypeHandler.class)
2. 自定义 ResultMap 配置
<result column="phone" property="phone" typeHandler="cn.eastx.practice.demo.crypto.config.mp.FuzzyCryptoTypeHandler" />
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
/*
对非null参数值进行加密,需要通过实体类处理方可,支持 INSERT/UPDATE ENTITY
当前处理 INSERT ENTITY,UPDATE ENTITY 会先通过拦截器处理
因为拦截器修改元数据将导致实体类属性值产生变更,所以实体类还是由 TypeHandler 来进行处理
*/
ps.setString(i, CryptoDataUtil.fuzzyEncrypt(parameter));
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 对可为null的结果进行解密
return CryptoDataUtil.decrypt(rs.getString(columnName));
}
注:目前仅支持简单查询处理,复杂查询可能存在问题。
自定义字段注解 CryptoCond.java
replacedColumn() 替换 SQL 查询条件中的字段名encryption() 对 SQL 中条件值、参数值进行加密,支持两种方式(整体匹配、模糊匹配)User.java自定义 MyBatis 拦截器
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
// 支持处理 SELECT、UPDATE、DELETE
boolean canHandler = Stream.of(SqlCommandType.SELECT, SqlCommandType.UPDATE,
SqlCommandType.DELETE)
.anyMatch(item -> item.equals(mappedStatement.getSqlCommandType()));
if (canHandler && !getIntercept()) {
clearIntercept();
return invocation.proceed();
}
clearIntercept();
// 判断是否有参数需要处理
BoundSql boundSql = statementHandler.getBoundSql();
if (Objects.isNull(boundSql.getParameterObject())) {
return invocation.proceed();
}
// 获取自定义注解,通过 MapperID 获取到 Mapper 对应的实体类,获取实体类所有注解字段与注解对应 Map
Map<String, CryptoCond> condMap = mapEntityFieldCond(mappedStatement.getId());
if (CollectionUtil.isNotEmpty(condMap)) {
replaceHandle(mappedStatement.getConfiguration(), condMap, boundSql);
}
return invocation.proceed();
}
// 替换数据处理
private void replaceHandle(Configuration configuration, Map<String, CryptoCond> condMap,
BoundSql boundSql) {
String sql = boundSql.getSql();
Pair<String, List<SqlCondOperation>> sqlPair = SqlUtil.getSqlCondOperationPair(sql);
List<SqlCondOperation> operationList = sqlPair.getValue();
if (CollectionUtil.isEmpty(operationList)) {
return;
}
sql = sqlPair.getKey();
MetaObject paramMetaObject = configuration.newMetaObject(boundSql.getParameterObject());
List<ParameterMapping> mappings = boundSql.getParameterMappings();
int mappingStartIdx = 0;
int addIdxLen = 0;
for (SqlCondOperation operation : operationList) {
String condStr = operation.getOriginCond();
int prepareNum = SqlUtil.countPreparePlaceholder(condStr);
CryptoCond ann = condMap.get(operation.getColumnName());
if (Objects.nonNull(ann)) {
// 替换查询条件参数中的列名
if (StrUtil.isNotBlank(ann.replacedColumn()) && !operation.checkSetCond()) {
sql = operation.replaceSqlCond(sql, addIdxLen,
operation.getColumnName(), ann.replacedColumn());
}
// 替换属性值为加密值
if (prepareNum == 0) {
// 存在非预编译语句条件,直接替换 SQL 条件值
String propVal =
String.valueOf(paramMetaObject.getValue(operation.getColumnName()));
String useVal = getCryptoUseVal(ann, propVal);
sql = operation.replaceSqlCond(sql, addIdxLen, propVal, useVal);
} else {
// 预编译语句条件通过替换条件值处理
for (int i = 0; i < prepareNum; i++) {
String propName = mappings.get(mappingStartIdx + i).getProperty();
if (!propName.startsWith("et.")) {
// 非实体类属性进行值替换,实体类属性通过 TypeHandler 处理
String propVal = String.valueOf(paramMetaObject.getValue(propName));
paramMetaObject.setValue(propName, getCryptoUseVal(ann, propVal));
}
}
}
}
mappingStartIdx += prepareNum;
addIdxLen += operation.getOriginCond().length() - condStr.length();
}
ReflectUtil.setFieldValue(boundSql, "sql", sql);
}
测试
IUserService.javaUserServiceTest.java
使用问题
TypeHandler 不起效
UserMapper.xml<!-- 使用自定义SQL时,对于加密处理需要使用ResultMap作为返回对象,否则对解析成实际数据会存在问题 -->
<resultMap id="BaseResultMap" type="cn.eastx.practice.demo.crypto.pojo.po.User">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="password" property="password" />
<result column="salt" property="salt" />
<result column="phone" property="phone" typeHandler="cn.eastx.practice.demo.crypto.config.mp.OverallCryptoTypeHandler" />
<result column="email" property="email" typeHandler="cn.eastx.practice.demo.crypto.config.mp.FuzzyCryptoTypeHandler" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
</resultMap>
@TableName(autoResultMap = true) ,自动构建 ResultMap加密后解密数据乱码
CryptoCondInterceptor 不起效
@CryptoCond ,示例:User.java@Data
@TableName(value = "crypto_user", autoResultMap = true)
public class User {
/**
* 用户表主键ID
*/
private Long id;
/**
* 用户名
*/
private String name;
/**
* 加密后的密码,MD5加盐
*/
private String password;
/**
* 加密密码使用的盐
*/
private String salt;
/**
* 手机号码,整体加密
*/
@TableField(typeHandler = OverallCryptoTypeHandler.class)
@CryptoCond(encryption = CryptoCond.EncryptionEnum.DEFAULT_OVERALL)
private String phone;
/**
* 邮箱,模糊加密
*/
@TableField(typeHandler = FuzzyCryptoTypeHandler.class)
@CryptoCond(encryption = CryptoCond.EncryptionEnum.DEFAULT_FUZZY)
private String email;
/**
* 创建时间
*/
@TableField(fill = INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = INSERT_UPDATE)
private LocalDateTime updateTime;
}
public interface UserMapper extends BaseMapper<User>MySQL 异常
参考
demo 地址:https://github.com/EastX/java-practice-demos/tree/main/demo-crypto
推荐阅读:
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD
本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01 客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02 数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit
文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co
我正在尝试在Rails上安装ruby,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf