I had to do this a few years ago using a BouncyCastle. As Allen Puzichβs answer says, two problems are mysql key generation and PKCS7 add-on. BouncyCastle will handle the add-on for you using the PaddedBufferedBlockCipher , but you will need to generate the key yourself. Here is the code for this:
public static KeyParameter getMySqlAESPasswdKey(String passwd, int keyLength) { byte[] pword = passwd.getBytes(); byte[] rawKey = new byte[keyLength/8]; int j = 0; for (int i = 0; i < pword.length; i++, j++) { if(j==rawKey.length) { j = 0; } rawKey[j] = pword[i]; } return new KeyParameter(rawKey); }
Note that the default keyLength for mysql is 128.
Using the above method to create a KeyParameter , you can complete encryption / decryption as follows.
public static byte[] mysqlAesPasswdEncrypt (byte [] toEncrypt, KeyParameter key) throws InvalidCipherTextException { BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESFastEngine()); cipher.init(true, key); byte[] result = new byte[cipher.getOutputSize(toEncrypt.length)]; int len = cipher.processBytes(toEncrypt, 0, toEncrypt.length, result, 0); cipher.doFinal(result, len); return result; } public static byte[] mysqlAesPasswdDecrypt (byte [] toDecrypt, KeyParameter key) throws InvalidCipherTextException { BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESFastEngine()); cipher.init(false, key); byte[] result = new byte[cipher.getOutputSize(toDecrypt.length)]; int len = cipher.processBytes(toDecrypt, 0, toDecrypt.length, result, 0); cipher.doFinal(result, len); return stripTrailingZeros(result); } public static byte[] stripTrailingZeros(byte[] data) { int lastData = data.length-1; for (int i = data.length-1; i >= 0; i--) { if(data[i]!=(byte)0) { lastData = i; break; } } byte[] data2 = new byte[lastData+1]; System.arraycopy(data, 0, data2, 0, lastData+1); return data2; }
source share