系列文章
簡介
本文以用戶表為例,介紹如何在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)
- 動態(tài)SQL方式
'${AES_KEY}'
UserMapper.xml加解密username等字段
- 加密過程:先將字段轉化為16進制格式的字符串表示,再進行AES加密。
- 解密過程:先將字段使用加密時的key進行解密,再將中間值從16進制字符串還原為原來的值。
<sql id="decryptGetColumns">
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
</sql>
<!-- 添加用戶,加密字段-->
<insert id="addUser" parameterType="com.scut.emos.entity.User">
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});
</insert>
<!-- 查詢用戶,解密字段-->
<select id="getUserByUserId" parameterType="Long" resultType="com.scut.emos.entity.User">
SELECT
<include refid="decryptGetColumns"/>
FROM user_t
WHERE user_id = #{userId}
LIMIT 1
</select>
<select id="getUserByUsername" parameterType="String" resultType="com.scut.emos.entity.User">
SELECT
<include refid="decryptGetColumns"/>
FROM user_t
WHERE username = hex(AES_ENCRYPT(#{username}, '${AES_KEY}'))
LIMIT 1;
</select>
參考文獻
本文作者: seawish
版權聲明: 本博客所有文章除特別聲明外,均采用 CC BY-NC-SA 3.0 許可協(xié)議。轉載請注明出處!