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加密匹配,有時候卻不行,設置一個隨機數種子就能夠了java