Skip to content Skip to sidebar Skip to footer

Encrypting A Columnar Transposition Cipher

I'm trying to figure out how to encrypt a columnar transposition cipher in Python given a plaintext uppercase string and a number key of any length. For example, if the key is 3124

Solution 1:

def encode(txt,key):
    sz = len(key)  # how big are the columns 
    cols = list(map("".join,zip(*zip(*[iter(txt)]*sz)))) # list partitioned into columns
    return "".join([cols[key.index(str(c))] for c in range(1,sz+1)])



encoded = encode("IHAVETWOCATS","3124")
print encoded

is probably how I would do it


Solution 2:

def split_len(seq, length):
    return [seq[i:i + length] for i in range(0, len(seq), length)]

def encode(key, plaintext):

    order = {
        int(val): num for num, val in enumerate(key)
    }

    ciphertext = ''
    for index in sorted(order.keys()):
        for part in split_len(plaintext, len(key)):
            try:
                ciphertext += part[order[index]]
            except IndexError:
                continue

    return ciphertext

print(encode('3214', 'IHAVETWOCATS'))
#>>> HTAAWTIECVOS

split_len is by Ian Bicking

So i split the code into chunks with split_len then use dictionary comprehension to just get correct order of indexes and finally i concatanate the letters in that order.


Post a Comment for "Encrypting A Columnar Transposition Cipher"