python - Python ASCII 加密程序
问题描述
再会,
我创建了一个简单的 ASCII 加密程序,但我只有 3 个问题:
- 我如何检查输入的密钥是否错误,并告诉我的程序在输入错误时不要尝试解密。
- 为什么密文比原文长?
- 如果我想加密其他东西而不是 ASCII 文本会有多难?
谢谢,下面是我的代码和结果:
import time
key = "This■isôthe╝key¦b££glkHPAfgbm(*&%$$*(■ô▀"
string = "Encryption the hell out of me, even if I repeatttttttt lettersssss you can't tell"
entext = ""
detext = ""
keycnt=0
print("Displaing Text to be Encrypted")
time.sleep(1)
print(string)
time.sleep(5)
#Loops through the string and the key and adds the ascii values together to create a Encrypted character
for sLetter in string:
entext += chr(ord(sLetter) + ord(key[keycnt]))
keycnt += 1
if keycnt == len(key):
keycnt =0
print("Displaying encrypted Text")
time.sleep(1)
print(entext)
#Resetting key position
keycnt=0
#Loops through the string and the key and subtracts the ascii values together to create a decrypted character
for sLetter in entext:
detext += chr(ord(sLetter) - ord(key[keycnt]))
keycnt += 1
if keycnt == len(key):
keycnt =0
time.sleep(2)
print("Displaying decrypted Text")
time.sleep(1)
print(detext)
time.sleep(1)
解决方案
首先,密钥字符的加法不是一个好的密码,甚至不是一个好的凯撒或维吉尼亚密码。为此,您需要模块化添加:普通字母表的模数 26(但没有大写或小写字母和其他字符)或字节的模数 256。对于字节,您需要为密钥的每个字节指定一个随机值。
目前,您的密文有一个偏差:如果您要添加一个带有 0x00 的字符值和一个值为 0x00 的密钥,那么您将获得 0x00 作为密文字节。问题在于,只有在您的加密方案中使用该特定组合才能达到值 0x00。因此,如果您看到值 0x00,那么您将立即知道密钥和明文值。
我如何检查输入的密钥是否错误,并告诉我的程序在输入错误时不要尝试解密。
无法检查密钥的值是否正确。您唯一能做的就是验证输出是否符合您的预期。
现代密码学使用消息认证码 (MAC) 来创建认证标签。这个标签可以根据密文和密钥(或者,对于不太安全的方案,明文和密钥)进行验证。还有一些经过身份验证的加密模式,例如 GCM,它们基本上是内置 MAC 身份验证的密码。
为什么密文比原文长?
如果您添加值为 255 或更低的值,那么您将获得 510 或更低的值。然而,这些值至少需要两个字节来编码。
如果我想加密其他东西而不是 ASCII 文本会有多难?
没那么难:只需使用真正随机的密钥执行 XOR 或模加法(例如 8 位/一个字节的模 256)。但是,要创建任何安全的东西,您可以使用一次性密码(其中密钥与二进制明文大小相同)或现代密码。
推荐阅读
- python - 带有双标头的 DataFrame 散点图
- php - 在 Laravel 中接收 Notificatoin Pusher + Echo
- slimbox - 在 Slimbox 中定位
- node.js - nodejs Puppeteer 缓存
- c# - 如何将控制台输出发送到我的电子邮件?
- javascript - 在嵌套循环中将条目推送到数组中
- mysql - 仅选择符合条件的值
- reporting-services - SSRS 2017 加载 QRCoder 版本 1.3.6.0 时出错
- python - 获取与其他约束相结合的行中最小值的索引
- python-3.x - Python:文件中的反斜杠 (\u...)