Question

I want to transform a String value to secret KEY DES:

String sb="fffe7a50" //Example of DES key 
byte []b=sb.getBytes();  //string to bytes
SecretKey key2 = new SecretKeySpec(b, 0, b.length, "DES");

however the output is completly different :

javax.crypto.spec.SecretKeySpec@183a2

i know that the numbers after the "@" are supposed to be the DES key , but why are the results different ? how can i fix it ?

Was it helpful?

Solution

You've got a few issues here:

  1. sb.getBytes() does not do what you think it does. What you are expecting is a byte array containing { 0xff, 0xfe, 0x7a, 0x50 }. What you are getting is a byte array containing { 0x46, 0x46, 0x46, 0x45, 0x37, 0x61, 0x35, 0x30 } (assuming you're using UTF-8).

    Your choices here would be to either initialise the byte array manually, like so:

    byte[] b = new byte[]{ (byte) 0xff, (byte) 0xfe, (byte) 0x7a, (byte) 0x50 };
    

    Or to parse the string correctly. I'm not sure exactly how you'd go about that, but it should be doable (and there will likely be an open-source library to do it for you).

  2. The output javax.crypto.spec.SecretKeySpec@183a2 is not writing out the value of the key. All you're seeing is the toString output of the SecretKeySpec, which follows the format <fully-qualified-class-name>@<hashcode> (see here for details on the toString() method), so the numbers you're seeing, 183a2, are just the hashcode of the SecretKeySpec object, which must not be the key - that would very insecure. To see the value of the key it's holding, you'd need to call the SecretKeySpec#getEncoded() method.

    Note that just calling System.out.println(byteArray) will not display the content of the byte array - it will just display the class name and hashcode again. You'll need to either iterate through the array and print out the elements one-by-one, or use another tool to compare the two arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top