-2

Here is my encryption method(value is an input parameter):

 byte key_bytes[] = "12345678".getBytes();
 SecretKeySpec _keyspec = new SecretKeySpec(key_bytes, "DES");
 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); // Yes, I know I shouldn't use DES
 cipher.init(Cipher.ENCRYPT_MODE, _keyspec);

 byte[] utf8 = value.getBytes("UTF8");
 byte[] enc = cipher.doFinal(utf8);   // Encrypt

 String encrypted = new String(new Base64().encode(enc));

 return URLEncoder.encode(encrypted, "UTF-8");

Here is my decryption method(value is an input parameter):

byte key_bytes[] = "12345678".getBytes();
SecretKeySpec _keyspec = new SecretKeySpec(key_bytes, "DES");
Cipher dcipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, _keyspec);

byte[] dec = new Base64().decode(value);
byte[] utf8 = dcipher.doFinal(dec);  // Decrypt, throws exception
return new String(utf8, "UTF8");

And I get an Exception:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

I've read different topics, so I figured out, that this exception occurs, when there is no padding and there is another cipher mode. So, what's wrong?

John Smith
  • 831
  • 5
  • 19
  • 37

2 Answers2

2

You are missing an URLDecoder in your decryption method. Note that if the string has been compromised in any other way, and the length is not a multiple of the block size anymore that you will receive this exception for both the ECB and CBC modes of operation.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I use apache's Base64 encoder, URL is decoded above, in another method, so value in input is already decoded – John Smith Jul 17 '14 at 16:15
  • 2
    Works on my system otherwise. Check if the string received is the string send! Note that this is why you should create a SSCCE! – Maarten Bodewes Jul 17 '14 at 16:19
  • the string, which I recieve on the output of encryption method equals the string, which is given as input in decryption – John Smith Jul 18 '14 at 07:26
  • Could you show us an example input string used for decryption that fails with this exception? Preferably edit it into the answer and respond that you did so here. – Maarten Bodewes Jul 18 '14 at 12:53
1

As exception stack says, length must be multiple of 8.

So, length of 8, 16, 24,... are valid for key bytes.

Try with length of 8 (12345678)

byte key_bytes[] = "12345678".getBytes();

If error persists, you can follow this answer

Updated

If you want to use URLDecoder, try with this code in your decrypt method,

String decryptd = URLDecoder.decode(value, "UTF-8");
byte[] dec = new Base64().decode(decryptd);
byte[] utf8 = dcipher.doFinal(dec);  
return new String(utf8, "UTF-8");
Community
  • 1
  • 1
Wundwin Born
  • 3,467
  • 19
  • 37