[python] 密码学:代换密码的实现

来源:互联网 发布:苹果数据恢复 编辑:程序博客网 时间:2024/05/17 09:44

《密码学原理与实践》中古典密码的第二个内容就讲到了代换密码。

理论公式为:(截图来自原书)



随后书中给出了一个例题,如下(截图来自原书)



这种加密方法就是将某个字母唯一的与任意字母组成一一对应的关系:

例题中的表就是一个加密函数,例题的结尾给出了一个问题,让读者解密密文。

我的python代码如下:

import sys,getoptplainfile=''cipherfile=''plainstring=''cipherstring=''encryDict={'\n':'\n',' ':' ','a':'X','b':'N','c':'Y','d':'A','e':'H','f':'P','g':'O','h':'G','i':'Z','j':'Q','k':'W','l':'B','m':'T','n':'S','o':'F','p':'L','q':'R','r':'C','s':'V','t':'M','u':'U','v':'E','w':'K','x':'J','y':'D','z':'I'}def help():'HELP FUNCTION'print '''-h:help-i:plaintext filename-o:ciphertext filename--plain:plain-string--cipher:cipher-string'''def encrypt(plainstring):'ENCRYPT FUNCTION'#print "plainstring:",plainstringcipher_array=[0 for i in range (len(plainstring))] #init the array#print cipher_arrayflag = 0for i in range(len(plainstring)):flag = 0for key in encryDict:if plainstring[i] == key:cipher_array[i] = encryDict[key]flag = 1if flag == 0:cipher_array[i] = plainstring[i]cipherstring_local = ''.join(cipher_array)return cipherstring_localdef decrypt(cipherstring):'DECRYPT FUNCTION'#print "cipherstring:",cipherstringplain_array=[0 for i in range (len(cipherstring))] #init the array#print plain_arrayflag = 0for i in range(len(cipherstring)):flag = 0for key in encryDict:if cipherstring[i] == encryDict[key]:plain_array[i] = keyflag = 1if flag == 0:plain_array[i] = cipherstring[i]plainstring_local = ''.join(plain_array)return plainstring_localdef fileEncrypt(thefile):'ENCRYPT info in TXT'try:fobj_r = open(thefile,'r')all_the_text = fobj_r.read()fobj_r.close()fobj_w = open(thefile,'w')print >> fobj_w,encrypt(all_the_text)fobj_w.close()except IOError,e:print "ERROR INFO:",edef fileDecrypt(thefile):'DECRYPT info in TXT'try:fobj_r = open(thefile,'r')all_the_text = fobj_r.read()fobj_r.close()fobj_w = open(thefile,'w')print >> fobj_w,decrypt(all_the_text)fobj_w.close()except IOError,e:print "ERROR INFO:",edef main():'MAIN FUNCTION'opts,args=getopt.getopt(sys.argv[1:],"hc:d:",["plain=","cipher="])for op,value in opts:if op=="-h":help()for op,value in opts:if op=="-c":plainfile=valuefileEncrypt(plainfile)for op,value in opts:if op=="-d":cipherfile=valuefileDecrypt(cipherfile)for op,value in opts:if op=="--plain":plainstring=valuecipherstring=encrypt(plainstring)print "cipher:",cipherstringfor op,value in opts:if op=="--cipher":cipherstring=valueplainstring=decrypt(cipherstring)print "plain:",plainstringif __name__=="__main__":main()

运行如下:



可知原文的内容为thisciphertextcannotbedecrypted

完毕


0 0