为什么这个换位解密代码不能处理某些密钥?你知道吗
def transencrypt(word,key):
'''Traspositon encryption function. This function is used to encrypt a line
using the transposition encryption method. To know how transpositon encryption
works you can visit here https://en.wikipedia.org/wiki/Transposition_cipher.'''
count1=0
count2=0
encrypted=''
encryptbox=['']*key
while count1<key:
count2=count1
while count2<len(word):
encryptbox[count1]+=word[count2]
count2+=key
encrypted+=encryptbox[count1]
count1+=1
return encrypted
def transdecrypt(word,key):
'''This Function is for the decrypting the encrypted strings encrypted by
transencrypt().This function only requires the encrypted string and the key
with which it has been decrypted.'''
import math
count1=0
count2=0
decrypted=''
col=int(math.ceil(len(word)/key))
decryptbox=['']*col
while count1<col:
count2=count1
while count2<len(word):
decryptbox[count1]+=word[count2]
count2+=col
decrypted+=decryptbox[count1]
count1+=1
return decrypted
print(transencrypt('hello world',5))
print(transdecrypt('h dewlolrol',5))
我试过用密钥5加密“hello world”,但在解密时我得到了错误的结果。使用其他键也可以。你知道吗
问题是字符串长度(11)没有平均地划分到键(5)中,因此字符串
"hello world"
编码成组h d-ew-lo-lr-ol
,即"h dewlolrol"
。这很好,但是解密例程将"h dewlolrol"
分割成h d-ewl-olr-ol
,并生成错误的结果"heoo wlldlr"
。你知道吗有几种可能的解决方法:
1)用数组替换
encryptbox
字符串,并将加密单元填充到偶数宽度段:h d-ew -lo -lr -ol
即"h dew lo lr ol "
这将允许您的解密例程工作,但您将在解密结束时得到空格,加密字符串的大小将不同于原始字符串。你知道吗
或
2)根据要解码的剩余字符串的长度和预期段的剩余数量,动态调整解密逻辑以确定段必须收缩多少。这意味着您的解密例程不能像现在这样类似于加密例程。但是它允许您处理当前加密例程的输出,并且加密的字符串可以保持与原始字符串相同的长度。你知道吗
下面是一个粗略的修改,按照上面的方法#2,您可以看到它允许加密例程保持简单,但解密例程必须更复杂才能弥补它:
**输出*
相关问题 更多 >
编程相关推荐