Montgomery G.
Montgomery G.

Reputation: 13

Caesar cipher shift by ASCII values of a keyword rather than a number

I have been assigned to write a Caesar cipher program in python. I used a number to shift/encrypt the message but now I need to use a keyword. The keyword is repeated enough times to match the length of the plaintext message. The alphabet value of each letter of the key phrase is added to the alphabet value of each letter of the plaintext message to generate the encrypted text.

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)

Upvotes: 1

Views: 3569

Answers (1)

jkd
jkd

Reputation: 1045

To get the added ASCII values of all the characters in the word (convert word into numbers), this function should work:

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

Define this at the start of your code then pass in the keyword to convert it into a number value. Then you can use the code you have for the number cipher.

Upvotes: 2

Related Questions