加密柱状转置密码 [英] Encrypting a columnar transposition cipher
问题描述
我试图找出如何加密Python中的柱状转置密码,给出明文大写字母和任何长度的数字键。例如,如果键为3124,字符串为IHAVETWOCATS,则将按如下方式组织字符串:
I'm trying to figure out how to encrypt a columnar transposition cipher in Python given a plaintext uppercase string and a number key of any length. For example, if the key is 3124 and the string is 'IHAVETWOCATS', it would organize the string like so:
3124
IHAV
ETWO
CATS
然后返回列中的字符1,然后列2等,直到最后返回加密的字符串'HTAAWTIECVOS'
。到目前为止,我知道我需要使用一个累加器,我一直在使用一个字典,但是我完全陷入困境。这些是我尝试过的一些功能:
and then return the characters in column 1 first, then column 2, etc, until finally returning the encrypted string 'HTAAWTIECVOS'
. So far I know that I'll need to use an accumulator, and I've been toying with the idea of using a dictionary, but I'm just completely stuck. These are some of the functions I've tried:
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)
^只返回几个字母,而不是一个适当长度的字符串。
^This only returns a few letters, not a string of appropriate length.
def columnar(明文,键)
值= {}
seqlist = []
nextvalue = 1
indices = rand(len(key))
为明文中的字母:
为i在索引:
if letter == key [i]:
values [i] = nextvalue
nextvalue = nextvalue + 1
for i in indexes:
seqlist.append值[i])
返回seqlist
^上述函数返回一个KeyError:0错误。
非常感谢您的帮助!
^The above function returns a KeyError: 0 error. Thank you very much for any help!
推荐答案
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
is by Ian Bicking
所以我用 split_len
将代码分成块,然后使用字典理解来获取索引的顺序,该订单中的字母。
So i split the code into chunks with split_len
then use dictionary comprehension to just get correct order of indexes and finally i concatanate the letters in that order.
这篇关于加密柱状转置密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!