Search code examples
javaencryptiondes

Java DES Wrong Encryption


I have coded DES in Java using builtin Libraries but I am not getting the right Encryption Result. Please explain me where I am making a mistake

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.bind.DatatypeConverter;

public class MainClass {

    public static void main(String[] args) {

        String l = "0e329232ea6d0d73";

        byte[] a = DatatypeConverter.parseHexBinary(l);

        try{
            DESKeySpec dks = new DESKeySpec(a);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey sk = skf.generateSecret(dks);
        Cipher c = Cipher.getInstance("DES");
        c.init(Cipher.ENCRYPT_MODE, sk);
        String M = "8787878787878787";
        byte[] b = c.doFinal(M.getBytes());

        System.out.println(new String(b));
        c.init(Cipher.DECRYPT_MODE, sk);
        System.out.println(new String(c.doFinal(b)));
        }
        catch(Exception e)

        {
            System.out.println(e.getMessage());
        }   
    }

}

HexaDecimal 16 Digit Key: 0e329232ea6d0d73
Plain Text: 8787878787878787
Encryption : –m^MúÊ'+–m^MúÊ'+©ôËÓ—

Desired Encryption: 0000000000000000

This is what I am saying the answer in the encrypted output in online calculator is 0000, and mine is completely different:

Image


Solution

  • Change

    byte[] b = c.doFinal(M.getBytes());

    to

    byte[] b = c.doFinal(DatatypeConverter.parseHexBinary(M));

    Besides, use mode ECB in your code (because you marked ECB in your picture). Like:

    Cipher c = Cipher.getInstance("DES/ECB/NoPadding");
    

    The String.getBytes() encodes the String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. In your case which is an array of length 16 containing values 56 55 56 55... ASCII representation of 8787...

    What you need is converting the Hex 8787... to binary.