首页 文章

加密柱状转置密码

提问于
浏览
2

给出明文大写字符串和任意长度的数字键,我试图弄清楚如何在Python中加密柱状转置密码 . 例如,如果键是3124并且字符串是'IHAVETWOCATS',它将组织字符串,如下所示:

3124
IHAV
ETWO
CATS

然后首先返回第1列中的字符,然后返回第2列等,直到最后返回加密字符串 'HTAAWTIECVOS' . 到目前为止,我知道我已经玩弄了使用字典的想法,但我已经尝试过了:775588

def columnar(plaintext,key):
    cipher=''
    acc=0
    for i in range(len(key)):
        while acc<(len(plaintext)/len(key)):
            cipher=cipher+plaintext[i+acc*5]
            acc=acc+1
    return(cipher)

^这只返回几个字母,而不是一个适当长度的字符串 .

def columnar(plaintext,key) values={} seqlist=[] nextvalue=1 indices=rand(len(key)) for letter in plaintext: for i in indices: if letter==key[i]: values[i]=nextvalue nextvalue=nextvalue+1 for i in indices: seqlist.append(values[i]) return seqlist

^上面的函数返回KeyError:0错误 . 非常感谢您的帮助!

2 回答

  • 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
    

    我可能就是这样做的

  • 0
    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 是Ian Bicking

    所以我用 split_len 将代码分成块,然后使用字典理解来获得正确的索引顺序,最后我按顺序连接字母 .

相关问题