Advertisement
_eremec_

Untitled

Nov 17th, 2017
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. def add_sybs(coll):
  2.     return coll if len(coll) % 2 == 0 else coll + " "
  3.  
  4. def partition(coll, n):
  5.     p = []
  6.     for i in range(0, len(coll), n):
  7.         p.append(coll[i:i+n])
  8.     return p
  9.  
  10. def char2bin(letter):
  11.     return bin(ord(letter))
  12.  
  13. def bin2char(binary):
  14.     return chr(int(binary,2))
  15.  
  16. def bitshiftright(binary, n):
  17.     b = binary
  18.     for _ in range(n):
  19.         b = b[-1:] + b[:-1]
  20.     return b
  21.  
  22. def bitshiftleft(binary, n):
  23.     b = binary
  24.     for _ in range(n):
  25.         b = b[1:] + b[:1]
  26.     return b
  27.  
  28. def handle_binary(b, n):
  29.     return ([0 for _ in range(n - (len(b) - 2))]
  30.            + [int(el) for el in b[2:]])
  31.  
  32. def xor(b1, b2):
  33.     return [0 if r1 == r2 else 1 for r1, r2 in zip(b1, b2)]
  34.  
  35. def make_block(pair, n):
  36.     return [handle_binary(char2bin(pair[0]), n),
  37.             handle_binary(char2bin(pair[1]), n)]
  38.  
  39. def make_blocks(text, n):
  40.     pairs = partition(add_sybs(text), 2)
  41.     return [make_block(pair, n) for pair in pairs]
  42.  
  43. def encode_block(block, key):
  44.     l = block[0]
  45.     r = block[1]
  46.     return [xor(r, bitshiftright(l, key)), l]
  47.  
  48. def el_encode(blocks, key):
  49.     return [encode_block(block, key) for block in blocks]
  50.  
  51. def list2str(arr):
  52.     return ''.join([str(el) for el in arr])
  53.  
  54. def block2str(block):
  55.     return (bin2char(list2str(block[0])) +
  56.            bin2char(list2str(block[1])))
  57.  
  58. def blocks2str(blocks):
  59.     return ''.join([block2str(block) for block in blocks])
  60.  
  61. def last_round(block, key):
  62.     l = block[0]
  63.     r = block[1]
  64.     return [l, xor(r, bitshiftright(l, key))]
  65.    
  66. def my_encode(text, n, key, k):
  67.     blocks = make_blocks(text, n)
  68.     for _ in range(k-1):
  69.         print(blocks[0])
  70.         blocks = el_encode(blocks, key)
  71.     print(blocks[0])
  72.     return [last_round(block, key) for block in blocks]
  73.  
  74. def last_swap(block):
  75.     return [block[1], block[0]]
  76.  
  77. def my_decode(blocks, key, k):
  78.     for _ in range(k):
  79.         blocks = el_encode(blocks, key)
  80.     return [last_swap(block) for block in blocks]
  81.  
  82. text = "Кто не работает тот не ест"
  83.  
  84. encoded_text = my_encode(text, 16, 4, 2)
  85.  
  86. print(blocks2str(encoded_text))
  87. print(blocks2str(my_decode(encoded_text, 4, 2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement