Caesar Cipher解码不起作用

时间:2014-11-17 13:44:25

标签: python encryption

我试图让凯撒密码工作,我可以获得编码,但不使用-shift进行解码。我认为它可能是真的,并没有什么成功

提前全部谢谢

def helper(message, shift):
    message = message.lower()

    secret = ""
    for c in message:
        if c in "abcdefghijklmnopqrstuvwxyz":
            num = ord(c)
            num += shift
            if num > ord("z"):     # wrap if necessary
                num -= 26
            elif num < ord("a"):
                num += 26
            secret = secret + chr(num)
        else:
        # don't modify any non-letters in the message; just add them as-is
            secret = secret + c
    return secret

#   Encrypts the given string using a Caesar cipher and returns the result.


def encrypt(message):
        return helper(message, x)

#   Decrypts a string that was previously encrypted using a Caesar cipher and returns the result.
def decrypt(message):
    return helper(message, x)




t=input('e or d ')
msg = input("Your message to encode? ")
x = int(input('no '))


if len (msg) > 0:
# wants to encrypt
    secret = encrypt(msg)
    print("The encoded message is:", secret)
else:
# empty message; wants to decrypt
    secret = input("Your message to decode? ")
    if len(secret) > 0:
        msg = decrypt(secret)
        print("The decoded message is:" ,msg)

1 个答案:

答案 0 :(得分:1)

解密应该在加密的相反方向上转移。

def decrypt(message):
    return helper(message, -x)

现在您可以使用相同的密码进行解密和加密。

x = 5
msg = "hello"
print("plaintext message:", msg)
print("encrypted message:", encrypt(msg))
print("decrypted message:", decrypt(encrypt(msg)))

结果:

plaintext message: hello
encrypted message: mjqqt
decrypted message: hello