Android解密:最终确定密码时出错

时间:2014-10-17 13:30:49

标签: java android encryption encryption-symmetric

我使用Android来加密和加密应用之间发送的图像。

加密效果很好但是当文件到达目的地时它不会解密。现在我已经在目标应用程序中复制了该文件,并使用第三方软件成功解密。

我得到的错误是:在IllegalBlockSizeException引起的CipherInputStream(CipherInputStream.java:107)中“最终确定密码时出错”。

加密&解密代码如下:

public static String encrypt(String plainFile, String encryptedFile) throws    IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
    // Here you read the cleartext.
    File extStore = Environment.getExternalStorageDirectory();
    FileInputStream fis = new FileInputStream(plainFile);
    // This stream write the encrypted text. This stream will be wrapped by
    // another stream.
    FileOutputStream fos = new FileOutputStream(encryptedFile);

    // Length is 16 byte
    SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
    // Create cipher
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    }
    // Flush and close streams.
    cos.flush();
    cos.close();
    fis.close();

    return encryptedFile;
}   

static String decrypt(String plainFile, String encryptedFile) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {

    File encFile=new File(encryptedFile);
    FileInputStream fis = new FileInputStream(encFile);

    FileOutputStream fos = new FileOutputStream(plainFile);
    SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
              "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    int b;
    byte[] d = new byte[8];
    while ((b = cis.read(d)) != -1) {
        fos.write(d, 0, b);
    }
    fos.flush();
    fos.close();
    cis.close();

    return plainFile;
}    

有什么想法吗?谢谢!

罗南

更新: 收到的加密文件始终比原始文件小1个字节,原始文件似乎产生错误。在代码行触发错误重新块大小  while((b = fis.read(d))!= -1){在解密函数中。

更新: 感谢您的反馈。最终解决方案定义为last block incomplete with CipherInputStream/CipherOutputStream, even with padding AES/CBC/PKCS5Padding

罗南

0 个答案:

没有答案