加密柱状转置密码

时间:2014-07-21 18:44:01

标签: python encryption python-3.x multiple-columns transpose

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

3124
IHAV
ETWO
CATS

然后首先返回第1列中的字符,然后返回第2列等,直到最后返回加密字符串'HTAAWTIECVOS'。到目前为止,我知道我需要使用累加器,而且我一直在想使用字典,但我只是完全卡住了。这些是我尝试过的一些功能:

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 个答案:

答案 0 :(得分: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

可能是我该怎么做的

答案 1 :(得分: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的块然后使用字典理解来获得正确的索引顺序,最后我按顺序连接字母。

相关问题