柱状换位密码

2024-09-24 22:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何在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错误。 非常感谢你的帮助!


Tags: key字符串inforlenreturndefacc
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是由Ian Bicking写的

因此,我用split_len将代码分成块,然后使用字典理解来获得正确的索引顺序,最后按照该顺序来计算字母。

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

可能是我要做的

相关问题 更多 >