Python简单Vignere解密函数

2024-09-27 21:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有作业。现在很晚了,我的大脑功能不太好。 我的最终结果中有以下函数(但我必须使用它们):

def letterToIndex(char):
    az = "abcdefghijklmnopqrstuvwxyz "
    idx = az.find(char)
    if idx < 0:
        print ("err: not in here ", char)
    return idx

def indexToLetter(idx):
    az = "abcdefghijklmnopqrstuvwxyz "
    if idx > 25:
        print ("err: ", idx, " too large")
        letter = ''
    elif idx < 0:
        print "err: ", idx , "should not be this"
    else:
    return letter

另外,这一个,显然是一个导致问题(我仍然不清楚如何扭转模式26):

def vigneIndex(keylet, plainlet):
    keyIdx = letterToIndex(keylet)
    plainIdx = letterToIndex(plainlet)
    newIdx = (plainIdx + keyIdx) % 26
    return indexToLetter(newIdx)

最后是我的加密/解密程序:

def encryptVigne(key,string):
    cipher = ''
    keyLen = len(key)
    for i in range(len(string)):
        char = string[i]
        if char == ' ':
            cipher = cipher + char
        else:
            cipher = cipher + vigneIndex(key[i%keyLen], char)
    return cipher

加密机工作。你知道吗

nkey = 'abc'
print nkey
print encryptVigne(nkey, 'testing')
cip = encryptVigne(nkey, 'testing')

def undoVigne(key,cipher):
    string = ''
    keyLen = len(key)
    for i in range(len(cipher)):
        char = cipher[i]
        if char == ' ':
            string = string + char
        else:
            string = string + vigneIndex(key[i%keyLen], char)
    return string

但是解密并不能解密它。有人告诉我,这就像颠倒过程一样简单,但很明显,我在这幅图中遗漏了一些东西。你知道吗


Tags: keystringlenreturnifdefazerr
2条回答

我没有对它进行测试,但从飞行视图来看,您的函数indexToLetter似乎工作不正常。试着用这个来改变它:

def indexToLetter(idx):
    az = "abcdefghijklmnopqrstuvwxyz"
    if idx > 25:
        print("err: ", idx, " too large")
        return ''
    elif idx < 0:
        print("err: ", idx , "should not be this")
        return ''
    else:
        return az[idx]

但是如果idx错误,则应该引发异常,而不是将消息打印到输出流。你知道吗

真的有密码解密吗?你知道吗

例如,在反转过程(解密)时,在函数:encryptVigne中,您不应该采取:

newIdx = (plainIdx - keyIdx) % 26

要反转加密时所做的操作,请执行以下操作:

newIdx = (plainIdx + keyIdx) % 26

相关问题 更多 >

    热门问题