Reputation: 23497
I wrote an encrypt and a decrypt function. The encrypt works fine, but I always get IllegalBlockSizeException in the decrypt.
public static String aes_encrypt (String text, String key)
{
SecretKey skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.ENCRYPT_MODE, skey);
return new String((cipher.doFinal(text.getBytes())));
}
And here's the decrypt function:
public static String aes_decrypt (String text, String key)
{
SecretKey skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.DECRYPT_MODE, skey);
return new String((cipher.doFinal(text.getBytes())));
}
Here's the simple main method that tests this:
public static void main (String args[])
{
String text = "Hello, world!";
String key = "nv93h50sk1zh508v";
String en, de;
System.out.println("Text: " + text);
System.out.println("Encrypted: " + (en = aes_encrypt(text, key))
+ " length = " + en.length());
System.out.println("Decrypted: " + (de = aes_decrypt(en, key)));
}
Does anyone know how to "pad" the encrypted string properly so that I can decrypt it?
(I tried padding the string with 0 until the length is a multiple of 16, but got something like string not properly padded
.)
Thanks
Upvotes: 1
Views: 284
Reputation: 72880
I think the problem is in your using the String
constructor. This is converting to string using a text encoding mechanism, which may not preserve every value in the byte array - unsupported ones in the system default encoding may be discarded, leaving the encoded data shorter than it should be. If you want a string representation, convert to hex or base 64 encoding instead. And reverse whatever encoding you use here at the start of the decryption method.
It's not a padding issue - the encryption call will pad this fine, you are short of bytes because of your means of encoding the byte array to a string.
You'll find some base 64 instructions in answers to this SO question.
Upvotes: 2