python实现凯撒密码

这是我首次用python语言写东西,里边代码肯定不能算非常高效,如有疑问,欢迎在博客留言

我觉得应该先对凯撒密码的原理有一定的了解,再看代码才最有效

凯撒的百度百科:https://baike.baidu.com/item/%E6%81%BA%E6%92%92%E5%AF%86%E7%A0%81/4905284?fromtitle=%E5%87%AF%E6%92%92%E5%AF%86%E7%A0%81&fromid=1336345&fr=aladdin

凯撒加密的维基百科https://en.wikipedia.org/wiki/Kaiser

说一说思路和方法

凯撒其实简单的来讲就是移位操作或者替换操作,有规律的将一些字符换成另一些字符;

本文主要实现了根据key来加密、根据key来解密、根据一些常用的单词来解密

要说的主要有两点

1、有的代码是直接对字符的ASCII进行加或减的操作,最后转换为字符型;而我就比较不喜欢走寻常路,我直接就建了一个txt文本表,里边一行对应一个key,26个字母,26行。如果用到那个key就取那一行,直接来替换,不做加操作,直接做赋值操作。

2、根据key来解密就不多说了,根据常用词解密怎么弄?首先要从网上找100(几个都可以,看心情)个常用词汇,做成一个list。你不知道key,只能用暴力来解决了,电脑是个傻瓜但计算能力又比我们强大,你让它做什么,它二话不说就给你做了,你让它帮你暴力破解,不到一秒就能把26种情况列出来;但他是个傻瓜,别忘了;它看不出来那个key最像真正的key,你要告诉它判断的规则,就好比现在的人工智能,你要给算法,它才能变得稍微有那么一点判断力;如何判断?循环26个key,每次记录此key破解后的明文中,能够与100个常用词汇的匹配程度,找出匹配程度最高的那个就行了

 

话不多说上代码

########################功能#######################
#1、文件读入100个常用单词、密文
#2、解密后存文件
########################程序###########################
import time
import re
#存放100常用单词的文本
WORDS_FILE_NAME = 'D:\\2018\Python_Learning\pythonlearning\words.txt'
#加密所用的对照表
KEY_FILE_NAME = 'D:\\2018\Python_Learning\pythonlearning\duizhao.txt'
#存放密文的文本
CIPHER_FILE_NAME = 'D:\\2018\Python_Learning\pythonlearning\cipher.txt'
#存放明文的文本
PLAIN_FILE_NAME = 'D:\\2018\Python_Learning\pythonlearning\plain.txt'

letters = 'abcdefghijklmnopqrstuvwxyz'
#读入一个文本
def read_file(filename):
    lines = ''
    with open(filename,'r') as fp:
        for line in fp:
            lines += line
    return lines

#写入字符串到文本
def write_file(str,filename):
    with open(filename,'w') as fp:
        fp.write(str)

#根据秘钥加密
def encrypt(key,textFileString):
    lines = ''
    #读入待加密文本
    lines = read_file(textFileString)
    lines.lower()
    #读入对应转换表
    letters1 = '' #选择对应的转换表
    with open(KEY_FILE_NAME, 'r') as fp1:
        for line in fp1:
            key -= 1
            if key == -1:
                letters1 += line
    #进行加密
    cstring = ''
    length = len(lines)
    for i in range(0, length):
        if lines[i] >= 'a' and lines[i] <= 'z':
            for j in range(0, 26):
                if lines[i] == letters[j]:
                    cstring += letters1[j]
        else:
            cstring += lines[i]
    return cstring
#根据秘钥解密
def decipher1(key,textFileString):
    #从文件读入数据
    lines = ''
    cstring = ''#密文结果
    lines = read_file(textFileString)
    #全部转换为小写字母
    lines.lower()
    #根据key进行解密
    letters1 = ''
    with open(KEY_FILE_NAME,'r') as fp1:
        for line in fp1:
            key += 1
            if key == 27:
                letters1+=line
    #开始解密
    length  = len(lines)
    for i in range(0,length):
        if lines[i]>='a' and lines[i] <= 'z':
            for j in range(0, 26):
                if lines[i] == letters[j]:
                    cstring+=letters1[j]
        else:
            cstring += lines[i]
    return cstring

