首页 > 解决方案 > Python ASCII 加密程序

问题描述

再会,

我创建了一个简单的 ASCII 加密程序,但我只有 3 个问题:

  1. 我如何检查输入的密钥是否错误,并告诉我的程序在输入错误时不要尝试解密。
  2. 为什么密文比原文长?
  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)

标签: pythonencryptioncryptographyascii

解决方案


首先,密钥字符的加法不是一个好的密码,甚至不是一个好的凯撒或维吉尼亚密码。为此,您需要模块化添加:普通字母表的模数 26(但没有大写或小写字母和其他字符)或字节的模数 256。对于字节,您需要为密钥的每个字节指定一个随机值。

目前,您的密文有一个偏差:如果您要添加一个带有 0x00 的字符值和一个值为 0x00 的密钥,那么您将获得 0x00 作为密文字节。问题在于,只有在您的加密方案中使用该特定组合才能达到值 0x00。因此,如果您看到值 0x00,那么您将立即知道密钥和明文值。

我如何检查输入的密钥是否错误,并告诉我的程序在输入错误时不要尝试解密。

无法检查密钥的值是否正确。您唯一能做的就是验证输出是否符合您的预期。

现代密码学使用消息认证码 (MAC) 来创建认证标签。这个标签可以根据密文和密钥(或者,对于不太安全的方案,明文和密钥)进行验证。还有一些经过身份验证的加密模式,例如 GCM,它们基本上是内置 MAC 身份验证的密码。

为什么密文比原文长?

如果您添加值为 255 或更低的值,那么您将获得 510 或更低的值。然而,这些值至少需要两个字节来编码。

如果我想加密其他东西而不是 ASCII 文本会有多难?

没那么难:只需使用真正随机的密钥执行 XOR 或模加法(例如 8 位/一个字节的模 256)。但是,要创建任何安全的东西,您可以使用一次性密码(其中密钥与二进制明文大小相同)或现代密码。


推荐阅读