【问题标题】:Caesar cipher shift by ASCII values of a keyword rather than a number凯撒密码通过关键字的 ASCII 值而不是数字进行移位
【发布时间】:2015-03-21 23:47:32
【问题描述】:

我被分配用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)

【问题讨论】:

  • Vigenère cipher,好像和你想做的很接近。
  • 对于num -= 26,最好使用num %= 26,以防万一。

标签: python encryption ascii


【解决方案1】:

要获取单词中所有字符的附加 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

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

【讨论】:

    猜你喜欢
    • 2014-09-28
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2019-12-09
    相关资源
    最近更新 更多