/**
* Password based encryption using AES with MySql style key generation.
* @param toEncrypt Unencrypted byte array.
* @param key A KeyParameter generated with the getMySqlAESPasswdKey() method.
* @return Encrypted byte array.
* @throws InvalidCipherTextException If provided key cannot be used with this method on the provided data.
*/
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;
}
/**
* Password based decryption using AES with MySql style key generation.
* @param toDecrypt Encrypted byte array.
* @param key A KeyParameter generated with the getMySqlAESPasswdKey() method.
* @return Unencrypted byte array.
* @throws InvalidCipherTextException If provided key cannot be used with this method on the provided data.
*/
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);
}
/**
* Strip trailling zeros from the end of decrypted byte arrays.
* @param data Data to strip.
* @return Stripped data.
*/
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;
}