凱撒密碼暴力破解的算法實現(python)
#凱撒密碼破解
message='guv6Jv6Jz!J6rp5r7Jzr66ntrM'
SYMBOLS='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
#循環遍歷所有可能的KEY
for key in range(len(SYMBOLS)):
#將translateed設置為空字符串很重要
#translated的值
translated=''
#其余部分和凱撒相同
#循環遍歷message中的每一個字符
for symbol in message:
# 注意:只能加解密SYMBOLS字符串中的符號
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
# 執行解密
translatedIndex = symbolIndex - key
# 如果需要,執行回環
if translatedIndex<0:
translatedIndex = translatedIndex + len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
else:
# 添加未加解密的字符
translated = translated + symbol
#顯示每一個可能的解密值
print('Key #%s:%s'%(key,translated))#凱撒密碼
#要加解密的字符串
message='This is my secret message.'
#加解密密鑰
key=13
#程序是加密還是解密
mode='encrypt' #設置為encrypt或decrypt
#可能被加解密的符號
SYMBOLS='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
#存儲消息的加解密形式
translated=''
for symbol in message:
#注意:只能加解密SYMBOLS字符串中的符號
if symbol in SYMBOLS:
symbolIndex=SYMBOLS.find(symbol)
#執行加解密
if mode =='encrypt':
translatedIndex=symbolIndex+key
if mode =='decrypt':
translatedIndex=symbolIndex-key
#如果需要,執行回環
if translatedIndex>=len(SYMBOLS):
translatedIndex=translatedIndex-len(SYMBOLS)
elif translatedIndex <= 0:
translatedIndex=translatedIndex+len(SYMBOLS)
translated=translated+SYMBOLS[translatedIndex]
else:
#添加未加解密的字符
translated=translated+symbol
#輸出translated字符串
print(translated)