凯撒加密原理
恺撒密码是一种替换加密方式技术。它的加密原理是明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。根据偏移量的不同,还存在若干特定的恺撒密码名称:
- 偏移量为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))
本人水平有限,文章难免存在疏漏和不足之处,欢迎广大读者朋友批评指正。