我正试图弄清楚如何在Python中加密一个列式换位密码,给定一个明文大写字符串和一个任意长度的数字密钥。例如,如果键是3124,字符串是"IHAVETWORCATS",它会像这样组织字符串:
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错误。非常感谢您的帮助!
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
我可能会这样做
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
将代码分割成块,然后使用字典理解来获得正确的索引顺序,最后按该顺序连接字母。