python - 凯撒密码按关键字的 ASCII 值而不是数字进行移位

标签 python encryption ascii

我被分配用 python 编写凯撒密码程序。我使用数字来移动/加密消息,但现在我需要使用关键字。关键字重复足够多的次数以匹配明文消息的长度。将关键短语的每个字母的字母值与明文消息的每个字母的字母值相加以生成加密文本。

MAX_KEY_SIZE = 26
def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
    print('Enter your message:')
    return input()
def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        key = int(input())
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key
def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''
    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key
            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26
            translated += chr(num)
        else:
            translated += symbol
    return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
getMode()
getMessage()
getKey()
getTranslatedMessage(mode, message, key)
getTranslatedMessage(mode, message, key)

最佳答案

要获取单词中所有字符的 ASCII 值相加(将单词转换为数字),此函数应该有效:

def word_to_num(word):
    word = str(word) #Check it is a string
    ascii_value = 0
    for i in word:
        ascii_value += ord(i) #You can use many operations here
    return ascii_value

在代码开头定义它,然后传入关键字将其转换为数字值。然后您可以使用您拥有的数字密码代码。

关于python - 凯撒密码按关键字的 ASCII 值而不是数字进行移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189370/

相关文章:

python - matplotlib 'bar'与 'barh'情节。 bar的问题

python - 继承子类 MRO 的别名

c - 荨麻双鱼 CBC

c# - 在Python中使用公共(public)模数和指数进行RSA加密密码

python - 为 ASCII 数据添加名称和分配数据类型

c++ - 为什么 strlen(s) 与 s 的大小不同,为什么 cout char 显示的是字符而不是数字?

python - Unicode 编码错误

python - 将单词中的字母频率与 R(或 python)中的 26 个字母进行匹配

java使用 key 对加密和解密?

arrays - 为什么我的矩阵值在 C 中消失了?