我在android中对文件进行加密解密,为此我使用以下代码
private void encryptFile()
{
try
{
File f = new File(Environment.getExternalStorageDirectory() + "/images.jpg");
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[100];
int num = in.read(buffer, 0, 100);
Encryption mEncryption = new Encryption("test");
File tempFile = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
FileOutputStream os = new FileOutputStream(tempFile);
os.write(mEncryption.encrypt(buffer), 0, 100);
while(in.read(buffer) != -1)
{
os.write(buffer);
}
in.close();
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void decryptFile()
{
try
{
File f = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[100];
in.read(buffer, 0, 100);
Encryption mEncryption = new Encryption("test");
File tempFile = new File(Environment.getExternalStorageDirectory() + "/images.jpg");
FileOutputStream os = new FileOutputStream(tempFile);
os.write(mEncryption.decrypt(buffer), 0, 100);
while(in.read(buffer) != -1)
{
os.write(buffer);
}
in.close();
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
但是当我解密文件时,它给了我IllegalBlockSizeException: last block incomplete in decryption
任何想法为什么会发生这种情况?
修改:我正在使用此Encryption class
答案 0 :(得分:2)
您正在使用的加密类已经发布在我的博客上,就像您说的那样(http://blog.kotowicz.net/2010/09/story-of-android-cryptography-and.html),但作为您不应该实施加密的示例!它有一些特定的填充和密钥扩展问题,所有这些都在博客文章中提到过。
该类来自此类源自Android Remote Notifier项目。如果您真的需要它,至少使用更正后的版本http://code.google.com/p/android-notifier/source/browse/trunk/AndroidNotifier/src/org/damazio/notifier/util/Encryption.java - 我博客文章中的版本存在一些严重问题。
正如Nic Strong所提到的,你遇到填充 - 块密码与块大小对齐,你应该考虑到这一点。
答案 1 :(得分:0)
此代码存在许多潜在问题。什么是Encryption
班?它不是标准Android SDK的一部分。你不打算加密整个文件吗?此代码仅加密前100个字节。而这正是主要的错误所在。然后代码假定输入文件的前100个字节将包含加密数据,这是一个无效的假设。首先将加密数据标准化为加密算法的块大小的长度。