为什么这个转置解密代码无法使用某些密钥?
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”,但在解密时我得到了错误的结果。使用其他键可以正常工作。
答案 0 :(得分:0)
问题是字符串长度(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的粗略返工 - 您可以看到它允许加密例程保持简单,但解密例程必须更复杂才能弥补它:
import math
def transencrypt(string, key):
'''
Transpositon encryption function. This function is used to encrypt a line
using the transposition encryption method. To learn how transpositon encryption
works you can visit here https://en.wikipedia.org/wiki/Transposition_cipher.
'''
encrypted = ''
length = len(string)
for start in range(key):
for offset in range(start, length, key):
encrypted += string[offset]
return encrypted
def transdecrypt(string, key):
'''
This function is for the decrypting the strings encrypted by
transencrypt(). This function only requires the encrypted
string and the key with which it was decrypted.
'''
decrypted = ''
length = len(string)
width = int(math.ceil(length / key))
for start in range(width):
offset = start
remaining_key = key
remaining_length = length
remaining_width = width
while offset < length:
decrypted += string[offset]
offset += remaining_width
remaining_key -= 1
if remaining_key > 0:
remaining_length -= remaining_width
remaining_width = int(math.ceil(remaining_length / remaining_key))
return decrypted[:length]
if __name__ == '__main__':
import sys
string = sys.argv[1]
key = int(sys.argv[2])
print(transencrypt(string, key))
print(transdecrypt(transencrypt(string, key), key))
** OUTPUT *
> python3 test.py "hello world" 5
h dewlolrol
hello world
>