Cryptography-with-python-hacking-monoalphabetic-cipher

提供:Dev Guides
移動先:案内検索

モノアルファベット暗号のハッキング

この章では、単一アルファベット暗号とPythonを使用したそのハッキングについて学習します。

単一アルファベット暗号

Monoalphabetic暗号は、メッセージ全体を暗号化するために固定置換を使用します。 JSONオブジェクトを含むPython辞書を使用したモノアルファベット暗号がここに示されています-

monoalpha_cipher = {
   'a': 'm',
   'b': 'n',
   'c': 'b',
   'd': 'v',
   'e': 'c',
   'f': 'x',
   'g': 'z',
   'h': 'a',
   'i': 's',
   'j': 'd',
   'k': 'f',
   'l': 'g',
   'm': 'h',
   'n': 'j',
   'o': 'k',
   'p': 'l',
   'q': 'p',
   'r': 'o',
   's': 'i',
   't': 'u',
   'u': 'y',
   'v': 't',
   'w': 'r',
   'x': 'e',
   'y': 'w',
   'z': 'q',
    ' ': ' ',
}

この辞書の助けを借りて、JSONオブジェクトの値として、関連付けられた文字で文字を暗号化できます。 次のプログラムは、暗号化と復号化のすべての機能を含むクラス表現として、アルファベット順のプログラムを作成します。

from string import letters, digits
from random import shuffle

def random_monoalpha_cipher(pool = None):
   if pool is None:
      pool = letters + digits
   original_pool = list(pool)
   shuffled_pool = list(pool)
   shuffle(shuffled_pool)
   return dict(zip(original_pool, shuffled_pool))

def inverse_monoalpha_cipher(monoalpha_cipher):
   inverse_monoalpha = {}
   for key, value in monoalpha_cipher.iteritems():
      inverse_monoalpha[value] = key
   return inverse_monoalpha

def encrypt_with_monoalpha(message, monoalpha_cipher):
   encrypted_message = []
   for letter in message:
      encrypted_message.append(monoalpha_cipher.get(letter, letter))
   return ''.join(encrypted_message)

def decrypt_with_monoalpha(encrypted_message, monoalpha_cipher):
   return encrypt_with_monoalpha(
      encrypted_message,
      inverse_monoalpha_cipher(monoalpha_cipher)
   )

このファイルは、後述するMonoalphabetic暗号の暗号化および復号化プロセスを実装するために後で呼び出されます-

import monoalphabeticCipher as mc

cipher = mc.random_monoalpha_cipher()
print(cipher)
encrypted = mc.encrypt_with_monoalpha('Hello all you hackers out there!', cipher)
decrypted = mc.decrypt_with_monoalpha('sXGGt SGG Nt0 HSrLXFC t0U UHXFX!', cipher)

print(encrypted)
print(decrypted)

出力

上記のコードを実装すると、次の出力を確認できます-

モノアルファベット

したがって、指定されたキーと値のペアを持つモノアルファベット暗号をハッキングして、暗号テキストを実際のプレーンテキストに分解できます。