Reputation: 313
I created a Encrypter and Decrypter for the Vignere cipher. The encrypter works it turned "THE EAGLE HAS LANDED" into "WHZ RCOOE PNU OAILRF". However when I try to decrypt "WHZ RCOOE PNU OAILRF" using DAVINCI, it doesn't return THE EAGLE HAS LANDED. Instead it returns a random jumble "ZHU EEWRE XAW RADTEH". Is the issue in the decryptVignere or is it the previous functions? I know encryptVignere works perfectly.
"""
This program will decrypt/encrypt a Vignere with the Keyword: DaVinci
"""
# helper functions
# letter to index
def letterToIndex(ch):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
idx = alphabet.find(ch)
if idx < 0:
print ("error: letter not in the alphabet", ch)
return idx
# index to letter
def indexToLetter(idx):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
if idx > 25:
print ('error: ', idx, ' is too large')
letter = ' '
elif idx < 0:
print ('error: ', idx, ' is less than 0')
letter = ' '
else:
letter = alphabet[idx]
return letter
# looking up a letter in the Vignere square
def vignereIndex(keyLetter, plainTextLetter):
keyIndex = letterToIndex(keyLetter)
ptIndex = letterToIndex(plainTextLetter)
newIdx = (ptIndex + keyIndex) % 26
return indexToLetter(newIdx)
def decryptVignere(key, cipherText):
plainText = ""
keyLen = len(key)
for i in range (len(cipherText)):
ch = cipherText[i]
if ch == ' ':
plainText = plainText + ch
else:
plainText = plainText + vignereIndex(key[i%keyLen], ch)
return plainText
#encrypting a message using the Vignere cipher
def encryptVignere(key, plainText):
cipherText = ""
keyLen = len(key)
for i in range (len(plainText)):
ch = plainText[i]
if ch == ' ':
cipherText = cipherText + ch
else:
cipherText = cipherText + vignereIndex(key[i%keyLen], ch)
return cipherText
# decrypt
messageOne = "WHZ RCOOE PNU OAILRF" # raw_input("Enter your string: ")?
keyOne = "DAVINCI"
deStr = decryptVignere(keyOne, messageOne)
print deStr
Upvotes: 0
Views: 135
Reputation: 16651
Your decrypt method is exactly identical to your encrypt method! The decrypt method should do the opposite, i.e. subtract the key instead of adding it.
A possible solution is to add a parameter to your vignereIndex
method to toggle between encrypting and decrypting.
def vignereIndex(keyLetter, plainTextLetter, encrypt):
keyIndex = letterToIndex(keyLetter)
ptIndex = letterToIndex(plainTextLetter)
if not encrypt:
keyIndex *= -1
newIdx = (ptIndex + keyIndex) % 26
return indexToLetter(newIdx)
Upvotes: 1