为了保护用户隐私,我们需要对数据库用户关键数据,入库加密,取出来解密。为了我们系统自身的安全数据库连接用户名和密码都要加解密

1、数据库连接加解密

1.1、数据库连接配置

####################################
### DB
####################################
#durid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false#####################################
#### DB
####################################
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/hlj_demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
spring.datasource.druid.username=GCBeAUOZNANpmXfIUPO42qx/dQP80Lae3BI7ABxQN2AzWhgQAG+S6Dhe
spring.datasource.druid.password=GCAfE1p20be+BX5TZsVlFe1/T1bQ+f2IhnjqOQKe7CJT7xgQ8YOQrf7U
#####################################是否需要数据连接加密
spring.datasource.encrypt=true

1.2、Java数据库连接

package com.fintech.confin.web.config;import com.alibaba.druid.pool.DruidDataSource;
import com.fintech.confin.sensitivity.KeycenterUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;/*** @author HealerJean* @ClassName DateSourceConfig* @date 2020/4/9  10:43.* @Description*/
@Configuration
public class DateSourceConfig {@Value("${spring.datasource.druid.driver-class-name}")private String driverClassName;@Value("${spring.datasource.druid.url}")private String dbUrl;@Value("${spring.datasource.druid.username}")private String username;@Value("${spring.datasource.druid.password}")private String password;@Value("${spring.datasource.druid.initialSize}")private int initialSize;@Value("${spring.datasource.druid.minIdle}")private int minIdle;@Value("${spring.datasource.druid.maxActive}")private int maxActive;@Value("${spring.datasource.druid.maxWait}")private int maxWait;@Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")private int timeBetweenEvictionRunsMillis;@Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")private int minEvictableIdleTimeMillis;@Value("${spring.datasource.druid.validationQuery}")private String validationQuery;@Value("${spring.datasource.druid.testWhileIdle}")private boolean testWhileIdle;@Value("${spring.datasource.druid.testOnBorrow}")private boolean testOnBorrow;@Value("${spring.datasource.druid.testOnReturn}")private boolean testOnReturn;@Value("${spring.datasource.encrypt}")private boolean encrypt;@Bean(name = "dataSource")public DataSource dataSource(KeycenterUtils keycenterUtils) {DruidDataSource datasource = new DruidDataSource();datasource.setDriverClassName(driverClassName);datasource.setUrl(dbUrl);if (encrypt) {datasource.setUsername(keycenterUtils.decrypt(username));datasource.setPassword(keycenterUtils.decrypt(password));} else {datasource.setUsername(username);datasource.setPassword(password);}datasource.setInitialSize(initialSize);datasource.setMinIdle(minIdle);datasource.setMaxActive(maxActive);datasource.setMaxWait(maxWait);datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);datasource.setValidationQuery(validationQuery);datasource.setTestWhileIdle(testWhileIdle);datasource.setTestOnBorrow(testOnBorrow);datasource.setTestOnReturn(testOnReturn);return datasource;}}

2、数据库字段加解密

2.1、KeyCenterUtils:加解密工具类

package com.healerjean.proj.config.keycenter.one;import org.springframework.stereotype.Service;import java.util.Base64;/*** @author HealerJean* @ClassName AES* @date 2020/4/9  14:28.* @Description*/
@Service
public class KeyCenterUtils {/*** 自己写加密逻辑*/public  String encrypt(String src) {try {String result = Base64.getEncoder().encodeToString(src.getBytes("UTF-8"));return result;} catch (Exception e) {throw new RuntimeException("encrypt fail!", e);}}/*** 自己写解密逻辑*/public  String decrypt(String src) {try {byte[] asBytes = Base64.getDecoder().decode(src);String result = new String(asBytes, "UTF-8");return result;} catch (Exception e) {throw new RuntimeException("decrypt fail!", e);}}}

2.2、CustomTypeHandler数据库字段加解密控制器

