Mysql 解密函数:
SELECT AES_DECRYPT(UNHEX('*****'),'*****')
Java 代码
public class AesTools {
private AesTools() {}
public static String encrypt(String content, String key) {
try {
if (StringUtils.isNotBlank(content) && StringUtils.isNotBlank(key)) {
SecretKey aesKey = generateMySQLAESKey(strKey, "ASCII");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
byte[] cipherBytes = cipher.doFinal(contentBytes);
return Hex.encodeHexString(cipherBytes).toUpperCase();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
public static String decrypt(String content, String key) {
try {
if (StringUtils.isNotBlank(content) && StringUtils.isNotBlank(key)) {
SecretKey aesKey = generateMySQLAESKey(key, "ASCII");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
byte[] contentBytes = Hex.decodeHex(content.toCharArray());
byte[] cipherBytes = cipher.doFinal(contentBytes);
return new String(cipherBytes, StandardCharsets.UTF_8);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) {
try {
final byte[] keyBytes = new byte[16];
int i = 0;
for (byte b : key.getBytes(encoding))
keyBytes[i++ % 16] ^= b;
return new SecretKeySpec(keyBytes, "AES");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static ArrayList<List<Integer>> splitArray(ArrayList<Integer> arrayList, int subNum) {
int counter = arrayList.size() % subNum == 0 ? arrayList.size() / subNum : arrayList.size() / subNum + 1;
ArrayList<List<Integer>> arrayLists = new ArrayList<>();
for(int i = 0; i < counter; i++) {
int index = i * subNum;
List<Integer> tempList = new ArrayList<>();
int j = 0;
while(j < subNum && index < arrayList.size()) {
tempList.add(arrayList.get(index++));
j++;
}
arrayLists.add(tempList);
}
return arrayLists;
}
public static void main(String[] args) {
String value = "******";
String key = "*******";
String content = encrypt(value, key);
System.out.println("加密后:" + content);
System.out.println("解密后:" + decrypt(content, key));
}
}