user2747596 user2747596 - 1 month ago 17
Java Question

Java DES Wrong Encryption

I have coded DES in Java using builtin Libraries but I am not getting the right Encryption Result. Please help me out and 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

This is what i am saying the answer in the encrypted output in online calculator is 0000........ And mine is completely different

Answer

Change

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

to

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

Besides, use mode ECB. Like:

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