I understand that aes encryption needs to be in blocks of 16, but I was under the impression that using Cipher.getInstance("AES/ECB/PKCS5PADDING");
padded the byte array to achieve this. My code is below:
CipherUtils.java
private static byte[] key = {
0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79
};//"thisIsASecretKey";
public static byte[] EncryptByteArray(byte[] array)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return (cipher.doFinal(array));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static byte[] DecryptByteArray(byte[] array)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(array);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Main Program
fis = new FileInputStream(path);
toDecrypt = new byte[fis.available()+1];
int content;
int i = 0;
while ((content = fis.read()) != -1) {
// convert to byte and display it
toDecrypt[i] = (byte)content;
i += 1;
}
byte[] decryptedStr = CipherUtils.DecryptByteArray(toDecrypt);
FileOutputStream decryptedStream = new FileOutputStream(path);
decryptedStream.write (decryptedStr);
decryptedStream.close();
The file at path
was encrypted using the function in cipherutils.java and written to the file using FileOutputStream.write
Update- I'm building for Android using Gradle.
Managed to work something out using @JonSkeet's answer (thanks!) :
As he pointed out, I shouldn't have been using the available() method. There was also a much better & faster way to write to the file than iterating through each byte! As per the comments, I have also changed the encryption to CBC mode with a random IV.