python凯撒密码加密代码_python教程

python凯撒密码加密代码_python教程凯撒密码是一种简单的替换密码 通过将明文中的每个字母按照固定的位移量进行替换来加密文本 下面是一个使用 Python 实现凯撒密码的示例代码 pythondef caesar encrypt text shift encrypted text for char in text if char isalpha 将字符转换为大写 char char upper

凯撒密码是一种简单的替换密码,通过将明文中的每个字母按照固定的位移量进行替换来加密文本。下面是一个使用Python实现凯撒密码的示例代码:

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 += char

return encrypted_text

def 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 += char

return decrypted_text[1:] 去掉末尾的换行符

使用示例:

python

plaintext = "Hello, World!"

shift = 3

encrypted_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`,分别用于加密和解密文本。在加密函数中,每个字母都根据位移量向后移动,而在解密函数中,每个字母都根据位移量向前移动以恢复原始文本。

编程小号
上一篇 2026-03-18 10:32
下一篇 2026-03-18 10:26

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/72002.html