private 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 (Exception e) {
throw new RuntimeException(e);
}
}
public static String encryptMysql(String str, String aesKey) {
try {
final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 一定要用上第三个参数,设置一个随机数种子,否则在linux下某些情况加密的密文不一致
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(1L);
cipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(aesKey, "UTF-8"), secureRandom);
return Hex.encodeHexString(cipher.doFinal(str.getBytes("UTF-8"))).toUpperCase();
} catch (Exception e) {
log.error("encryptMysql error", e);
}
return null;
}
linux环境下加密密文不一致,这个问题导致有时候能和mysql加密匹配,有时候却不行,设置一个随机数种子就可以了
本文介绍了一种在 Linux 环境下使用 AES 对 MySQL 数据进行加密的方法,并解决了因 SecureRandom 导致的加密结果不一致的问题。通过设置 SecureRandom 的种子为固定值,确保了加密过程的稳定性和加密结果的一致性。

4045

被折叠的 条评论
为什么被折叠?



