Vignere密码解密函数未返回正确的解密python 2.7
我为Vignere密码创建了一个加密和解密程序。加密机工作了,它把鹰降落到了WHZ RCOOE PNU OAILRF。然而,当我试图用达芬奇解密WHZ RCOOE PNU OAILRF时,它并没有返回鹰已经着陆的消息。相反,它会返回一个随机的混乱。问题是在decryptVignere中还是在前面的函数中?我知道维格纳工作得很好Vignere密码解密函数未返回正确的解密python 2.7,python,encryption,Python,Encryption,我为Vignere密码创建了一个加密和解密程序。加密机工作了,它把鹰降落到了WHZ RCOOE PNU OAILRF。然而,当我试图用达芬奇解密WHZ RCOOE PNU OAILRF时,它并没有返回鹰已经着陆的消息。相反,它会返回一个随机的混乱。问题是在decryptVignere中还是在前面的函数中?我知道维格纳工作得很好 """ This program will decrypt/encrypt a Vignere with the Keyword: DaVinci """ # help
"""
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
您的解密方法与加密方法完全相同!解密方法应该做相反的事情,即减去密钥而不是添加密钥 一种可能的解决方案是向vignereIndex方法添加一个参数,以便在加密和解密之间切换
def vignereIndex(keyLetter, plainTextLetter, encrypt):
keyIndex = letterToIndex(keyLetter)
ptIndex = letterToIndex(plainTextLetter)
if not encrypt:
keyIndex *= -1
newIdx = (ptIndex + keyIndex) % 26
return indexToLetter(newIdx)
代码注释:您可以使用字典将字母转换为数字,反之亦然,而不是每次都查看字符串。@Dschoni:更干净的解决方案是使用字母的ascii值。将ord和chr用于转换Python不使用C样式的三元组。@wvdz:Python也不使用!为了否定。你用什么解释器来测试你的代码?@DSM:也解决了这个问题。你可能已经猜到了,我正在使用内部大脑编译器IBC。