# 凱撒密碼破解 # (BSD Licensed) message = 'GUVF VF ZL FRPERG ZRFFNTR.' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # 把每個可能的密鑰循環一遍 for key in range(len(LETTERS)): # key代表密鑰 # translated設為空字符串 # 每次循環后清空. translated = '' # # 密文里的每一個字符按順序解密 for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) # 在26個字母里搜索到密文字符的位置 num = num - key # 檢查是否小於0,如果小於0,就加上26 if num < 0: num = num + len(LETTERS) # 把解密之后的字符追加到translated字符串的末尾 translated = translated + LETTERS[num] else: # 密文里的symbol如果不在26個字母里,就不進行解密,直接追加到字符串末尾 translated = translated + symbol # 輸出解密采用的key和解密后的明文 print('Key #%s: %s' % (key, translated))
