From 41d89b8acac121527d4488f56285faca27de9269 Mon Sep 17 00:00:00 2001 From: chenjiahe <763432473@qq.com> Date: 星期四, 06 一月 2022 19:35:22 +0800 Subject: [PATCH] 添加Mysql数据库的AES加解密方法 --- src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java | 73 ++++++++++++++++++++++++++++++++++++ 1 files changed, 73 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java b/src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java new file mode 100644 index 0000000..2905210 --- /dev/null +++ b/src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java @@ -0,0 +1,73 @@ +package com.hx.util.mysql.aes; + +import com.hx.util.StringUtils; +import org.apache.commons.codec.binary.Hex; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; + +/** + * mybatis鏁版嵁搴撶殑AES_ENCRYPT锛堝姞瀵嗭級鍜孉ES_DECRYPT锛堣В瀵嗭級 + * mybatis鏁版嵁搴撶殑HEX锛堝姞澹筹級UNHEX锛堣В澹筹級 + * @author CJH + * @Date 2021-01-06 + */ +public class MysqlHexAes { + + + public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) { + try { + final byte[] finalKey = new byte[16]; + int i = 0; + for(byte b : key.getBytes(encoding)) { + finalKey[i++%16] ^= b; + } + return new SecretKeySpec(finalKey, "AES"); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + /**AES 瑙e瘑 + * @param data 闇�瑕佽В瀵嗙殑鏁版嵁 + * @param aesKey 绉橀挜 + * @param encoding 缂栫爜锛屼笉濉粯璁TF-8 + * @return + * @throws Exception + */ + public static String decrpt(String data,String aesKey,String encoding) throws Exception { + if(StringUtils.isEmpty(encoding)){ + encoding = "UTF-8"; + } + // Decrypt + final Cipher decryptCipher = Cipher.getInstance("AES"); + decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); + return new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray()))); + } + + /**AES鍔犲瘑 + * @param data 闇�瑕佽В瀵嗙殑鏁版嵁 + * @param aesKey 绉橀挜 + * @param encoding 缂栫爜锛屼笉濉粯璁TF-8 + * @return + * @throws Exception + */ + public static String encrpt(String data,String aesKey,String encoding) throws Exception { + if(StringUtils.isEmpty(encoding)){ + encoding = "UTF-8"; + } + // Encrypt + final Cipher encryptCipher = Cipher.getInstance("AES"); + encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesKey, encoding)); + char[] code = Hex.encodeHex(encryptCipher.doFinal(data.getBytes(encoding))); + StringBuilder builder = new StringBuilder(); + for (char d : code) { + builder.append(d); + } + String strning = builder.toString(); + return strning; + + } + +} -- Gitblit v1.8.0