Reputation: 73
I have a problem I have been trying to solve for last three days. I have to use DES to encrypt an array of bytes to get a specific result. The default implementation of DES in Java (Javax.crypto.cipher, JDK 7, provider SunJCE version 1.7), however, seemingly does not work. When I have the following code:
private void testDES() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
byte[] keyByte = convertStringToBytes("00 00 00 00 00 00 00 00");
byte[] data = convertStringToBytes("00 00 00 00 00 00 00 00");
Key key = new SecretKeySpec(keyByte, "DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println(hexadecimalString(cipher.doFinal(data)));
}
It prints F4 DA 4D 97 BF CF 23 D9 instead of the correct result 8C A6 4D E9 C1 B1 23 A7 (according to the test vectors : http://common-lisp.net/project/clbuild/mirror/ironclad/test-vectors/des.testvec) The methods hexadecimalString and convertStringToBytes just transform byte to hexa and vice versa. Could anyone please help me? After searching for a rather long time, I just don't know what to do. Thanks in advance. Joe
Upvotes: 0
Views: 453
Reputation: 9651
I think the problem is with either convertStringToBytes or hexadecimalString.
You can replace:
byte[] keyByte = convertStringToBytes("00 00 00 00 00 00 00 00");
byte[] data = convertStringToBytes("00 00 00 00 00 00 00 00");
with:
byte[] keyByte = new byte[8];
byte[] data = new byte[8];
... because in Java, arrays are initialised to zero.
When I run the same code, but with the above (and not convertStringToBytes), then I get the expected result (8C A6 ...)
Edit: Since you're still having problems, here's a full program. The output for me is:
8c a6 4d e9 c1 b1 23 a7
Code below:
public class Main {
public static void main(String[] args) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
byte[] keyByte = new byte[8];
byte[] data = new byte[8];
Key key = new SecretKeySpec(keyByte, "DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(data);
StringBuilder str = new StringBuilder();
for (byte b : result) {
str.append(Integer.toHexString(0xff & b)).append(' ');
}
System.out.println(str);
}
}
Upvotes: 1