我正在用 python3 学习密码学
现在我正在研究凯撒密码,这是我的问题
我尝试使用 key 16 加密“hdjdyueeeje” 这就是结果 "zwzt??uuzu"
你能解释一下我做错了什么以及如何解决吗
我的代码:
print("\n----------------Caesar_Cipher----------------\n")
print(' 1) Crypt mode')
print(" 2) Decrypt mode")
try:
mode = int(input('\n [#] Enter number what you need (1,2) : '))
if mode == 1:
print("\n--------Crypting process is starting---------")
key = int(input("\n [#] Enter here key which will be used to crypt data \n (number from 1 to 25 including) --> "))
if 1 >= key or key > 25:
print(" You choosed wrong number. I will make it 1 automatically")
key = 1
else:
pass
msg = input("\n [#] Now enter your message what you wanna crypt \
\n -->")
print("")
msgc = ""
for letter in msg:
x = ord(letter)
y = chr(x + key)
msgc += y
print('\n Crypted data -->',msgc)
elif mode == 2:
print("\n-------Decrypting process is starting--------")
key = int(input("\n [#] Enter here key which will be used to decrypt data \n (number from 1 to 25 including) --> "))
if 1 >= key or key > 25:
print(" You choosed wrong number. I will make it 1 automatically")
key = 1
else:
pass
msg = input("\n [#] Now enter your message what you wanna decrypt \
\n -->")
print("")
msgd = ""
for letter in msg:
x = ord(letter)
y = chr(x - key)
msgd += y
print('\n Decrypted data -->',msgd)
else:
print("Number not defined")
就这样
请您参考如下方法:
你的问题在这里:
x = ord(letter)
y = chr(x + key) # <- problem
msgc += y
如果没有足够的字母留下更高的代码,字母表需要环绕。例如,当您尝试加密 y
时,您只能加 1 才能得到 z
。如果 key 为 2,则需要环绕并返回到 a
。这种“环绕”可以很容易地通过减去字母表的长度来完成。此版本的代码有效:
x = ord(letter)
y = x + key
if y > ord('z'):
y -= 26
msgc += chr(y)
请注意,这仅适用于小写字母。