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-z
0...25
。
您的加密(即凯撒密码)然后将该范围向右移动key
的值,由于x = x % 26
而环绕。例如,如果key
为 5,则0
映射到5
,20
映射到25
,21
映射到0
,等等。
将修改后的字母表重新转换为 ASCII 字符,您需要重新添加回ord('a')
的代码点,因此chr(x + 97)
。