2025年凯撒密码加密算法python(凯撒密码加密解密python)

凯撒密码加密算法python(凯撒密码加密解密python)以下是 Python 实现 凯撒密码 加密 和解密 的示例代码 加密 python def caesar encrypt plain text shift em 凯撒密码 em em 加密 em param plain text 明文 param

大家好,我是讯享网,很高兴认识大家。

以下是Python实现凯撒密码加密解密的示例代码:

加密

def caesar_encrypt(plain_text, shift): &quot;&quot;&quot; <em>凯撒密码</em><em>加密</em> :param plain_text: 明文 :param shift: 移位数 :return: 密文 &quot;&quot;&quot; cipher_text = &#39;&#39; for char in plain_text: if char.isalpha(): cipher_text += chr((ord(char) - ord(&#39;a&#39;) + shift) % 26 + ord(&#39;a&#39;)) else: cipher_text += char return cipher_text 

讯享网

解密


讯享网

讯享网def caesar_decrypt(cipher_text, shift): &quot;&quot;&quot; <em>凯撒密码</em><em>解密</em> :param cipher_text: 密文 :param shift: 移位数 :return: 明文 &quot;&quot;&quot; plain_text = &#39;&#39; for char in cipher_text: if char.isalpha(): plain_text += chr((ord(char) - ord(&#39;a&#39;) - shift + 26) % 26 + ord(&#39;a&#39;)) else: plain_text += char return plain_text 

使用示例:

plain_text = &#39;hello world&#39; shift = 3 cipher_text = caesar_encrypt(plain_text, shift) print(cipher_text) # khoor zruog decrypted_text = caesar_decrypt(cipher_text, shift) print(decrypted_text) # hello world 

注:以上代码中,只考虑了小写字母的情况。如果需要加密解密大写字母或其他字符,请自行修改代码。


小讯
上一篇 2025-04-14 10:12
下一篇 2025-06-02 15:40

相关推荐

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