凱撒密碼做爲一種最爲古老的對稱加密體制,在古羅馬的時候都已經很流行,他的基本思想是:經過把字母移動必定的位數來實現加密和解密。明文中的全部字母都在字母表上向後(或向前)按照一個固定數目進行偏移後被替換成密文。例如,當偏移量是3的時候,全部的字母A將被替換成D,B變成E,以此類推X將變成A,Y變成B,Z變成C。因而可知,位數就是凱撒密碼加密和解密的密鑰。python
#coding:utf-8 upperDict=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lowerDict=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def cesarWithLetter(ciphertext,offset): ''' 凱撒密碼 : 只轉換字母(包括大寫小寫) 參數 : ciphertext : 明文 offset : 偏移量 ''' result = "" for ch in ciphertext: if ch.isupper(): result=result+upperDict[((upperDict.index(ch)+offset)%26)] elif ch.islower(): result=result+lowerDict[((lowerDict.index(ch)+offset)%26)] elif ch.isdigit(): result=result+ch else: result=result+ch return result def printAllResult(ciphertext): ''' 打印全部偏移結果 ''' for i in range(len(upperDict)): print cesarWithLetter(ciphertext,i) ciphertext=raw_input("Please input the words :") printAllResult(ciphertext)
#-*-coding:utf-8-*- __author__ = 007 __date__ = 2016 / 02 / 04 #==================================================================# # 凱撒密碼(caesar)是最先的代換密碼,對稱密碼的一種 # # 算法:將每一個字母用字母表中它以後的第k個字母(稱做位移值)替代 # #==================================================================# def encryption(): str_raw = raw_input("請輸入明文:") k = input("請輸入位移值:") str_change = str_raw.lower() str_list = list(str_change) str_list_encry = str_list i = 0 while i < len(str_list): if ord(str_list[i]) < 123-k: str_list_encry[i] = chr(ord(str_list[i]) + k) else: str_list_encry[i] = chr(ord(str_list[i]) + k - 26) i = i+1 print "加密結果爲:"+"".join(str_list_encry) def decryption(): str_raw = raw_input("請輸入密文:") k = input("請輸入位移值:") str_change = str_raw.lower() str_list = list(str_change) str_list_decry = str_list i = 0 while i < len(str_list): if ord(str_list[i]) >= 97+k: str_list_decry[i] = chr(ord(str_list[i]) - k) else: str_list_decry[i] = chr(ord(str_list[i]) + 26 - k) i = i+1 print "解密結果爲:"+"".join(str_list_decry) while True: print u"1. 加密" print u"2. 解密" choice = raw_input("請選擇:") if choice == "1": encryption() elif choice == "2": decryption() else: print u"您的輸入有誤!" #if __name__ == "__main__": # main