Cannot get correct result with DES decryption!
Hello,
I have a problem to decript data encoded in DES/ECB.
Encrypted data is "48E226B65B1DDE2B"
and DES key is "D767B63786280221"
According to manufacturer, decrypted data must be : EA429AAE2FB5EA7D
The manufacturer says that data is encrypted with DES-1 algorithm in ECB mode.
Here is the code I used for my test.
String decodedString ="";
String szData = "\u0048\u00E2\u0026\u00B6\u005B\u001D\u00DE\u002B";
String szDESKey = "\u00D7\u0067\u00B6\u0037\u0086\u0028\u0002\u0021";
try {
byte key[] = szDESKey.getBytes("ISO-8859-1");
SecretKeySpec secretKey = new SecretKeySpec(key,"DES");
Cipher decrypt = Cipher.getInstance("DES/ECB/NoPadding");
decrypt.init(Cipher.DECRYPT_MODE, secretKey);
decodedString = decrypt.doFinal(szData.getBytes("ISO-8859-1")).toString();
} catch (Exception ex) {
}
With this code I get the result "5B4240636432313932" instead of "EA429AAE2FB5EA7D"
Does anyone of you know where can be the problem?
Thanks in advance,
Message was edited by:
Philipina
[1118 byte] By [
Philipinaa] at [2007-10-3 3:28:21]

The values you are given are hex encoded so the following gives the result you expect -
import javax.crypto.*;
import javax.crypto.spec.*;
import org.apache.commons.codec.binary.*;
public class Fred106
{
public static void main(String[] args) throws Exception
{
Hex encoder = new Hex();
byte[] encryptedData = (byte[])encoder.decode("48E226B65B1DDE2B");
byte[] DESkey = (byte[])encoder.decode("D767B63786280221");
SecretKey key = new SecretKeySpec(DESkey, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(encryptedData);
System.out.println(new String(encoder.encode(decrypted)));
}
}
Thanks a lot, this is now working fine.
After reading your code I decided to check mine and finally the only think I did to get the correct result was changing the line:
decodedString = decrypt.doFinal(szData.getBytes("ISO-8859-1")).toString();
in
byte[] decodedString = decrypt.doFinal(szData.getBytes("ISO-8859-1"));
And this is working well.
I don't really understand why the "toString" creates problem.
Alain
Message was edited by:
Philipina
> byte[] decodedString =
> decrypt.doFinal(szData.getBytes("ISO-8859-1"));
>
> And this is working well.
> I don't really understand why the "toString" creates
> problem.
>
Conversion of bytes to a String using this approach is generally wrong since for most character encodings it is not reversible. i.e.
bytes -> chars -> bytes
does not get back the original bytes.
You can often get away with it for iso-8859-1 but it in my view it is still wrong. If you have to have a String representation then I would suggest Base64 or Hex encoding.