Guest User

Untitled

a guest
Nov 26th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. # Sets the key parity bit of a DES key byte
  2. def set_parity(b):
  3.     # If Hamming weight is even,
  4.     # flip least-significant bit
  5.     if hw(b) % 2 == 0:
  6.         return b ^ 0x01
  7.     # Else, return b as-is.
  8.     return b
  9.  
  10. # Take a 20-bit number and generate a DES key with
  11. # parity bits in significant bytes, followed by
  12. # zero-padding.
  13. def get_key(n):
  14.     # 20 = 2*8+4. Subtracting parity bits gives
  15.     # effective key bits: 2*7+6, so we shift
  16.     # each whole byte by 7 * the number of less
  17.     # significant bytes + effective length of least
  18.     # significant byte, take modulo 2^7 = 128 and
  19.     # finally shift one to the left to make space
  20.     # for the parity bit.
  21.  
  22.     # Byte 3 (least-significant byte): take modulo
  23.     # 2^l, where l is the size of the partial byte
  24.     # in bits, and shift by 8-l. This gives 8-6=2.
  25.     b3 = set_parity((n % 64) << 2)
  26.     # Byte 2: Shift by combined length of less
  27.     # signficiant bytes: 6
  28.     b2 = set_parity(((n >> 6) % 128) << 1)
  29.     # Byte 3: Shift by combined length of less
  30.     # signficiant bytes: 7+6=13
  31.     b1 = set_parity(((n >> 13) % 128) << 1)
  32.    
  33.     # Assemble the generated bytes into a
  34.     # bytearray object.
  35.     key = bytearray([b1, b2, b3, 0, 0, 0, 0, 0])
  36.  
  37.     # Return the key as a bytes object for DES
  38.     # library compatibility.
  39.     return bytes(key)
Advertisement
Add Comment
Please, Sign In to add comment