凯撒加密—加密算法
在密码学中,恺撒密码是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。
# 凯撒加密---加密算法的实现
import string
def kaisacrypt(text='hello', k=3):
# 对原有小写字母向右移动k位
lower = string.ascii_lowercase[k:] + string.ascii_lowercase[:k]
upper = string.ascii_uppercase[k:] + string.ascii_uppercase[:k]
# 用于创建字符串映射的转换表'hello'
table = str.maketrans(string.ascii_letters, lower+upper)
# 根据转换表去转换对应的字符
return text.translate(table)
在移动位默认为3的情况下
对应关系为:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
defghijklmnopqrstuvwxyzabcDEFGHIJKLMNOPQRSTUVWXYZABC
#检测
def check(text):
mostCommonWords = ('the', 'is', 'to', 'not', 'have', 'than', 'for', 'ok', 'and' )
return len([1 for word in mostCommonWords if word in text])>2
测试文本中是否存在至少两个最常见的英文单词, 如果有, 则代表破解成功
# 暴力破解
def bruteForce(text):
for i in range(26):
# 1,2,3,4,5
t = kaisacrypt(text, -i)
if check(t):
print(i)
print(t)
break
循环检测移动位k值,检测成功代表破解成功
text = "If not to the sun for smiling, warm is still in the sun there, but wewill laugh more confident calm; if turned to found his own shadow, appropriate escape, the sun will be through the heart,warm each place behind the corner; if an outstretched palm cannot fall butterfly, then clenched waving arms, given power; if I can't have bright smile, it will face to the sunshine, and sunshine smile together, in full bloom."
cryptStr = kaisacrypt(text=text, k=18)
print(cryptStr)
#####
Ax fgl lg lzw kmf xgj keadafy, osje ak kladd af lzw kmf lzwjw, tml owoadd dsmyz egjw ugfxavwfl usde; ax lmjfwv lg xgmfv zak gof kzsvgo, shhjghjaslw wkushw, lzw kmf oadd tw lzjgmyz lzw zwsjl,osje wsuz hdsuw twzafv lzw ugjfwj; ax sf gmlkljwluzwv hsde usffgl xsdd tmllwjxdq, lzwf udwfuzwv osnafy sjek, yanwf hgowj; ax A usf'l zsnw tjayzl keadw, al oadd xsuw lg lzw kmfkzafw, sfv kmfkzafw keadw lgywlzwj, af xmdd tdgge.
18
If not to the sun for smiling, warm is still in the sun there, but wewill laugh more confident calm; if turned to found his own shadow, appropriate escape, the sun will be through the heart,warm each place behind the corner; if an outstretched palm cannot fall butterfly, then clenched waving arms, given power; if I can't have bright smile, it will face to the sunshine, and sunshine smile together, in full bloom.