Search code examples
pythonencryptionvigenere

Vigenere cipher not working


So my teacher created this vigenere cipher and he said it was working. However, after checking its results with online vigenere ciphers it appears to not be resulting with the correct encryptions.

I have no idea how to fix it and I was wondering if someone could direct me to the errors, and tell me how to fix them.

Here is the code

base = ord("a")
alphabets = 'abcdefghijklmnopqrstuvwxyz'  
keyword = input('What is your keyword')
message = input('What is your message to be coded or encoded?').lower()

expandedKeyword = ""
while len(expandedKeyword) < len(message): 
    for i in keyword:
        if len(expandedKeyword) < len(message): 
            expandedKeyword += i 


cipheredMessage = '' 
indexofKeyword = 0
for i in message:
        if i == ' ':
            cipheredMessage = cipheredMessage + " "
        else:
            shiftedIndex = (ord(i) + ord(expandedKeyword[indexofKeyword])-base) % 26 +base
            cipheredMessage = cipheredMessage + chr(shiftedIndex)
            indexofKeyword = indexofKeyword + 1



print(cipheredMessage)

I understand the concept of what is happening, but I cant seem to figure out the error.


Solution

  • Your calculation of shiftedIndex is wrong, you need to subtract base twice , but you are currently only subtracting it once. Example -

    shiftedIndex = (ord(i) + ord(expandedKeyword[indexofKeyword])-2*base) % 26 +base
    

    This is because you need to subtract base first time from ord(i) to get the index of i (from 'a') , and the second time from ord(expandedKeyword[indexofKeyword]) , to get the index of that character (from 'a' ) . So it should look like (for better understanding) -

    shiftedIndex = ((ord(i) - base) + (ord(expandedKeyword[indexofKeyword])-base)) % 26 + base