views:

154

answers:

1

I create a triple DES key from the a byte array ("skBytes") but when calling getEncoded on the triple DES key ("sk") and comparing it to the byte array, they differ! They are almost the same if you look at the console output, though. How would I create a triple DES key that is exactly as "skBytes"?

    byte[] skBytes = {(byte) 0x41, (byte) 0x0B, (byte) 0xF0, (byte) 0x9B, (byte) 0xBC, (byte) 0x0E, (byte) 0xC9, (byte) 0x4A, (byte) 0xB5, (byte) 0xCE, (byte) 0x0B, (byte) 0xEA, (byte) 0x05, (byte) 0xEF, (byte) 0x52, (byte) 0x31, (byte) 0xD7, (byte) 0xEC, (byte) 0x2E, (byte) 0x75, (byte) 0xC3, (byte) 0x1D, (byte) 0x3E, (byte) 0x61};
    DESedeKeySpec keySpec = new DESedeKeySpec(skBytes);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
    SecretKey sk = keyFactory.generateSecret(keySpec);

    for(int i = 0; i < skBytes.length; i++)
    {
        System.out.println("(sk.getEncoded()[i], skBytes[i]) = (" + sk.getEncoded()[i] +", " + skBytes[i] + ")");
    }

Console output:

(sk.getEncoded()[i], skBytes[i]) = (64, 65)
(sk.getEncoded()[i], skBytes[i]) = (11, 11)
(sk.getEncoded()[i], skBytes[i]) = (-15, -16)
(sk.getEncoded()[i], skBytes[i]) = (-101, -101)
(sk.getEncoded()[i], skBytes[i]) = (-68, -68)
(sk.getEncoded()[i], skBytes[i]) = (14, 14)
(sk.getEncoded()[i], skBytes[i]) = (-56, -55)
(sk.getEncoded()[i], skBytes[i]) = (74, 74)
(sk.getEncoded()[i], skBytes[i]) = (-75, -75)
(sk.getEncoded()[i], skBytes[i]) = (-50, -50)
(sk.getEncoded()[i], skBytes[i]) = (11, 11)
(sk.getEncoded()[i], skBytes[i]) = (-22, -22)
(sk.getEncoded()[i], skBytes[i]) = (4, 5)
(sk.getEncoded()[i], skBytes[i]) = (-17, -17)
(sk.getEncoded()[i], skBytes[i]) = (82, 82)
(sk.getEncoded()[i], skBytes[i]) = (49, 49)
(sk.getEncoded()[i], skBytes[i]) = (-42, -41)
(sk.getEncoded()[i], skBytes[i]) = (-20, -20)
(sk.getEncoded()[i], skBytes[i]) = (47, 46)
(sk.getEncoded()[i], skBytes[i]) = (117, 117)
(sk.getEncoded()[i], skBytes[i]) = (-62, -61)
(sk.getEncoded()[i], skBytes[i]) = (28, 29)
(sk.getEncoded()[i], skBytes[i]) = (62, 62)
(sk.getEncoded()[i], skBytes[i]) = (97, 97)
+3  A: 

DES Keys are 56-bit and it's represented in 8 bytes. Each byte carries a parity bit. Triple DES key is simply 3 DES keys concatenated together.

When you make keys with DESedeKeySpec and it adjusts the parity for you. So you have to provide the bytes with proper parity to get the same encoded values.

ZZ Coder