Python 中的凯撒密码无法解密

Decryption not working in Caesar cipher in Python

我的加密工作正常,但是当我运行解密代码时,它不起作用。当我到达那部分代码时,出现错误 -

cipher2 += cipher[(cipher(A)-key1)%(len(cipher2))]
TypeError: 'str' object is not callable

如果你能花时间帮助我,我将不胜感激。

alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
msgall = alphabetL + alphabetC + number + space
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))
cipher = ''
cipher2 = ''


for A in Question1:
    if A in alphabetL:
        cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
    elif A in alphabetC:
        cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
    elif A in number:
        cipher += number[(number.index(A)+key1)%Ln]
    elif A in space:
        cipher += space
    else:
        print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
print (cipher)

Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
    for A in cipher:
        cipher2 += cipher[(cipher(A)-key1)%(len(cipher2))]
    print (cipher2)

您可以创建一个用于加密和解密的函数。

alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
msgall = alphabetL + alphabetC + number + space
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))

cipher2 = ''

def ceaser_cipher(Question1,key1):
    cipher = ''
    for A in Question1:
        if A in alphabetL:
            cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
        elif A in alphabetC:
            cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
        elif A in number:
            cipher += number[(number.index(A)+key1)%Ln]
        elif A in space:
            cipher += space
        else:
            print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

    return cipher


cipher=ceaser_cipher(Question1,key1)
print (cipher)
Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
    cipher2=ceaser_cipher(cipher,-key1)
    print (cipher2)