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

我使用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个字节,原始文件似乎产生错误。 错误重新块大小在代码行触发,而((b = fis.read(d))!= -1){在解密函数中。

更新:感谢您的反馈。 最终解决方案是在最后一个块中使用CipherInputStream / CipherOutputStream不完整定义的,即使使用填充AES / CBC / PKCS5Padding也是如此

罗南