package com.healerjean.proj.config.keycenter.one;/*** @author HealerJean* @ClassName AESTypeHandler* @date 2020/4/9  14:27.* @Description*/import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class CustomTypeHandler<T> extends BaseTypeHandler<T> {@Autowiredprivate KeyCenterUtils keyCenterUtils;public CustomTypeHandler() {}@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {ps.setString(i, this.keyCenterUtils.encrypt((String)parameter));}@Overridepublic T getNullableResult(ResultSet rs, String columnName) throws SQLException {String columnValue = rs.getString(columnName);//有一些可能是空字符return StringUtils.isBlank(columnValue) ? (T)columnValue : (T)this.keyCenterUtils.decrypt(columnValue);}@Overridepublic T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {String columnValue = rs.getString(columnIndex);return StringUtils.isBlank(columnValue) ? (T)columnValue : (T)this.keyCenterUtils.decrypt(columnValue);}@Overridepublic T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {String columnValue = cs.getString(columnIndex);return StringUtils.isBlank(columnValue) ? (T)columnValue : (T)this.keyCenterUtils.decrypt(columnValue);}
}

2.3、Handle的使用

2.3.1、数据层实体类注解

package com.healerjean.proj.data.entity;import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.healerjean.proj.config.keycenter.one.CustomTypeHandler;
import lombok.Data;import java.util.Date;@Data
@TableName(autoResultMap = true) //有了这个BaseMapper查询的结果才能解密
public class User {private Long id;private String name;private Integer age;//有了这个数据库BaseMapper插入的时候才能加密@TableField(typeHandler = CustomTypeHandler.class)private String telPhone;@TableField(typeHandler = CustomTypeHandler.class)private String email;private Date createDate;private Date createTime;
}

2.3.2、自定义sql查询的配置

如果不是mybatisPlus的 BaseMapper内部的方法,则需要我们自己放入我们自定义的typeHandler

@Results({@Result(column = "email", property = "email", typeHandler = CustomTypeHandler.class),@Result(column = "tel_phone", property = "telPhone", typeHandler = CustomTypeHandler.class)})
@Select("select * from user where id = #{id}")
List<User> selectDncryptList(Long id);

2.3.3、测试

User中的数据都是正常的 。不是密文。因为我们只讲入库的数据设置了密文。并不会改变User对象本身


@Test
public void encrypt(){List<User> users = null ;//插入数据User user = new User();user.setName("name");user.setAge(12);user.setEmail("healerjean@gmail.com");user.setTelPhone("18841256");userMapper.insert(user);//更新user.setEmail("12456@gmail.com");userMapper.updateById(user);//查询 :列表查询users = userMapper.selectList(null);System.out.println(users);//查询 :根据Id查询User user1 = userMapper.selectById(user.getId());System.out.println(user1);//自定义sql查询users  = userMapper.selectDncryptList(user.getId());System.out.println(users);}

2.4、敏感字段查询:(需要精确查询)

因为数据库中是密文,所以查询的时候,需要我们先加密后才能查

// 根据敏感字段查询
Wrapper<User> userWrapper = new QueryWrapper<User>().lambda().select(User::getEmail).eq(User::getEmail, keyCenterUtils.encrypt("healerjean@gmail.com"));users  = userMapper.selectList(userWrapper);
System.out.println(users);

ps:介绍一个mybatis操作数据库时的一个类似黑匣子的东西,TypeHandler

闲聊:
      在我们平常开发操作数据库时,查询、插入数据等操作行为,有时会报数据类型不匹配异常,就可以得知数据的类型是不唯一的必然是多种不同的数据类型。并且我们必须要明确的一点就是java作为一门编程语言有自己的数据类型,数据库也是有自己的数据类型的。

jdbc数据类型:org.apache.ibatis.type.JdbcType 此枚举就是所有的数据库支持类型
java数据类型:int、long、string、…

一定要分清,例如java重的date数据插入到数据库中,应该是已经转换成了数据库的某种类型,必然跟java已经没有关系了。中间有一些我们看不见的操作做了数据处理。
        假设此时的java类型与数据库数据类型是一样的,哪么其他语言中的日期数据插入数据库时又该怎么解释,例如C#操作数据库存入时间类型,C#与java肯定没有关系吧。所以每种语言与数据库之间有种数据类型关系对应。

思考:

  1. 因为java与数据库各自有数据类型,所以在将java数据存入数据库前中间是否有其他操作,是我们看不见的,不然java数据怎么知道自己与哪个jdbc数据类型匹配?

    答:mybatis框架为每种数据类型做了默认的关系对应,BaseTypeHandler的所有实现类,就是来做这些处理的。

  2. 例如:java中的date插入数据库时是jdbc哪种类型,怎么就是这种类型? 中间具体有什么操作?
    答:DateTypeHandler就是来解决date数据类型的处理。

源码查看: 看一下源码中具体怎么处理date数据类型的。

先看一下接口:

//此接口作用是用于指定jdbc与java的数据类型间对应关系处理。
public interface TypeHandler<T> {// 保存操作,数据入库之前时数据处理void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;//下面三个则是,从数据库加载数据后,vo对象封装前的数据处理T getResult(ResultSet rs, String columnName) throws SQLException;T getResult(ResultSet rs, int columnIndex) throws SQLException;T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}
然后BaseTypeHandler 实现了TypeHandler 接口

MybatisPlus实现数据库加解密相关推荐

  1. 基于Java的SQL Server数据库加解密系统设计与实现

    目 录 摘 要 1 ABSTRACT 2 第1章 绪论 3 1.1 数据库加解密系统开发背景 3 1.2 国内外现状 3 1.3 本文的主要工作 4 1.4 论文的组织结构 4 第2章 数据库加密的基 ...

  2. 三级等保之数据库加解密技术方案预言分析篇(一)

    系列文章目录 三级等保之数据库加解密技术方案预言分析篇(一) 三级等保之SpringBootMybatis数据安全(二) 数据库内容加密后支持模糊搜索功能(三) 文章目录 系列文章目录 前言 一.项目 ...

  3. Android数据库加解密逆向分析(三)——微信数据库密码破解

    接着上一篇文章,在上一篇文章中我们通过对Line数据库加密的逆向分析,了解到了对要写入到数据库中的数据加密,读取时再将读取出的数据解密这种Android上的数据库加密方式.这篇文章来通过介绍对微信数据 ...

  4. 通过T-SQL语句实现数据库加解密功能

    CREATE TABLE [dbo].[Users] ([U_nbr] NVARCHAR(20) NOT NULL PRIMARY KEY,[Pwd] nvarchar(MAX) )--加密 DECL ...

  5. boot数据加解密 spring_SpringBoot 集成 Jasypt 对数据库加密以及踩坑

    前言 密码安全是非常重要的,因此我们在代码中往往需要对密码进行加密,以此保证密码的安全 加依赖 <!-- jasypt --> <dependency><groupId& ...

  6. Druid之——连接池自定义数据库密码加解密的实现

    转载请注明出处:https://blog.csdn.net/l1028386804/article/details/79920338 Druid是阿里巴巴开发的一款数据库连接池,它支持对数据库密码的加 ...

  7. Druid连接池自定义数据库密码加解密的实现

    Druid的功能 1.替换DBCP和C3P0.Druid提供了一个高效.功能强大.可扩展性好的数据库连接池. 2.可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能 ...

  8. Druid对数据库配置进行加解密

    ** 把数据库用户名和密码写在配置文件中,不安全,这里用阿里的druid数据库连接池对指定配置属性进行自定义加解** 这里对springMVC 框架的项目做简单介绍,下边简单介绍下配置: * 第一步* ...

  9. 敏感词加解密与隐位处理

    1.隐位处理 使用方法 在返回对象实体中增加注解 @Sensitive(strategy = SensitiveStrategy.PHONE) private String phone; 请求返回方式 ...

  10. Mybatis 字段加解密

    需求场景: 当数据库中保存的部分数据需要加密,页面需要解密正常显示.比如手机号码,email,身份证号码等隐私信息.项目开发中对表字段加密解密,业务代码无需关心加解密环节. 解决方案 使用mybati ...

最新文章

  1. oracle数据库访问order by不起作用分析
  2. 0909初学编译原理
  3. SD初始化过程以及Cmd解析
  4. Page9:结构分解以及系统内部稳定和BIBO稳定概念及其性质[Linear System Theory]
  5. .NET进行客户端Web开发又一利器 - Ant Design Blazor
  6. epub 阅读器_全球与中国EPUB阅读器市场深度调研分析报告
  7. linux自动截屏脚本,Android实现自动截图脚本
  8. “打工皇帝”唐骏借收购重返IT
  9. 10款滑动门代码_jquery 滑动门_js滑动门_tab滑动门_jquery 选项卡_js选项卡_tab选项卡效果(二)
  10. nginx请求转发配置
  11. CISP 考试教材《第 2 章 知识域:网络安全监管》知识整理
  12. ant design java_SpringBoot整合Ant Design Pro进行部署
  13. buff系统 游戏中_arpg游戏的技能系统和buff系统的一种实现
  14. 骑行318、 2016.7.17
  15. Skype for Business Server-呼叫质量仪表板(一)安装与配置
  16. oracle静默安装报错,静默安装Oracle11gR2 [FATAL] [INS-32015]报错
  17. 如何用手机快速制作好看的二维码
  18. ImageIO.read(URL) 返回 null
  19. Revit模型带材质导入到Unity3D软件
  20. 基于微信电影院购票小程序系统设计与实现 开题报告

热门文章

  1. 2022年最新河南建筑安全员模拟题库及答案
  2. 利用混合高斯模型实现视频中运动目标与背景的分离
  3. php notice错误是什么意思,PHP中Notice错误常见解决方法
  4. java.lang.ArithmeticException: Division undefined
  5. python运行代码无反应_linux执行python命令后没有反应,不打印日志信息
  6. GUI输出中文为乱码解决方式
  7. BigData:根据最新2018.07.19《财富》世界500强榜单进行大数据分析
  8. Java图形用户界面(容器)
  9. android 刷机 zip,ZipInstaller(ZIP刷机神器)
  10. 每日一题之 hiho1542 无根树变有根树