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:

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



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

is probably how I would do it

Solution 2:

defsplit_len(seq, length):
    return [seq[i:i + length] for i inrange(0, len(seq), length)]

defencode(key, plaintext):

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

    ciphertext = ''for index insorted(order.keys()):
        for part in split_len(plaintext, len(key)):
            try:
                ciphertext += part[order[index]]
            except IndexError:
                continuereturn 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"