Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def add_sybs(coll):
- return coll if len(coll) % 2 == 0 else coll + " "
- def partition(coll, n):
- p = []
- for i in range(0, len(coll), n):
- p.append(coll[i:i+n])
- return p
- def char2bin(letter):
- return bin(ord(letter))
- def bin2char(binary):
- return chr(int(binary,2))
- def bitshiftright(binary, n):
- b = binary
- for _ in range(n):
- b = b[-1:] + b[:-1]
- return b
- def bitshiftleft(binary, n):
- b = binary
- for _ in range(n):
- b = b[1:] + b[:1]
- return b
- def handle_binary(b, n):
- return ([0 for _ in range(n - (len(b) - 2))]
- + [int(el) for el in b[2:]])
- def xor(b1, b2):
- return [0 if r1 == r2 else 1 for r1, r2 in zip(b1, b2)]
- def make_block(pair, n):
- return [handle_binary(char2bin(pair[0]), n),
- handle_binary(char2bin(pair[1]), n)]
- def make_blocks(text, n):
- pairs = partition(add_sybs(text), 2)
- return [make_block(pair, n) for pair in pairs]
- def encode_block(block, key):
- l = block[0]
- r = block[1]
- return [xor(r, bitshiftright(l, key)), l]
- def el_encode(blocks, key):
- return [encode_block(block, key) for block in blocks]
- def list2str(arr):
- return ''.join([str(el) for el in arr])
- def block2str(block):
- return (bin2char(list2str(block[0])) +
- bin2char(list2str(block[1])))
- def blocks2str(blocks):
- return ''.join([block2str(block) for block in blocks])
- def last_round(block, key):
- l = block[0]
- r = block[1]
- return [l, xor(r, bitshiftright(l, key))]
- def my_encode(text, n, key, k):
- blocks = make_blocks(text, n)
- for _ in range(k-1):
- print(blocks[0])
- blocks = el_encode(blocks, key)
- print(blocks[0])
- return [last_round(block, key) for block in blocks]
- def last_swap(block):
- return [block[1], block[0]]
- def my_decode(blocks, key, k):
- for _ in range(k):
- blocks = el_encode(blocks, key)
- return [last_swap(block) for block in blocks]
- text = "Кто не работает тот не ест"
- encoded_text = my_encode(text, 16, 4, 2)
- print(blocks2str(encoded_text))
- print(blocks2str(my_decode(encoded_text, 4, 2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement