Cipher class from javax.crypto package not working as expected using the DES algorithm

Here is my code:

public byte[] encrypt(byte[] key, byte[] pText) throws Exception
    System.out.println( DatatypeConverter.printHexBinary(key)); // Outputs: 3FBB589A6A941D01
    System.out.println( DatatypeConverter.printHexBinary(pText)); // Outputs: 92F3BD61F852727E
    Cipher ciph = Cipher.getInstance("DES");
    SecretKey blah = new SecretKeySpec(key, 0, key.length, "DES");

    ciph.init(Cipher.ENCRYPT_MODE,  blah);
    byte[] test = ciph.doFinal(pText); 
    System.out.println( DatatypeConverter.printHexBinary(test)); // Outputs: 4799F8A1C0A427E17E2B19DD22064444

    return test;

A couple of things I as unsure on:

  1. I padded the key with 01, that is why the output on the first line ends with 01. I tried padding it with 0s but that did not work either. And the required length is 8 bytes. So not sure if I did that right.
  2. I am not completely sure what offset means in the SecretKey constructor(2nd argument). I am assuming it should be 0.
  3. My main question is why is test(the cipherText) 16 bytes? According to page 13 it should be only 8 bytes.

I also know my code is not working because I know what the final encrypted output should be.


You don't specify the mode and padding for the cipher in the call to getInstance(), so the provider will choose default parameters. Your provider is defaulting to "PKCS5Padding", so it add 8 bytes with a value of 0x08 to your plain text before performing the DES encryption.

To avoid platform-dependent behavior, it's very important to specify a complete transformation when creating a Cipher instance: algorithm, mode, and padding. If you don't want padding, say so:

Cipher ciph = Cipher.getInstance("DES/ECB/NoPadding");
SecretKey blah = new SecretKeySpec(key, "DES");

Why did you pad your key? Why wasn't your key 8 bytes long to start? If the first 7 bytes are intended to be used as the actual key, and lack parity bits, you can't just slap a byte on the end; you need to expand the key to eight bytes, appending one parity bit to each 7-bit chunk.

If you use the parity-adjusted key, 3EDCD613A754513B, and no padding, the cipher text is C094C47D7F89E219. Is that what you are expecting?

Need Your Help

The best Django webcasts/videos

python django

I'm currently learning Django though reading the Django Book, but I'm a huge fan of webcasts/screencasts/videos and haven't found any good ones so far. Are there any and which ones would you recomm...