Vigenere cipher not working

情到浓时终转凉″ 提交于 2020-01-05 02:29:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32126091/vigenere-cipher-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!