我编写了一个Python脚本,使用this video中描述的对称密钥算法加密明文文件。然后我创建了第二个脚本来解密加密的消息。原文如下:
I came, I saw, I conquered.
以下是加密和解密后的文本:
^{pr2}$
几乎完美,除了一个字母。对于较长的文本,将有多个字母刚好偏离,即字符的数字表示比原始字符的数字表示低一个。我不知道为什么会这样。在
下面是我的脚本是如何工作的。首先,我生成了一个随机数字序列—我的PAD—并将其保存在文本文件中。”键盘.txt”. 我不展示代码,因为它太简单了。然后我保存了要加密的文本“文本.txt”. 接下来,我运行加密脚本,它对文本进行加密并将其保存在文件中”加密文本.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)
这两个脚本看起来都非常简单,显然它们几乎完美地工作。但是,偶尔会有一个错误,我不明白为什么。在
Tags:
文本txt脚本lenreturnifopenpadtexttoencryptpossiblecharsencryptedtexttexttodecrypttruetexttruenumencryptednum1条回答网友
1楼 ·
发布于 2023-03-07 00:09:57
我找到了解决这个问题的办法。结果发现,每一个未正确解密的字符都被加密为\r
,不管出于什么原因,我的文本编辑器将其改为\n
。从可能的字符列表中删除\r
修复了此问题。在
Python加密和解密脚本偶尔会产生错误
https://www.sunnyrainsolutions.nl/2019/10/24/tuinvisie-neemt-de-rainwinner-op-in-hun-tuinassortiment/tuinvisielogonieuw/
Python加密和解密脚本偶尔会产生错误
http://www.coffretderelayage.fr/bonjour-tout-le-monde/?cid=6646
Python加密和解密脚本偶尔会产生错误
https://humanplotholes.com/2020/05/23/episode-1-on-the-existence-of-god/comment-page-6/
Python加密和解密脚本偶尔会产生错误
https://www.univ-chlef.dz/eds/?article=دور-الكليات-الجامعية-في-التنمية-الاجت
Python加密和解密脚本偶尔会产生错误
https://www.sikhreligion.net/party-queen/
Python加密和解密脚本偶尔会产生错误
https://insaaf99.com/blog/stamp-duty-and-registration-charges-in-delhi/
Python加密和解密脚本偶尔会产生错误
https://cyclause.com/showing-hatha-yoga-mantras-and-attestations/