admin管理员组

文章数量:1575526

 一、什么是凯撒密码

        “在密码学中,恺撒密码(英语:Caesar cipher),或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系。”

        关于凯撒密码的详细介绍:恺撒密码_百度百科

 二、python实现凯撒加密

凯撒密码程序的源代码 :
        在文件编辑器中建立.py文件,并将其保存为caesarCipher.py。然后将本文配套资源 
中的pyperclip.py模块放在与 caesarCipher.py 文件相同的目录(相同的文件夹)中、
caesarCipher.py将导人这个模块。pyperclip.py模块如下:

凯撒密码的pyperclip.py模块_༄༊ξ李的脏脏星࿐的博客-CSDN博客

1.首先引用pyperclip.py模块:

import pyperclip

2.定义变量message,message为要加密的字符串: 


# The string to be encrypted
message = 'ILOVEYOU.'

 3.将偏移设为3,即令key=3,设置为解密模式,并加入所有可加密的符号:

# The encryption key:
key = 3
mode = 'decrypt'

# Every possible symbol that can be encrypted:
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'

4. translated储存信息的解密形式,仅加密/解密在symbols和SYMBOLS里共有的字符(串)


# Stores the encrypted/decrypted form of the message:
translated = ''

for symbol in message:
    # Note: Only symbols in the `SYMBOLS` string can be encrypted/decrypted.
    if symbol in SYMBOLS:
        symbolIndex = SYMBOLS.find(symbol)

       

5.执行加密/解密并添加未加密/解密的字符:

 # Perform encryption/decryption:
        if mode == 'encrypt':
            translatedIndex = symbolIndex + key
        elif mode == 'decrypt':
            translatedIndex = symbolIndex - key

        # Handle wrap-around, if needed:
        if translatedIndex >= len(SYMBOLS):
            translatedIndex = translatedIndex - len(SYMBOLS)
        elif translatedIndex < 0:
            translatedIndex = translatedIndex + len(SYMBOLS)

        translated = translated + SYMBOLS[translatedIndex]

 6.输出translated字符串:



print(translated)
pyperclip.copy(translated)


 

本文标签: 凯撒语言Python