Create a DES key from a 56-bit binary string

I have a 56 bit binary string that I want to use as a secret key for DES encryption.

I found the following code on the JCA documentation website

byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 }; DESKeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 

However, the key uses 8 bytes (instead of 7). It is unclear whether desKeyData [0] matches the least significant byte or the most significant byte. Also, is it possible to use a 56-bit string directly to generate an array of bytes that can be used for this purpose?

+8
java binary jca
source share
2 answers

From Wikipedia :

The key supposedly consists of 64 bits; however, only 56 of them are actually used by the algorithm. Eight bits are used solely for parity and then discarded. Therefore, the effective key length is 56 bits, and it is never quoted as such. Every 8th bit of the selected key is discarded, that is, positions 8, 16, 24, 32, 40, 48, 56, 64 are deleted from the 64-bit key, leaving only the 56-bit key.

Thus, the least significant bits (that is, the 0th bit) are not used to construct keys; they can be used for parity on DESKeySpec.isParityAdjusted() .

EDIT: A simple test showing that the least significant bits are ignored:

 SecretKeyFactory sf = SecretKeyFactory.getInstance("DES"); byte[] in = "test".getBytes("UTF-8"); Cipher c1 = Cipher.getInstance("DES"); c1.init(Cipher.ENCRYPT_MODE, sf.generateSecret(new DESKeySpec( new byte[] {0x10,0x20,0x30,0x40,0x50,0x60,0x70,(byte) 0x80}))); byte[] r1 = c1.doFinal(in); Cipher c2 = Cipher.getInstance("DES"); c2.init(Cipher.ENCRYPT_MODE, sf.generateSecret(new DESKeySpec( new byte[] {0x11,0x21,0x31,0x41,0x51,0x61,0x71,(byte) 0x81}))); byte[] r2 = c2.doFinal(in); assertArrayEquals(r1, r2); 
+7
source share

A significant bit is one that changes the sign of one or two additions . The idea of ​​the least significant bit cannot be applied to bytes.

As follows from the answer of axtavt, of all 64 bits of the sequence, only bits in the ranges are used as the actual key: (1..7), (9..15), (17..23), (25..31), (33..39), (41..47), (49..55), (57..63) . For example, 56 corresponding bits in the sequence turned to 1 are: 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f , leaving the most significant bits equal to zero as a parity check.

To actually convert a sequence of 7 bytes, 56 bits into a sequence of 8 bytes, you can use this code .

+2
source share

All Articles