LoginSignup
3
5

Pythonでエニグマシミュレータを作成

Last updated at Posted at 2022-11-18

はじめに

Qiita 初投稿です。

映画「イミテーション・ゲーム/エニグマと天才数学者の秘密」で、エニグマが登場し興味があったので、Pythonで実行しました。

githubにてライブラリを公開しました。

目次

エニグマの仕組みについて

参考記事

使用方法

pipにてライブラリをインポート

pip install git+https://github.com/kazumamatsu/enigma_sim.git
import enigma

3つのローターの初期値と乱数の設定

config = list("AAA")
seed = 100

暗号化

インスタンスオブジェクトを作成し、

E = enigma.enigma(config[0], config[1], config[2], seed = 100)
text = list(str.upper(input()))
code = []
for t in text:
  code.append(E.typing(t))
print(text)
print(code)

「JAPAN」を暗号化すると、

>>> JAPAN
>>> ['J', 'A', 'P', 'A', 'N']
>>> ['W', 'U', 'Z', 'H', 'W']

「WUZHW」になります。

復号化

再度、同様の設定でインスタンスオブジェクトを作成し、
「WUZHW」を入力すると、

E = enigma.enigma(config[0], config[1], config[2], seed = 100)
decode = []
for t in code:
  decode.append(E.typing(t))
print(decode)
>>> ['J', 'A', 'P', 'A', 'N']

「JAPAN」に戻ります。

補足

途中結果を表示したい場合、.dec_print(ptype)を実行します。

E = enigma.enigma(config[0], config[1], config[2], seed = 100)
text = list(str.upper(input()))
code = []
for t in text:
  code.append(E.typing(t))
  E.dec_print(ptype = 0) #<-- ココ
print(text)
print(code)

出力は、

>>> JAPAN
>>> J -> Y -> H -> Q -> K -> G -> Z -> L -> W
>>> A -> B -> P -> K -> D -> R -> J -> O -> U
>>> P -> E -> N -> Z -> A -> M -> E -> B -> Z
>>> A -> H -> M -> H -> F -> A -> O -> I -> H
>>> N -> E -> P -> K -> D -> R -> J -> R -> W
>>> ['J', 'A', 'P', 'A', 'N']
>>> ['W', 'U', 'Z', 'H', 'W']

となります。

.dec_print(ptype = 1) の場合、
出力は、

>>> JAPAN
>>> J -> W
>>> A -> U
>>> P -> Z
>>> A -> H
>>> N -> W
>>> ['J', 'A', 'P', 'A', 'N']
>>> ['W', 'U', 'Z', 'H', 'W']

となり、各ローターでの途中結果が省略されます。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5