在Python中解密替换密码会为某些字母生成正确的替换,但不能替换其他字母

时间:2017-04-08 01:05:46

标签: python cryptography

为了帮助我学习Python,我一直在研究一个小脚本来解密Python Challenge上的简单替换密码。如果您想避免潜在的破坏者,请停在此处。

密文向后旋转两步,密文输入如下:

thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."

我使用的脚本如下所示,带有注释。

cipher = "abcdefghijklmnopqrstuvwxyz"

for letter in thread:
  if letter in cipher and cipher.index(letter) <= 23:    # if the character is in the alphabet and is between a-x...
    thread = thread.replace(letter, cipher[cipher.index(letter) + 2], 1)    # replace that letter with the one two letters after it, and save

  elif letter in cipher and cipher.index(letter) > 23:   # but if the character is y or z...
    thread = thread.replace(letter, cipher[cipher.index(letter) - 24], 1)    # replace those with a and b, respectively

print(thread)

这产生了输出:

o hoti ioi hihtt tterapati it ha hand. thaty uhat aoonutets ate dot. doine it in dw hand is ineddiaient and thyt's ufw rfis rexr gs so none. ssgne srrgne.oyierpyns() gs peammkcnbcb. lmu ynnlw ml rfc spl.

向我伸出的是第一个字母(g)被错误地转换了8个步骤。但是,第二个字母(f)通过2个步骤正确转换。其他不正确的字母似乎以不同的金额转换。我回去拆开了我的代码,检查各个部分是否有效:

print(cipher[cipher.index("g") + 2]) # this bit is functional and converts letters a-x by a shift of 2. more specifically, it does CORRECTLY convert g to i.

print(cipher[cipher.index("y") - 24]) # this is functional too and converts y and z

我不确定这个脚本有什么问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

好的,这就是我根据你的代码解决它的方法:

thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
cipher = "abcdefghijklmnopqrstuvwxyz"
thread_decrypted = ''  ## I used an empty string to append the rotated letters ##

for letter in thread:
    if letter in cipher : 
        if cipher.index(letter) <= 23 : 
            thread_decrypted += cipher[ cipher.index(letter) + 2 ]  
        else :  
            thread_decrypted += cipher[ cipher.index(letter) -24 ]  
    else : 
        thread_decrypted += letter

print(thread_decrypted)  

更简单,更多&#39; pythonic&#39;方式是这样的:

thread = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
cipher = "abcdefghijklmnopqrstuvwxyz"  
thread_decrypted = ''.join( cipher[ ( cipher.index(l) + 2 ) % 26 ] if l in cipher else l for l in thread )
print(thread_decrypted)  

这基本上是你在一行中的for循环(list comprehension)。

您的代码存在的问题是您使用replace() 每次迭代原始字符串都会发生变异 (&#39; a&#39;变成&#39; c,然后变成&#39;等等),
这就是为什么你会得到错误。

我希望这会有所帮助,祝你学习好运