Converting a 56-bit Value to a DES Key

The DES encrypter/decrypter requires a 64-bit key where only 56-bit are significant. The other 8-bit are parity bits used to ensure that the key has not been corrupted. To make the 64-bit key, the 56-bit value is broken up into 7-bit chunks. Each 7-bit chunk is moved into an 8-bit slot taking up the most significant bit positions. The least significant bit (the parity bit) is set to either 1 or 0 in order to make the quantity of 1 bits in the byte an odd number.

This example implements a method to convert a 56-bit value into a valid DES key. Such a method could be used to convert a 7-character string password to a valid DES key.

See also Encrypting a String with DES.

// Takes a 7-byte quantity and returns a valid 8-byte DES key. // The input and output bytes are big-endian, where the most significant // byte is in element 0. public static byte[] addParity(byte[] in) { byte[] result = new byte[8]; // Keeps track of the bit position in the result int resultIx = 1; // Used to keep track of the number of 1 bits in each 7-bit chunk int bitCount = 0; // Process each of the 56 bits for (int i=0; i<56; i++) { // Get the bit at bit position i boolean bit = (in[6-i/8]&(1<<(i%8))) > 0; // If set, set the corresponding bit in the result if (bit) { result[7-resultIx/8] |= (1<<(resultIx%8))&0xFF; bitCount++; } // Set the parity bit after every 7 bits if ((i+1) % 7 == 0) { if (bitCount % 2 == 0) { // Set low-order bit (parity bit) if bit count is even result[7-resultIx/8] |= 1; } resultIx++; bitCount = 0; } resultIx++; } return result; }
// Get the 56-bit value byte[] raw = new byte[]{0x01, 0x72, 0x43, 0x3E, 0x1C, 0x7A, 0x55}; byte[] keyBytes = addParity(raw); // You can check that the parity has been set properly try { boolean b = DESKeySpec.isParityAdjusted(keyBytes, 0); } catch (java.security.InvalidKeyException e) { // The DES is invalid } // Convert the bytes into a SecretKey suitable for use by Cipher SecretKey key = new SecretKeySpec(keyBytes, "DES");

Comments

6 Apr 2010 - 12:47am by ray (not verified)

when only 56 bits are significant what is the need to expand the key bits into 64 bits ? even they will be discarded in the round key expansion function. the key is transmitted securely over an un secure channel using either defii helman or public key exchange method what is the need for checking only parity of the key bits.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.