我为Vignere密码创建了一个加密器和解密器。加密器将它变成了“THE EAGLE已经登陆”进入“WHZ RCOOE PNU OAILRF”。但是,当我尝试使用DAVINCI解密“WHZ RCOOE PNU OAILRF”时,它并没有返回THE EAGLE已登陆。相反,它返回一个随机的混乱“ZHU EEWRE XAW RADTEH”。问题是解密Vignere还是以前的功能?我知道encryptVignere非常有效。
"""
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
答案 0 :(得分:1)
您的解密方法与您的加密方法完全相同!解密方法应该相反,即减去密钥而不是添加密钥。
一种可能的解决方案是在vignereIndex
方法中添加一个参数,以便在加密和解密之间切换。
def vignereIndex(keyLetter, plainTextLetter, encrypt):
keyIndex = letterToIndex(keyLetter)
ptIndex = letterToIndex(plainTextLetter)
if not encrypt:
keyIndex *= -1
newIdx = (ptIndex + keyIndex) % 26
return indexToLetter(newIdx)