Keyword Transposition Cipher

  • + 0 comments

    Just another solution: Python3, given description implemented staightforward ...

    from itertools import cycle
    
    def make_cipher(key):
        'Build monoalphabetic substitution list.'
        seed = list(dict.fromkeys(key)) # remove duplicate letters
        # build columns
        cols = [[c] for c in seed]
        col_it = cycle(cols)
        for c in map(chr, range(ord('A'), ord('Z') +1)):
            if c not in seed:
                next(col_it).append(c)
        # sort columns
        cols.sort()
        # join all
        return ''.join(''.join(col) for col in cols)
    
    def encrypt(key, plain):
        cipher = make_cipher(key)
        encrypt1 = (lambda c:   ' ' if c == ' ' 
                                else cipher[ord(c)-ord('A')] )
        return ''.join(map(encrypt1, plain))
    
    def decrypt(key, crypt):
        cipher = make_cipher(key)
        decrypt1 = (lambda c:   ' ' if c == ' ' 
                                else chr(ord('A')+cipher.index(c)) )
        return ''.join(map(decrypt1, crypt))
    
    if __name__ == '__main__':
        n = int(input())
        for _ in range(n):
            print(decrypt(input(), input()))