Create DES key from 56 bit binary string

北战南征 提交于 2019-12-03 03:13:40

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);  

A significant bit is the one that changes the sign of a one or two's complement number. The idea of a most-or-least significant bit can not be applied to bytes.

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

To actually convert a 7 bytes, 56 bits sequence to an 8 byte sequence you can use this code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!