在Android

时间:2015-08-11 17:23:45

标签: java android encryption aes badpaddingexception

首先,我在Java / Android中创建了一个小的加密/解密程序。没有什么特别的,这真的很基本,所以没有缓冲或任何东西。在那里使用了Iv和Salt我在文件的开头写了盐和iv(24个字节)。第一个版本能够对文件进行加密/解密,最后两个文件的二进制文件相同。

现在我试图不立即读取和处理整个文件,而是使用缓冲区(大小为1024字节)的单步执行。我在最后将cipher.doFinal更改为多个cipher.update和一个空cipher.doFinal

加密:

byte[] salt = {1, 2, 3, 4, 5, 6, 7, 8};
byte[] iv = {23, 45, 23, 12 , 39, 111, 90, 1, 2, 3, 4, 5, 6, 7, 8, 9};

FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[1024];

byte[] output = new byte[24];
cpyArray(iv, output, 0);
cpyArray(salt, output, 16);

FileOutputStream fos = new FileOutputStream(new File(f.getPath() + ".enc"));
fos.write(output);


Cipher cipher = getcCipher(pass, salt,iv, Cipher.ENCRYPT_MODE);

for(int length; (length = fis.read(buffer)) > 0; ) { 
    byte[] realbuffer = new byte[length];
    if (length != 1024) {
        cpyArrayUntil(buffer, realbuffer, 0, length);
    } else {
        realbuffer = buffer;
    }
    byte[] chipped = cipher.update(realbuffer)
    fos.write(chipped);
    System.out.println("Chipped: " + chipped.length);
}
cipher.doFinal();
fis.close();
fos.close();

解密:

 Cipher cipher = getcCipher(pass, salt, iv, Cipher.DECRYPT_MODE);
byte[] buffer = new byte[1024];
for(int length; (length = fis.read(buffer)) > 0; ) {
    byte[] realbuffer = new byte[length];
    if (length != 1024) {
        cpyArrayUntil(buffer, realbuffer, 0, length);
    } else {
        realbuffer = buffer;
    }
    byte[] chipped = cipher.update(realbuffer)
    fos.write(chipped);
    System.out.println("Chipped: " + chipped.length);
}
cipher.doFinal();

所以,问题是现在,当我运行它并比较最后的文件时,
1.解密时,我在doFinal上获得了BadPaddingExeption。 和2. En-and Decrypted文件在文件末尾缺少29个字节。

不用担心,Iv和盐通常是随机的,只是静态的测试。

另外,丢失的字节取决于文件大小。刚尝试了另一个文件,它缺少21个字节。

1 个答案:

答案 0 :(得分:0)

您正在丢弃加密和解密例程中doFinal()的输出。这两个都返回一个byte[],它也必须写入你的输出,以便加密的密文或解密的纯文本完整有效。