Rail Fence Cipher通用解密Python代码错误排查求助
Rail Fence Cipher解密代码错误分析与修正
我正在学习Brian Heinold所著《Python编程实用入门》,书中第23章习题涉及栅栏密码(Rail Fence Cipher):将字符串按3组、4组等拆分加密。我已实现通用加密代码且可正常运行,但编写的解密代码无法还原原始消息,附上我的代码,请帮忙指出错误所在并提供修正建议。
我的加密代码
message = input("Enter a message: ") part = eval(input("Enter the encryption interval, e.g. by threes, fours, etc. ")) encrypted = "" for chunk in range(part): for i in range(chunk, (len(message)), part): encrypted = encrypted + message[i] print(encrypted)
我的解密代码
message = input("Enter a message: ") part = eval(input('Into how many parts the cyoher was split? ')) length = len(message) block = length//part decrypted = "" for k in range(0, length, part): for i in range(block): for j in range(part): section = message[part + i] decrypted = decrypted + section print(decrypted)
错误分析
你的解密代码逻辑完全不符合栅栏密码的解密规则:
- 多层嵌套循环逻辑混乱,没有对应加密的逆过程;
section = message[part + i]索引计算错误,会重复读取固定位置的字符,无法还原原始字符顺序;- 未考虑原字符串长度无法被分组数整除的情况,这种场景下前几个分组的长度会比其他分组多1个字符。
修正后的解密代码
message = input("Enter a message: ") part = int(input('Into how many parts the cipher was split? ')) # 用int替代eval更安全 length = len(message) remainder = length % part groups = [] start = 0 # 拆分加密后的字符串为对应分组 for i in range(part): # 确定当前分组的长度,前remainder个分组多1个字符 group_length = length // part + (1 if i < remainder else 0) groups.append(message[start:start + group_length]) start += group_length decrypted = "" # 按顺序从每个分组取字符拼接原始消息 for idx in range(max(len(group) for group in groups)): for group in groups: if idx < len(group): decrypted += group[idx] print(decrypted)
修正逻辑说明
- 拆分分组:根据加密时的分组数,将加密后的字符串拆分为对应分组。当原字符串长度不能被分组数整除时,前
remainder个分组会比后面的多1个字符(和加密时的取数逻辑对应); - 还原顺序:循环每个位置索引,依次从每个分组中取出对应位置的字符并拼接,即可得到原始消息。
内容的提问来源于stack exchange,提问作者romanbouchouiev
相关产品推荐
相关产品推荐

