我已经尝试了很长时间尝试创建关键字密码,以便我可以创建一个密码应用。但我似乎无法做到正确,我只能创建一个普通的密码,有人可以请将我的代码更改为关键字密码
import string
alphabet = string.ascii_lowercase
message = input('Please insert the message you want to encrypt: ')
key = int(input('What key value do you want in your encryption? '))
output = []
for m in message:
if m in alphabet:
output.append(alphabet[(alphabet.index(m) + key) % (len(alphabet))])
print(''.join(output))
message1 = input('please inset what you want to decrypt:')
key1 = int(input('please insert the key value wanted:'))
output = []
for m in message1:
if m in alphabet:
output.append(alphabet[(alphabet.index(m) - key1) % (len(alphabet))])
print(''.join(output))
print('thanks for coding!')
答案 0 :(得分:0)
首先,您必须输入关键字而不是简单值,并将密钥的每个字母的值存储在列表中:
key1 = input('please insert the key value wanted:')
keys = [ alphabet.index(m) + 1 for m in key1 if m in alphabet ]
例如,密钥abc
会提供[1, 2, 3]
然后在计算编码字符串时迭代该列表:
for i, m in enumerate(message):
if m in alphabet:
output.append(alphabet[(alphabet.index(m) + keys[i % len(keys)])
% (len(alphabet))])
使用- keys[...]
而不是+ keys[...]
进行解码仍然是一样的,它应该可以正常工作