pythonpython-3.xencryptionwhitespacevigenere

Spacing in a single letter viginere cipher


Trying to account for spacing/whitespaces in a viginere cipher in python. this is a single letter encryption.

Please note that i'm very new to python!

def encrypt(message, key):
    '''Vigenere encryption of message using key.'''

    # Converted to uppercase.
    # Non-alpha characters stripped out.
    message = filter(str.isalpha, message.upper())

    def enc(c, k):
        '''Single letter encryption.'''

        return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))

    return ''.join(starmap(enc, zip(message, cycle(key))))


def decrypt(message, key):
    '''Vigenere decryption of message using key.'''

    def dec(c, k):
        '''Single letter decryption.'''

        return chr(((ord(c) - ord(k) - 2 * ord('A')) % 26) + ord('A'))

    return ''.join(starmap(dec, zip(message, cycle(key))))

Have already tried this but it does not work

def enc(c, k):
        '''Single letter encryption.'''
        if ord(c) == 32:
            return chr(ord(c))
        else:
            return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))

This is what i get with my current code:

"Hello World" --> "JKJLJYUPLY" key = "wasup"

I want:

"Hello world" --> "JKJLJ YUPLY" key "wasup"

Solution

  • I didn't really documented myself on the encryption method itself, but I tested it word by word and it worked well :

    to_encrypt = 'Hello World'
    my_key = 'wasup'
    
    encrypted = []
    
    for word in to_encrypt.split():
        encrypted.append(encrypt(word, my_key))
    
    print(' '.join(encrypted))
    

    prints JKJLJ YUPLY

    That could be the way to use it if the viginere cipher is only supposed to be applied words by words.