Python教程2-实现凯撒密码(移位密码)

2021-12-14 12:12:19 浏览数 (1)

作者: zifanwang  发布于2020-05-23

凯撒密码也叫移位密码 它是一个很古老的加密解密方法。 最初由凯撒大帝使用。 原理如下: ●密钥是一个随机数

加密:

●密文每一位的ascii码 = 明文每一位的ascii码 密钥

解密:

●明文每一位的ascii码 = 密文每一位的ascii码 - 密钥 python代码:

代码语言:javascript复制
def main():
    myMessage = "Common sense is not so common."
    myKey = 8
    ciphertext = encryptMessage(myKey, myMessage)
    print("ciphertext: " ciphertext)
    text = decryptMessage(myKey, ciphertext)
    print("plaintext: " text)
def encryptMessage(key, message):
    return ''.join([chr(ord(c) key) for c in message])
def decryptMessage(key, message):
    return ''.join([chr(ord(c)-key) for c in message])
if __name__ == '__main__':
    main()

运行结果:

代码语言:javascript复制
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
====================== RESTART: D:/zifan/my file/unit1.py ======================
ciphertext: Kwuuwv({mv{m(q{(vw|({w(kwuuwv6
plaintext: Common sense is not so common.
>>> 

0 人点赞