python3实现凯撒加密

凯撒加密原理

恺撒密码是一种替换加密方式技术。它的加密原理是明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。根据偏移量的不同,还存在若干特定的恺撒密码名称:

  • 偏移量为10:Avocat(A→K)
  • 偏移量为13:ROT13
  • 偏移量为-5:Cassis (K6)
  • 偏移量为-6:Cassette (K7)

例如,当偏移量是左移3的时候(解密时的密钥就是3):
明文字母表:ABCDEFGHIJKLMNOPQRSTUVWXYZ ;
密文字母表:DEFGHIJKLMNOPQRSTUVWXYZABC。
这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系。

python3实现凯撒加密解密

# encoding: utf-8
# encoding: utf-8
"""
@description: 凯撒密码
@author: baola
@time: 2020-06-10 20:14
@file: CaesarCrypto.py
@version: python3.8.1
"""

def CaesarEncode(crypto_str, shift):
    """
    凯撒加密
    :param crypto_str: 要加密的明文
    :param shift: 偏移量
    :return: 返回加密后的密文
    """
    result = ""
    num =int(shift)
    for word in crypto_str:
        ch = ord(word)
        if (ord('a') <= ch <= ord('z')):
            ch += num
            if ch > ord('z'):
                ch -= 26

        if (ord('A') <= ch <= ord('Z')):
            ch += num
            if ch > ord('Z'):
                ch -= 26
        result += chr(ch)
    return result

def CaesarDecode(crypto_str, shift):
    """
    凯撒解密
    :param crypto_str: 要解密的密文
    :param shift: 偏移量
    :return: 返回解密后问明文
    """
    result = ""
    num = int(shift)
    for word in crypto_str:
        ch = ord(word)
        if (ord('a') <= ch <= ord('z')):
            ch -= num
            if ch < ord('a'):
                ch += 26

        if (ord('A') <= ch <= ord('Z')):
            ch -= num
            if ch < ord('A'):
                ch += 26
        result += chr(ch)
    return result

#解密:全部遍历
# for i in range(1,26):
#     print(i,":",CaesarDecode("oknqdbqmoq{kag_tmhq_xqmdzqp_omqemd_qzodkbfuaz}",i))

shift = 0 #偏移量
str = "" #文本
# #解密
# print(CaesarDecode(str,shift))
# #加密
# print(CaesarEncode(str,shift))

本人水平有限,文章难免存在疏漏和不足之处,欢迎广大读者朋友批评指正。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值