使用 Caesar 密码算法,尝试解密输入的文本时,输出结果不正确。解密代码如下:
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ "
DMessage=input("Enter your message to decrypt")
UDMessage=DMessage.upper()
lenDMessage=len(UDMessage)
offset=(int(input("Enter what you would like your offset to be 0,25")))
offset=offset-2
for x in range(0,lenDMessage):
for y in range(-25,25):
if UDMessage[x]==alphabet[y+25]:
print(x,DMessage,[x], UDMessage[x],alphabet[y+25+offset])
加密的文本输入为 “Caesar code test run”, 但解密结果却是 “ecguctbeqfgbvgubbtwp”。无法正确解密,如何解决这个问题?
2、解决方案
以下是针对此问题的解决方案及代码示例:
解答 1
def shift(c,n=13,alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
u = c.upper()
if u not in alphabet: return c
s = alphabet[(alphabet.index(u)+n)%26]
if u!=c: s=s.lower()
return s
def caesar(s,n=13): return "".join(shift(c,n) for c in s)
def decaesar(s,n=13): return "".join(shift(c,-n) for c in s)
print(caesar('Puffo Burlone, dove vai?'))
print(decaesar(_))
print(caesar('Puffo Burlone, dove vai?',22))
print(decaesar(_,22))
print(caesar('Puffo Burlonè, dovè vai?'))
print(decaesar(_))
解答 2
def caesar_encrypt(plaintext, shift=13):
"""
Encrypts a plaintext string using the Caesar cipher.
Args:
plaintext (str): The plaintext string to encrypt.
shift (int, optional): The amount to shift each letter by. Defaults to 13.
Returns:
str: The encrypted ciphertext.
"""
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
start = ord('A')
else:
start = ord('a')
encrypted_char = chr((ord(char) - start + shift) % 26 + start)
ciphertext += encrypted_char
else:
ciphertext += char
return ciphertext
def caesar_decrypt(ciphertext, shift=13):
"""
Decrypts a ciphertext string using the Caesar cipher.
Args:
ciphertext (str): The ciphertext string to decrypt.
shift (int, optional): The amount to shift each letter by. Defaults to 13.
Returns:
str: The decrypted plaintext.
"""
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
start = ord('A')
else:
start = ord('a')
decrypted_char = chr((ord(char) - start - shift) % 26 + start)
plaintext += decrypted_char
else:
plaintext += char
return plaintext
print("Caesar cipher example:")
plaintext = "Hello, world!"
encrypted_text = caesar_encrypt(plaintext)
print(f"Plaintext: {plaintext}")
print(f"Encrypted text: {encrypted_text}")
decrypted_text = caesar_decrypt(encrypted_text)
print(f"Decrypted text: {decrypted_text}")
print("\nCustom shift example:")
custom_shift = 5
plaintext = "Top secret message"
encrypted_text = caesar_encrypt(plaintext, custom_shift)
print(f"Plaintext: {plaintext}")
print(f"Encrypted text: {encrypted_text}")
decrypted_text = caesar_decrypt(encrypted_text, custom_shift)
print(f"Decrypted text: {decrypted_text}")