0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで暗号解読ツールを作ってみた!〜AIを活用した判定〜

Posted at

はじめに

この記事では、Pythonを使って暗号解読ツールを作成したプロジェクトについて解説します。このツールは、暗号文を解読するだけでなく、AI(GPT)を活用して復号結果が意味のある日本語かどうかを判定します。

ソース

プロジェクトの概要

このプロジェクトでは、以下の暗号方式に対応しています:

  1. Caesar暗号(シフト暗号)
  2. XOR暗号(固定キーを使用)
  3. 転置暗号
  4. 書籍暗号(指定された書籍テキストを使用)

また、復号結果が意味のある日本語かどうかを判定するために、GPTを活用しています。

処理の流れ

暗号解読ツールの処理の流れを以下に示します。

  1. コマンドライン引数の解析
    • ユーザーが指定した暗号文や暗号方式、オプションを取得します。
  2. 暗号方式の選択
    • 指定された暗号方式に応じて、対応するクラスを初期化します。
  3. 暗号化または復号化の実行
    • 暗号文を解読し、結果を取得します。
  4. AIによる判定
    • 復号結果が意味のある日本語かどうかをGPTを使って判定します。
  5. 結果の出力
    • 復号結果をコンソールに表示します。

コード解説

以下に、主要なコードを抜粋して解説します。

コマンドライン引数の解析

コマンドライン引数を解析する部分です。暗号方式やモード(暗号化/復号化)を指定できます。

# filepath: cipher_tool.py
from argparse import ArgumentParser
from pathlib import Path

def parse_args():
    parser = ArgumentParser(description="暗号化・復号化ツール")
    parser.add_argument("--mode", choices=["encrypt", "decrypt"], required=True, help="暗号化か復号化かを指定")
    parser.add_argument("--cipher", choices=["caesar", "xor", "transposition", "book"], required=True, help="暗号方式を指定")
    parser.add_argument("--text", type=str, required=True, help="処理対象の文字列")
    parser.add_argument("--key", type=str, required=False, help="暗号で使う鍵(必要に応じて)")
    parser.add_argument("--book_path", type=Path, help="書籍暗号で使用するテキストファイル")
    return parser.parse_args()

暗号方式の選択と処理

ユーザーが指定した暗号方式に応じて、対応するクラスを初期化し、暗号化または復号化を実行します。

# filepath: cipher_tool.py
def main():
    match args.cipher:
        case "caesar":
            cipher = CaesarCipher(int(args.key))
        case "xor":
            cipher = KeyCipher(args.key)
        case "transposition":
            cipher = TranspositionCipher(int(args.key))
        case "book":
            book_lines = text.read_text_file(args.book_path)
            cipher = BookCipher(book_lines)

    result = cipher.encrypt(args.text) if args.mode == "encrypt" else cipher.decrypt(args.text)
    print(f"🔐 結果: {result}")

AIを活用した判定

復号結果が意味のある日本語かどうかをGPTを使って判定します。

# filepath: cipher_inspector.py
def is_meaningful_by_gpt(decrypt_text):
    prompt = "以下の文は自然で意味が通じる日本語ですか?端的に「はい」か「いいえ」で答えてください。\n"
    prompt += decrypt_text
    res = gemini_api.query(prompt)
    return res.startswith("はい") if res else False

実行例

以下は、書籍暗号を使用して復号化を行う例です。

python cipher_tool.py --mode decrypt --cipher book --text "暗号文" --book_path "material/books/kokoro.txt"

結果:

🔐 結果: 復号されたテキスト

まとめ

このプロジェクトでは、Pythonを使って暗号解読ツールを作成し、AIを活用して復号結果を判定する仕組みを実装しました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?