1

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

One Two Three
  • 22,327
  • 24
  • 73
  • 114

1 Answers1

2

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.

Community
  • 1
  • 1
David M
  • 71,481
  • 13
  • 158
  • 186
  • Could you please be more specific? So I'd need to convert the byte array to hex value? Thanks – One Two Three Apr 25 '12 at 19:30
  • You clearly want a text representation of the byte array so you can pass a string around (though you could always just keep the encrypted form as a byte array...). So common ways of doing this would involve translating to hexadecimal (a byte array containing 32, 65, 99 would become 204163), or encoding as base 64 (the same array would become IEFj). – David M Apr 25 '12 at 19:35