Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DES key from 56 bit binary string

Tags:

java

binary

jca

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

I found the following code at the JCA docs 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 this uses 8 bytes for the key (instead of 7). It is not clear if the desKeyData[0] corresponds to the least significant byte or the most significant one. Also, is it possible to use the 56 bit string directly to generate the byte array that can be used for this purpose ?

like image 363
AnkurVj Avatar asked Feb 13 '11 17:02

AnkurVj


People also ask

Why does DES have a 56 bit key?

DES works by encrypting groups of 64 message bits, which is the same as 16 hexadecimal numbers. To do the encryption, DES uses "keys" where are also apparently 16 hexadecimal numbers long, or apparently 64 bits long. However, every 8th key bit is ignored in the DES algorithm, so that the effective key size is 56 bits.

How 16 subkeys are generated in DES?

In general, a 64-bit key is used as input for DES, of which only 56-bits are used. 16 subkeys, with 48-bit each, will then be created from this 56-bits.


1 Answers

From Wikipedia:

The key ostensibly consists of 64 bits; however, only 56 of these are actually used by the algorithm. Eight bits are used solely for checking parity, and are thereafter discarded. Hence the effective key length is 56 bits, and it is never quoted as such. Every 8th bit of the selected key is discarded, i.e. positions 8, 16, 24, 32, 40, 48, 56, 64 are removed from the 64 bit key leaving behind only the 56 bit key.

So, the least significant bits (i.e. 0th bits) are not used for key construction, they can be used for checking parity by DESKeySpec.isParityAdjusted().

EDIT: 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);  
like image 78
axtavt Avatar answered Oct 12 '22 22:10

axtavt