berninator

Simplified DES for Python

Aug 8th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.36 KB | None | 0 0
  1. #!/usr/bin/python3.7
  2.  
  3. import sys
  4.  
  5. '''
  6. Rotates the given number left by one. Defaults to a 5-bit word.
  7. '''
  8. def left_shift(num, length=5):
  9.     num = (num << 1) + get_bit(num, 1, length);
  10.    
  11.     mask = 0;
  12.     for x in range(length):
  13.         mask = (mask << 1) + 1;
  14.    
  15.     return num & mask;
  16.  
  17. '''
  18. Returns the bit value of the 'pos'th bit in num. Defaults to little endian positioning. (MSB is position 1)
  19. '''
  20. def get_bit(num, pos, size=8, little_endian=True):
  21.     if(little_endian):
  22.         return (num >> (size - pos)) & 1;
  23.     else:
  24.         return (num >> pos) & 1;
  25.  
  26. '''
  27. Permutate the input's bits according to the given permutation array.
  28. The permutation array describes which input bits make up the output, and where they're positioned.
  29. '''
  30. def permutate(input_num, permutation, input_size=8):
  31.     ret_num = 0;
  32.     for p in range(len(permutation)):
  33.         ret_num += get_bit(input_num, permutation[p], input_size) << (len(permutation) - 1 - p);
  34.    
  35.     return ret_num;
  36.  
  37. '''
  38. All permutations performed in SDES.
  39. '''
  40. def P10(num):
  41.     return permutate(num, [3, 5, 2, 7, 4, 10, 1, 9, 8, 6], input_size=10);
  42.  
  43. def P8(num):
  44.     return permutate(num, [6, 3, 7, 4, 8, 5, 10, 9], input_size=10);
  45.  
  46. def P4(num):
  47.     return permutate(num, [2, 4, 3, 1], input_size=4);
  48.  
  49. def IP(num):
  50.     return permutate(num, [2, 6, 3, 1, 4, 8, 5, 7], input_size=8);
  51.  
  52. def IP_inverse(num):
  53.     return permutate(num, [4, 1, 3, 5, 7, 2, 8, 6], input_size=8);
  54.  
  55. def E_P(num):
  56.     return permutate(num, [4, 1, 2, 3, 2, 3, 4, 1], input_size=4);
  57.  
  58. '''
  59. Performs the S0-box calculation on the 4-bit input 'num'.
  60. '''    
  61. def S0(num):
  62.     box = ( (1, 0, 3, 2)
  63.            ,(3, 2, 1, 0)
  64.            ,(0, 2, 1, 3)
  65.            ,(3, 1, 3, 2) )
  66.            
  67.     row = (get_bit(num, 1, 4) << 1) + get_bit(num, 4, 4);
  68.     col = (get_bit(num, 2, 4) << 1) + get_bit(num, 3, 4);
  69.    
  70.     return box[row][col];
  71.  
  72. '''
  73. Performs the S1-box calculation on the 4-bit input 'num'.
  74. '''
  75. def S1(num):
  76.     box = ( (0, 1, 2, 3)
  77.            ,(2, 0, 1, 3)
  78.            ,(3, 0, 1, 0)
  79.            ,(2, 1, 0, 3) )
  80.            
  81.     row = (get_bit(num, 1, 4) << 1) + get_bit(num, 4, 4);
  82.     col = (get_bit(num, 2, 4) << 1) + get_bit(num, 3, 4);
  83.    
  84.     return box[row][col];
  85.  
  86. '''
  87. Performs the switching function. Switches the left four bits of 'num' with the right four bits.
  88. '''
  89. def SW(num):
  90.     return ((num & (0b1111)) << 4) + (num >> 4)
  91.  
  92. '''
  93. Generates the two subkeys K1 and K2 for use in the SDES algorithm.
  94. Returns the two keys in a tuple.
  95. '''
  96. def generate_subkeys(key):
  97.     key = P10(key);
  98.    
  99.     key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
  100.    
  101.     K1 = P8(key);
  102.    
  103.     key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
  104.     key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
  105.    
  106.     K2 = P8(key);
  107.    
  108.     return (K1, K2);
  109.  
  110. '''
  111. Performs one round of the Feistel cipher on the provided number.
  112. '''
  113. def f_K(num, subkey):
  114.     left_input = num >> 4;
  115.     right_input = num & 0b1111;
  116.        
  117.     data = E_P(right_input);   
  118.     data = data ^ subkey;
  119.     data = (S0(data >> 4) << 2) + S1(data & 0b1111);   
  120.     data = P4(data);   
  121.     left_output = left_input ^ data;
  122.        
  123.     return (left_output << 4) + right_input;
  124.    
  125. '''
  126. Encrypts the provided plaintext byte using the two subkeys, K1 and K2.
  127. '''
  128. def encrypt_byte(plaintext, K1, K2):
  129.     ip = IP(plaintext);
  130.    
  131.     round = f_K(ip, K1);
  132.     round = f_K(SW(round), K2);
  133.    
  134.     ciphertext = IP_inverse(round);
  135.    
  136.     return ciphertext;
  137.  
  138. '''
  139. Decrypts the provided ciphertext byte using the two subkeys, K1 and K2.
  140. '''    
  141. def decrypt_byte(ciphertext, K1, K2):
  142.     ip = IP(ciphertext);
  143.    
  144.     round = f_K(ip, K2);
  145.     round = f_K(SW(round), K1);
  146.    
  147.     plaintext = IP_inverse(round);
  148.    
  149.     return plaintext;
  150.  
  151. '''
  152. Encrypt or decrypt the input using SDES in electronic code book mode.
  153.  input_data: The data to process. Expects a byte-array.
  154.  key: The cipher key to process with.
  155.  mode: Whether to encrypt or decrypt the data. Defaults to encryption.
  156. '''
  157. def ecb(input_data, key, mode='encrypt'):
  158.     K1, K2 = generate_subkeys(key);
  159.    
  160.     output = bytearray();
  161.     for b in input_data:
  162.         if(mode.lower() == 'encrypt'):
  163.             processed_byte = encrypt_byte(b, K1, K2);
  164.         else:
  165.             processed_byte = decrypt_byte(b, K1, K2);
  166.         output.append(processed_byte);
  167.    
  168.     return bytes(output);
  169.  
  170. def main():
  171.     # Help text if not given enough arguments.
  172.     if(len(sys.argv) < 5):
  173.         print("***********************");
  174.         print("* SDES File Encryptor *");
  175.         print("***********************\n");
  176.         print(f"Usage:\n\tEncryption: python3 {sys.argv[0]} -e 'key_in_binary' 'plaintext_file' 'ciphertext_file'\n\tDecryption: python3 {sys.argv[0]} -d 'key_in_binary' 'ciphertext_file' 'plaintext_file'");
  177.         print(f"Example: python3 {sys.argv[0]} -e 1100101010 plaintext.txt cipertext.sdes");
  178.         quit();
  179.    
  180.     # Process the given files
  181.     with open(sys.argv[3], 'rb') as input_file:
  182.         with open(sys.argv[4], 'wb') as output_file:
  183.             chunk = bytearray(input_file.read(65535)); # Process the file in 64kB chunks
  184.             key = int(sys.argv[2], 2); # Grab and decode the provided cipher key
  185.             while chunk: # Process the entire file
  186.                 if(sys.argv[1] == "-e"): # Encrypt the data
  187.                     output_file.write( ecb(chunk, key) )
  188.                 elif(sys.argv[1] == "-d"): # Decrypt the data
  189.                     output_file.write( ecb(chunk, key, mode="decrypt") );
  190.                 else:
  191.                     # Error case if an improper mode is provided.
  192.                     sys.stderr.write(f"Mode '{sys.argv[1]}' is not supported! Please use '-e' or '-d'!\n");
  193.                     quit();
  194.                 chunk = input_file.read(65535);
  195.            
  196.  
  197. if __name__ == "__main__":
  198.     main()
Advertisement
Add Comment
Please, Sign In to add comment