0

I have a token and a secret that is needed to decrypt the token. I am not sure what am I doing wrong that I keep getting "illegal key size". My key size is 44 bytes. I am adding BouncyCastleProvider in a static block. Below is a small snippet of what I am trying to do.

SecretKeySpec skeySpec = new SecretKeySpec(keyText.getBytes(), "DES");
Cipher des = Cipher.getInstance("DES/CBC/ZeroBytePadding", "BC");
des.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[8]));
byte[] tokenData = des.doFinal(Base64.decodeBase64(token));
Bytekoder
  • 192
  • 1
  • 7
  • 23

2 Answers2

3

DES has a key size of 56-bits in 8-bytes, the lsb of each byte is reserved for parity but is generally ignored.

So "My key size is 44 bytes" is incorrect.

Next is the IV used for decryption must be the same as was used for encryption. DES has a block size of 8-bytes so the IV needs to be 8-bytes. One general way of handling the IV is so prefix the encrypted data with it, the IV does not need to be secret.

Finally, zero padding is not generally a good solution, it does not support binary data that may end with a zero byte. PKCS#5 is the generally used padding.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Zero padding is a bad idea in most cases, but (non-triple) DES is a much worse one always. – dave_thompson_085 Nov 02 '17 at 22:41
  • Best to skip over 3DES right to AES, it is the current standard. – zaph Nov 02 '17 at 22:45
  • I agree with your comment about zero padding but it's just that we have a legacy system and we need to live with it for a few more days. So the issue was both key and the encrypted data. – Bytekoder Nov 03 '17 at 20:20
1

My guess is that your keyText is Base64 encoded. You should probably decode it to get a byte[] of 32 bytes. In Java 8 you can do something like this:

byte[] key = java.util.Base64.getDecoder().decode(keyText.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(key, "DES");
Cipher des = Cipher.getInstance("DES/CBC/ZeroBytePadding", "BC");
des.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[8]));
byte[] tokenData = des.doFinal(Base64.decodeBase64(token));

This other question has more information about Base64. Converting Secret Key into a String and Vice Versa

I still think you will get invalid key size errors though. Isn't a DES key 56 bits (plus 8 parity bits)? So that would only be 8 bytes long not 44 or the 32 I think you will get when you decode Base64.

Corey
  • 664
  • 9
  • 18