凯撒密码是一种简单的替换密码,通过将明文中的每个字母按照固定的位移量进行替换来加密文本。下面是一个使用Python实现凯撒密码的示例代码:
def caesar_encrypt(text, shift):encrypted_text = ""for char in text:if char.isalpha():将字符转换为大写char = char.upper()计算字符移动后的位置shifted = (ord(char) - ord('A') + shift) % 26将移动后的字符添加到加密文本中encrypted_text += chr(shifted + ord('A'))else:非字母字符保持不变encrypted_text += charreturn encrypted_textdef caesar_decrypt(text, shift):decrypted_text = ""for char in text:if char.isalpha():将字符转换为大写char = char.upper()计算字符移动前的位置shifted = (ord(char) - ord('A') - shift) % 26将移动前的字符添加到解密文本中decrypted_text += chr(shifted + ord('A'))else:非字母字符保持不变decrypted_text += charreturn decrypted_text[1:] 去掉末尾的换行符
使用示例:
plaintext = "Hello, World!"shift = 3encrypted_text = caesar_encrypt(plaintext, shift)print("Encrypted text:", encrypted_text)decrypted_text = caesar_decrypt(encrypted_text, shift)print("Decrypted text:", decrypted_text)
输出:
Encrypted text: KHOOR, ZRUOG!Decrypted text: Hello, World!
这个示例代码定义了两个函数`caesar_encrypt`和`caesar_decrypt`,分别用于加密和解密文本。在加密函数中,每个字母都根据位移量向后移动,而在解密函数中,每个字母都根据位移量向前移动以恢复原始文本。

