2

I'm using a list of the alphabet, the user enters a keyword and the keyword gets indexed and added to the text you want to be encrypted. it does this however, if it is more than one character e.g. 'ab' it will only recognize it as the last character; '2' instead of '3'. Please help, thanks in advance

key = [123, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
   'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
   'x', 'y', 'z']

def encrypt(k, plaintext):
    result = ''

    for l in k:
        try:
            p = (key.index(l)) %26
            print p
    except ValueError:
        result += 1

    for l in plaintext:
        try:
           i = (key.index(l) + p) %26
           result += key[i]
           print i
    except ValueError:
        result += l

    return result.upper()
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 1
    Are you trying to implement a Caesar cipher? – reticentroot Oct 08 '15 at 14:29
  • 1
    Then take a look here, perhaps it can provide some insight, it's from my public repo, you can use it to write your own implementation, or fork it and do your own things. https://github.com/marcsantiago/CryptographyKit/blob/master/Cryptokit/CaesarCipher.py – reticentroot Oct 08 '15 at 14:41

1 Answers1

0

If your are implementing a Caesar cipher, you may want to take a look at this, which was taken from here https://inventwithpython.com/chapter14.html

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))
C. McCarthy
  • 102
  • 8