#根据常用词汇表解密
def decipher2(textFileString):
    #读入一百个单词
    words = read_file(WORDS_FILE_NAME).split(' ')
    max = 0;
    index = 0;
    #暴力破解选择一个秘钥
    for i in range(1,26):
        pstring = decipher1(i,'D:\\2018\Python_Learning\pythonlearning\cipher.txt')
        plainWords = re.split(' |,|\?|\.|\"|:',pstring)
        #对比
        length = len(plainWords)
        temp = 0
        for j in range(0,length):
            if plainWords[j] in words:
                temp += 1
        if temp > max:
            max = temp
            index = i
    print('破解秘钥是%d'%index)
    # print('单词个数%d',length)
    print('单词的匹配程度{}%'.format(float('%.2f'%(max*100/length))))
    #写入文件
    str = decipher1(index,textFileString)
    write_file(str,PLAIN_FILE_NAME)
    return decipher1(index,textFileString)

def main():
    print('主程序入口')
    #print(decipher1(5,'D:\\2018\Python_Learning\pythonlearning\\test.txt'))
    start_time = time.time()
    print('解密后的结果:\n'+decipher2('D:\\2018\Python_Learning\pythonlearning\\cipher.txt'))  #解密
    #print('加密后的结果:\n'+encrypt(3, 'D:\\2018\Python_Learning\pythonlearning\\plain.txt')) #加密
    end_time = time.time()
    run_time = end_time-start_time
    print('程序的运行时间为:{}'.format(run_time))

if __name__ == '__main__':
    main()

100个词汇

the be of and a to in he have it that for they I with as not on she at by this we you do but from or which one would all will there say who make when can more if no man out other so what time up go about than into could state only new year some take come these know see use get like then first any work now may such give over think most even find day also after way many must look before great back through long where much should well people down own just

cipher.txt

rxwvlgh wkh eleoh, wkhvh vla zrugv duh wkh prvw idprxv lq doo wkh olwhudwxuh ri wkh zruog. wkhb zhuh vsrnhq eb kdpohw zkhq kh zdv wklqnlqj dorxg, dqg wkhb duh wkh prvw idprxv zrugv lq vkdnhvshduh ehfdxvh kdpohw zdv vshdnlqj qrw rqob iru klpvhoi exw dovr iru hyhub wklqnlqj pdq dqg zrpdq. 
wr eh ru qrw wr eh, wr olyh ru qrw wr olyh,wr olyh ulfkob dqg dexqgdqwob dqg hdjhuob, ru wr olyh gxoob dqg phdqob dqg vfdufhob. d sklorvrskhu rqfh zdq whg wr nqrz zkhwkhu kh zdv dolyh ru qrw, zklfk lv d jrrg txhvwlrq iru hyhubrqh wr sxw wr klpvhoi rffdvlrqdoob. kh dqvzhuhg lw eb vdblqj: "l wklqn, wkhuhiruh dp."

plain.txt

outside the bible, these six words are the most famous in all the literature of the world. they were spoken by hamlet when he was thinking aloud, and they are the most famous words in shakespeare because hamlet was speaking not only for himself but also for every thinking man and woman. 
to be or not to be, to live or not to live,to live richly and abundantly and eagerly, or to live dully and meanly and scarcely. a philosopher once wan ted to know whether he was alive or not, which is a good question for everyone to put to himself occasionally. he answered it by saying: "i think, therefore am."

我把凯撒加解密和栅栏加解密的相关代码、文本、100个单词上传到我的资源页了,主要这CSDN资源分享至少要设置1C币而不能免费分享,我也很无奈,所以我只能收大家1C币了

你可能感兴趣的:(Python)