理解加密程序中的逻辑/数学所需的建议


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(97) 的 ASCII 值。如行中所示:

x = ord(character) - 97

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

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

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

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

最新更新