結城浩氏の「暗号技術入門 第3版 秘密の国のアリス」を読んでいく中で、折角なので自分でも勉強ついでにコーディングをしてみました。
今回はシーザー暗号とブルートフォースアタック(総当たり攻撃)について学んでいきます。
シーザー暗号とは
シーザー暗号とは、ローマの皇帝ジュリウス・シーザーが使用していたとされる暗号です。
シーザー暗号では、平文で使用されるアルファベットを決められた文字数だけずらしていくことで暗号化していきます。
例えば"hello"という平文を3文字ずらすと、"KHOOR"という暗号文を得ることができます。
h →K
e → H
l → O
l → O
o → R
ブルートフォースアタックとは
ブルートフォースアタックとは、総当たり攻撃と呼ばれるもので全てのパターンを順番に網羅していくことで、暗号を解読していきます。
上記のシーザー暗号では、アルファベットの数が26パターンしかなく容易に全パターンを網羅できるため、とても弱い暗号と言えます。
Pythonでシーザー暗号を実装
では、Pythonでシーザー暗号を実装していきます。
前提として、平文はアルファベットのみを使用としています。
import string alp_list = list(string.ascii_uppercase) def enc_caesar(text, shift): enc_text = "" text = text.upper() for t in text: ind = alp_list.index(t) + shift if ind > len(alp_list): ind = ind % len(alp_list) enc_text += alp_list[ind] return enc_text
# 平文 text = 'hello' enc_text = enc_caesar(text, 3) print(enc_text) # 実行結果 # KHOOR
Pythonでブルートフォースアタックを実装
それでは上記の暗号文をブルートフォースアタックで解読してみます。
import string
alp_list = list(string.ascii_uppercase)
def enc_caesar(text, shift):
enc_text = ""
text = text.upper()
for t in text:
ind = alp_list.index(t) + shift
if ind > len(alp_list):
ind = ind % len(alp_list)
enc_text += alp_list[ind]
return enc_text
def dec_caesar(enc_text, shift):
dec_text = ""
enc_text = enc_text.upper()
for t in enc_text:
ind = alp_list.index(t) - shift
if ind > len(alp_list):
ind = ind % len(alp_list)
dec_text += alp_list[ind]
return dec_text.lower()
def brute_force_caesar(enc_text):
for shift in range(len(alp_list)):
print(dec_caesar(enc_text, shift))
# 暗号文
enc_text = "KHOOR"
brute_force_caesar(enc_text)
# 実行結果
# khoor
# jgnnq
# ifmmp
# hello
# gdkkn
# fcjjm
# ebiil
# dahhk
# czggj
# byffi
# axeeh
# zwddg
# yvccf
# xubbe
# wtaad
# vszzc
# uryyb
# tqxxa
# spwwz
# rovvy
# qnuux
# pmttw
# olssv
# nkrru
# mjqqt
# lipps
上記からhelloという文字が推測されます。