使用自己的密码字典加密

Encryption with own Cipher Dictionary

这是我的代码:

dictionary = {'A':'3',
'B':'u',
'C':'t',
'D':'5',
'E':'b',
'F':'6',
'G':'7',
'H':'8',
'I':'/',
'J':'9',
'K':'0',
'L':'-',
'M':'o',
'N':'i',
'O':';',
'P':'}',
'Q':'c',
'R':'n',
'S':'4',
'T':'m',
'U':'.',
'V':'y', 
'W':'v',
'X':'r', 
'Y':',',
'Z':'e',
}
print(dictionary)
inp = input(str("What do you want me to encode?").upper()).upper()
li = list(inp)
print(li)
for letter in inp:
    pass

我想问一下如何使用这本字典来加密通过输入的任何消息。就像 'Hello my name is Jerry' 会变成:(没有短语)'8b--; o, i3ob /4 9bnn,'. 有人可以帮我解决这个问题吗?我看到其他类似的问题被问到 - 但他们使用 PyCrypto。我不想经历安装它的麻烦。有人可以帮帮我吗

谢谢, 杰瑞

你需要将用户输入的每一个字符都通过字典,才能得到cypher值。

# removed the first .upper() here
inp = input(str("What do you want me to encode?")).upper()
li = list(inp)
print(li)

# create a list of letters passed through the dictionary
out = [dictionary[letter] for letter in inp]

# using ''.join makes the new list a single string
print(''.join(out))

您可以使用str.translate方法。这里的好处是您只需创建一次 table,因此即使您有很多字符串要加密,也可以使用相同的 table。

table = str.maketrans(dictionary) # create a translate table

inp = input("What do you want me to encode? ").upper()
res = inp.translate(table)
print(res)