""" Sure! 以下是一个简单的凯撒密码加密和解密的def函数: """ # noinspection PyShadowingNames def caesar_encrypt(text, shift): encrypted_text = "" for char in text: if char.isalpha(): ascii_offset = ord('A') if char.isupper() else ord('a') encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset) encrypted_text += encrypted_char else: encrypted_text += char return encrypted_text # noinspection PyShadowingNames def caesar_decrypt(encrypted_text, shift): decrypted_text = "" for char in encrypted_text: if char.isalpha(): ascii_offset = ord('A') if char.isupper() else ord('a') decrypted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset) decrypted_text += decrypted_char else: decrypted_text += char return decrypted_text """ 以上是一个简单的凯撒密码加密和解密的def函数。 `caesar_encrypt`函数将给定的文本按照指定的偏移量进行加密,`caesar_decrypt`函数将加密后的文本按照相同的偏移量进行解密。 注意,这里的偏移量为整数,正数表示向右移动,负数表示向左移动。 """ """ `caesar_encrypt`函数使用凯撒密码算法将给定的文本加密成密文, `caesar_decrypt`函数使用相同的偏移量将密文解密回原文。 你可以通过调用这两个函数来加密和解密文本。例如: """ text = "Hello, World!" shift = 1 encrypted_text = caesar_encrypt(text, shift) print(encrypted_text) # 输出: Khoor, Zruog! decrypted_text = caesar_decrypt(encrypted_text, shift) print(decrypted_text) # 输出: Hello, World! """ 在这个例子中,我们使用偏移量为3对文本进行加密,然后再使用相同的偏移量对密文进行解密。最终得到的结果应该与原始文本相同。 请注意,在凯撒密码中,偏移量是循环的,所以偏移量为26的倍数时,加密和解密结果会与原文相同。 """
凯撒密码加密和解密
最新推荐文章于 2024-07-06 12:03:33 发布