mysql自带数据库用户加密方法_Mybatis数据库字段加解密1-使用mysql自带加密方法...

本文介绍了如何在Mybatis的mapper.xml中利用MySQL的AES加密方法对用户表的敏感字段如username、nickname、phone和email进行加解密操作。通过设置SqlSession全局变量并定义加密解密过程,实现了数据的安全存储和检索。
摘要由CSDN通过智能技术生成

系列文章

简介

本文以用户表为例,介绍如何在Mybatis的mapper.xml中对MySql数据库表的字段进行加解密。主要包括设置和获取全局变量和加密方法使用。

定义SqlSession全局变量

// import org.apache.ibatis.session.Configuration

final String key = "AES_KEY"; // sqlSession中全局属性kv中的key

String aesKey = "aesKey"; // aes加密使用的key

Configuration configuration = new Configuration(environment);

configuration.setMapUnderscoreToCamelCase(true); //数据库中下划线方式的键将映射到java pojo中的驼峰命名法的属性。如user_id映射为userId。

// 将全局变量存入sqlSession

configuration.getVariables().put(key, aesKey);

...

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

获取全局变量

java方式

sqlSessionFactory.getConfiguration().getVariables().get(key)

动态SQL方式

'${AES_KEY}'

UserMapper.xml加解密username等字段

加密过程:先将字段转化为16进制格式的字符串表示,再进行AES加密。

解密过程:先将字段使用加密时的key进行解密,再将中间值从16进制字符串还原为原来的值。

user_id, password,

AES_DECRYPT(unhex(username), '${AES_KEY}') username,

AES_DECRYPT(unhex(nickname), '${AES_KEY}') nickname,

AES_DECRYPT(unhex(phone), '${AES_KEY}') phone,

AES_DECRYPT(unhex(email), '${AES_KEY}') email,

register_time, source, local_lang, account_status, country, province, city, sex, age

INSERT INTO user_t(user_id, username, password, nickname, phone, email, register_time, source, local_lang,

account_status, country, province, city, sex, age)

VALUES (#{userId},

hex(AES_ENCRYPT(#{username}, '${AES_KEY}')),

#{password},

hex(AES_ENCRYPT(#{nickname}, '${AES_KEY}')),

hex(AES_ENCRYPT(#{phone}, '${AES_KEY}')),

hex(AES_ENCRYPT(#{email}, '${AES_KEY}')),

#{registerTime}, #{source}, #{localLang}, #{accountStatus}, #{country}, #{province}, #{city}, #{sex}, #{age});

SELECT

FROM user_t

WHERE user_id = #{userId}

LIMIT 1

SELECT

FROM user_t

WHERE username = hex(AES_ENCRYPT(#{username}, '${AES_KEY}'))

LIMIT 1;

参考文献

本文作者: seawish

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值