我知道aes加密需要在16個塊中,但我的印象是使用Cipher.getInstance("AES/ECB/PKCS5PADDING");
填充字節數組來實現這一點。我的代碼如下:當使用aes/ecb/pkcs5padding解密字節數組時,IllegalBlockSizeException
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;
}
主程序
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();
在path
該文件是使用在cipherutils.java的函數加密和寫入文件使用FileOutputStream.write
更新 - 我使用Gradle爲Android構建。
首先用硬編碼輸入單元測試你的方法:加密它並解密結果應該導致輸出等於輸入。完成之後,您會意識到加密和解密工作正常,並且問題出在您編寫和讀取文件的方式。 available()不會返回文件的長度。即使這樣做,你的數組也包含一個額外的字節。所以這沒有意義。 –
請不要使用ECB模式。它在語義上不安全。您應該至少使用CBC模式和隨機IV。充其量,你應該認證密文。這通常使用GCM等認證模式或通過HMAC運行密文(加密 - 然後MAC)來完成。 –
...或運行* IV *和密文雖然HMAC ... –