2015-02-08 65 views
0

我制作了一个Python脚本,使用this video中描述的对称密钥算法来加密明文文件。然后,我创建了第二个脚本来解密加密的消息。以下是原文:Python - 加密和解密脚本产生偶然错误

I came, I saw, I conquered. 

这里是被加密和解密后的文字:

I came, I saw, I conquerdd. 

近乎完美,除了一个字母。对于更长的文本,将会有多个字母刚刚关闭,即出现的字符的数字表示比原始字符的数字表示低一个字母。我不知道这是为什么。

下面是我的脚本如何工作。首先,我生成了一个随机数字序列 - 我的PAD - 并将其保存在文本文件“pad.txt”中。我不会显示代码,因为它非常简单。然后我在“text.txt”中保存了要加密的文本。接下来,我跑了加密脚本,加密文本和文件“encryptedText.txt”将其保存:

#!/usr/bin/python3.4 
import string 

def getPad(): 
    padString = open("pad.txt","r").read() 
    pad = padString.split(" ") 
    return pad 

def encrypt(textToEncrypt,pad): 
    encryptedText = "" 
    possibleChars = string.printable[:98] # last two elements are not used bec 
              # ause they don't show up well on te 
              # xt files. 
    for i in range(len(textToEncrypt)): 
     char = textToEncrypt[i] 
     if char in possibleChars: 
      num = possibleChars.index(char) 
     else: 
      return False 
     encryptedNum = num + int(pad[(i)%len(pad)]) 
     if encryptedNum >= len(possibleChars): 
      encryptedNum = encryptedNum - len(possibleChars) 
     encryptedChar = possibleChars[encryptedNum] 
     encryptedText = encryptedText + encryptedChar 
    return encryptedText 

if __name__ == "__main__": 
    textToEncrypt = open("text.txt","r").read() 
    pad = getPad() 
    encryptedText = encrypt(textToEncrypt,pad) 
    if not encryptedText: 
     print("""An error occurred during the encryption process. Confirm that \ 
there are no forbidden symbols in your text.""") 
    else: 
     open("encryptedText.txt","w").write(encryptedText) 

最后,我解密这个脚本文字:

#!/usr/bin/python3.4 
import string 

def getPad(): 
    padString = open("pad.txt","r").read() 
    pad = padString.split(" ") 
    return pad 

def decrypt(textToDecrypt,pad): 
    trueText = "" 
    possibleChars = string.printable[:98] 
    for i in range(len(textToDecrypt)): 
     encryptedChar = textToDecrypt[i] 
     encryptedNum = possibleChars.index(encryptedChar) 
     trueNum = encryptedNum - int(pad[i%len(pad)]) 
     if trueNum < 0: 
      trueNum = trueNum + len(possibleChars) 
     trueChar = possibleChars[trueNum] 
     trueText = trueText + trueChar 
    return trueText 

if __name__ == "__main__": 
    pad = getPad() 
    textToDecrypt = open("encryptedText.txt","r").read() 
    trueText = decrypt(textToDecrypt,pad) 
    open("decryptedText.txt","w").write(trueText) 

两个脚本看起来很直接,他们明显的工作几乎完美。然而,每隔一段时间就有一个错误,我看不出为什么。

+3

似乎你需要调试:) – runDOSrun 2015-02-08 17:09:34

回答

1

我找到了解决这个问题的办法。事实证明,没有正确解密的每个角色都被加密为\r,我的文本编辑器无论出于何种原因都将其更改为\n。从可能出现的字符列表中删除\r解决了问题。