Python - 加密和解密脚本偶尔会产生错误
Posted
技术标签:
【中文标题】Python - 加密和解密脚本偶尔会产生错误【英文标题】:Python - encryption and decryption scripts produce occasional errors 【发布时间】:2015-02-08 17:06:19 【问题描述】:我使用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)
这两个脚本看起来都非常简单,而且它们显然几乎完美地工作。但是,每隔一段时间就会出现错误,我不明白为什么。
【问题讨论】:
看来你需要调试 :) 【参考方案1】:我找到了解决这个问题的方法。事实证明,每个未正确解密的字符都被加密为\r
,我的文本编辑器出于某种原因将其更改为\n
。从可能的字符列表中删除 \r
解决了该问题。
【讨论】:
以上是关于Python - 加密和解密脚本偶尔会产生错误的主要内容,如果未能解决你的问题,请参考以下文章
实用脚本!利用 Python 对 PDF 进行加密解密操作,代码拿走就用!
实用脚本!利用 Python 对 PDF 进行加密解密操作,代码拿走就用!