【问题标题】:Advice required in understanding the logic/maths in encryption program了解加密程序中的逻辑/数学所需的建议
【发布时间】:2019-11-17 14:22:44
【问题描述】:
userPhrase = input('Enter a single word phrase to be encrypted: ') 
userPhrase = userPhrase.lower() 
key = int(input('Enter a key: ')) 
encryptedPhrase = '' 

for character in userPhrase: 
    x = ord(character) - 97
    x += key
    x = x % 26
    encryptedPhrase += chr(x + 97)

print('Encrypted phrase is ' + encryptedPhrase) 

我在上面编写了一个简单的加密程序,主要遵循在线指南,但是我阅读的所有材料都没有充分解释为什么加密字符的 ASCII 值被 A 的 ASCII 值减去/减少(97)。如行中所示:

x = ord(character) - 97

任何解释都会很棒,提前谢谢!

【问题讨论】:

  • 检查chr(97)的输出。

标签: python encryption ascii


【解决方案1】:

在 ASCII 中,小写字母 a-z 从点 ord('a') == 97 开始。因此,ord(character) - 97a-z 映射到整数范围0...25

您的加密是凯撒密码,然后将该范围向右移动key 的值,由于x = x % 26 而回绕。例如,如果key 为5,则0 映射到520 映射到2521 映射到0,等等。

将这个修改后的字母转换回 ASCII 字符,您需要添加回 ord('a') 的代码点,因此 chr(x + 97)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多