【发布时间】:2015-01-07 22:01:47
【问题描述】:
我在我的应用程序中为下载的文件提供了加密/解密机制。
此机制适用于所有 android 设备和 android 5.0-lollipop 之前的版本。
下面是解密过程:
cipher.init(Cipher.DECRYPT_MODE, key);
fileInputStream = new FileInputStream(file);
cipherInputStream = new CipherInputStream(fileInputStream, cipher);
byte[] fileByte = new byte[(int) file.length()];
int j = cipherInputStream.read(fileByte);
return fileByte;
密码和密钥之前生成并在整个应用程序中使用:
key = new SecretKeySpec(keyValue, "AES");
try {
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
当我在 android 5.0 中解密一个大约 200,000 字节的文件时,j(返回前的变量)约为 8000,远低于 200000,而在旧版本的 android 中它正好等于解密后的文件长度。
我发现问题出在解密上。因为我可以在 android 5.0 中加密文件并在较旧的 android 版本中解密它,但反之则不行。但是我正在发布加密过程:
cipher.init(Cipher.ENCRYPT_MODE, AESutil.key);
cipherOutputStream = new CipherOutputStream(output, cipher);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
cipherOutputStream.write(data, 0, count);
}
提前致谢
【问题讨论】:
-
您的流处理对我来说似乎很时髦。创建文件大小的缓冲区并不意味着实际读取所有这些字节。而且您似乎没有在加密期间明确关闭流(但也许只是不包括在内)。
-
@MaartenBodewes-owlstead 是的,我已经关闭了它们。问题依然存在。
-
您能否通过读取字节直到
j为-1来确保也读取了正确数量的字节? -
通常问题不是解密而是密钥生成。因此我强烈建议在加密/解密之前比较使用的密钥。
-
@MaartenBodewes-owlstead。我按照你说的修改了代码,问题就解决了。非常感谢。
标签: android encryption android-5.0-lollipop