Reputation: 15269
I am doing an encryption decryption of file in android, for this purpose I am using following code
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();
}
}
but when I decrypt file its giving me IllegalBlockSizeException: last block incomplete in decryption
any Idea why its happening?
Edit: I am using this Encryption class
Upvotes: 0
Views: 1886
Reputation: 143
the Encryption class you are using was posted on my blog like you said ( http://blog.kotowicz.net/2010/09/story-of-android-cryptography-and.html ) but as an example of how you SHOULDN'T implement the encryption! It has some certain padding and key expansion problems, all mentioned in the blog post.
The class comes from the source of this class comes from Android Remote Notifier project. If you really need it, at least use the corrected version http://code.google.com/p/android-notifier/source/browse/trunk/AndroidNotifier/src/org/damazio/notifier/util/Encryption.java - the version in my blog post has some serious issues.
As Nic Strong mentioned, you are encountering padding - block ciphers align to block size and you should account for that.
Upvotes: 2
Reputation: 6592
There are many potential problems with this code. What is the Encryption
class? It is not part of standard Android SDK. Are you not intending to encrypt the whole file? This code is only encrypting the first 100 bytes. And this is where the major fault is. The code then assumes that the first 100 bytes of input file will contain encrypted data, this is an invalid assumption. The encrypted data will for a start be normalised to the length of the block size of the encryption algorithm.
Upvotes: 0