Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sets the key parity bit of a DES key byte
- def set_parity(b):
- # If Hamming weight is even,
- # flip least-significant bit
- if hw(b) % 2 == 0:
- return b ^ 0x01
- # Else, return b as-is.
- return b
- # Take a 20-bit number and generate a DES key with
- # parity bits in significant bytes, followed by
- # zero-padding.
- def get_key(n):
- # 20 = 2*8+4. Subtracting parity bits gives
- # effective key bits: 2*7+6, so we shift
- # each whole byte by 7 * the number of less
- # significant bytes + effective length of least
- # significant byte, take modulo 2^7 = 128 and
- # finally shift one to the left to make space
- # for the parity bit.
- # Byte 3 (least-significant byte): take modulo
- # 2^l, where l is the size of the partial byte
- # in bits, and shift by 8-l. This gives 8-6=2.
- b3 = set_parity((n % 64) << 2)
- # Byte 2: Shift by combined length of less
- # signficiant bytes: 6
- b2 = set_parity(((n >> 6) % 128) << 1)
- # Byte 3: Shift by combined length of less
- # signficiant bytes: 7+6=13
- b1 = set_parity(((n >> 13) % 128) << 1)
- # Assemble the generated bytes into a
- # bytearray object.
- key = bytearray([b1, b2, b3, 0, 0, 0, 0, 0])
- # Return the key as a bytes object for DES
- # library compatibility.
- return bytes(key)
Advertisement
Add Comment
Please, Sign In to add comment