密码学:凯撒密码(移位密码)原理、加密与解密(Python代码示例)

发布时间 2023-06-23 10:47:13作者: 没事摸摸小肚子

原理

凯撒密码(移位密码):是一种替换加密,明文中的所有字母都在字母表上向后或向前按照一个固定数目进行偏移后被替换成密文。

例如,偏移量为3位的时候:A对应D,B对应E,C对应F等

当偏移量为13位的时候,凯撒密码又叫回转密码ROT13):明文加密得到密文,密文再加密就会得到明文(因为偏移量为13位,一共26个字母,加密两次就会回到明文了),在CTF中题目关键字眼会有回转、回旋、十三踢等字眼。

题目:阿哒,看我回旋十三踢!
密文:Nusynt
明文:AHflag

加密

def caesar_cipher(plaintext, shift):
    ciphertext = ""
    for char in plaintext:
        if char.isalpha():
            # 将字母转换为0-25之间的数字,a为0,b为1,依此类推
            char_num = ord(char.lower()) - ord('a')
            # 将数字加上偏移量,并对26取模
            shifted_num = (char_num + shift) % 26
            # 将数字转换回字母
            shifted_char = chr(shifted_num + ord('a'))
            # 如果原来的字母是大写,就将加密后的字母也变成大写
            if char.isupper():
                shifted_char = shifted_char.upper()
            ciphertext += shifted_char
        else:
            # 如果不是字母,就不进行加密
            ciphertext += char
    return ciphertext

# 获取用户输入的明文和偏移量
plaintext = input("请输入明文:")
shift = int(input("请输入偏移量:"))

# 调用函数进行加密
ciphertext = caesar_cipher(plaintext, shift)

# 输出加密后的密文
print("加密后的密文为:", ciphertext)

解密(枚举法)

def caesar_cipher_decrypt(ciphertext, max_shift):
    """
    用凯撒密码解密密文,展示所有可能的解密结果

    参数:
    ciphertext -- 密文字符串
    max_shift -- 最大位移量

    返回值:
    无返回值,直接打印所有解密结果
    """
    for shift in range(max_shift + 1):
        plaintext = ""
        for char in ciphertext:
            if char.isalpha():
                # 将字母转换为0-25之间的数字,a为0,b为1,依此类推
                char_num = ord(char.lower()) - ord('a')
                # 将数字加上偏移量,并对26取模
                shifted_num = (char_num - shift) % 26
                # 将数字转换回字母
                shifted_char = chr(shifted_num + ord('a'))
                # 如果原来的字母是大写,就将加密后的字母也变成大写
                if char.isupper():
                    shifted_char = shifted_char.upper()
                plaintext += shifted_char
            else:
                # 如果不是字母,就不进行解密
                plaintext += char
        # 打印解密结果
        print(f"Shift = {shift}: {plaintext}")

ciphertext = input("请输入密文:")
max_shift = 25
caesar_cipher_decrypt(ciphertext, max_shift)