【Python】シーザ暗号の実装例

Pythonでシーザー暗号を実装する方法についてソースコード付きでまとめました。

スポンサーリンク

シーザ暗号の実装例

シーザー暗号(Caesar Cipher)とは、世界初の暗号化手法で有名なシーザー(カエサル)が用いたものだそうです。
その方法は極めて単純な方法で、決められた数だけ文字をずらします。
例えば、「SAO」を1文字ずつずらせば「TBP」となります。
復号化(暗号した文章を元に戻す)は、逆向きに1文字ずつずらします。(元のSAOになります)

(シーザー暗号では、ずらす文字数が鍵(パスワード)となります)

今回は、これをPython3のchr・ord関数で実装してみます。

関連ページ
原理 【シーザー暗号】原理・アルゴリズム・例題
参考 【Python】chr・ord関数で「文字」「アスキーコード(ascii)」の相互変換
【ASCII】アスキーコードの一覧表
スポンサーリンク

サンプルコード

サンプルプログラムのソースコードです。

# シーザー暗号で暗号化
def encrypt(plaintext, key):
    ciphertext = ""

    for ch in list(plaintext):
        if 'A' <= ch <= 'Z':
            ciphertext += chr((ord(ch) - ord('A') - int(key)) % 26 + ord('A'))
        elif 'a' <= ch <= 'z':
            ciphertext += chr((ord(ch) - ord('a') - int(key)) % 26 + ord('a'))
        else:
            ciphertext += ch

    return ciphertext


# シーザー暗号で復号化
def decrypt(ciphertext, key):
    plaintext = ""

    for ch in list(ciphertext):
        if 'A' <= ch <= 'Z':
            plaintext += chr((ord(ch) - ord('A') + int(key)) % 26 + ord('A'))
        elif 'a' <= ch <= 'z':
            plaintext += chr((ord(ch) - ord('a') + int(key)) % 26 + ord('a'))
        else:
            plaintext += ch

    return plaintext


# 平文
plaintext = "Excalibur"

# 鍵
key = "1"

# 平文の表示
print("平文 : " + plaintext) # 平文 : Excalibur

# 暗号化
ciphertext = encrypt(plaintext, key)
print("暗号文 : " + ciphertext) # 暗号文 : Dwbzkhatq

# 暗号文を復号化
ciphertext = decrypt(ciphertext, key)
print("復号文 : " + ciphertext) # 復号文 : Excalibur

上記の例だとキーが「1」なので平文を1文字ずらしたものが暗号文となります。
(キーが「a」ならアスキーコードは97なので、97字分ずらす)

- 関連記事
1 【Python】データの暗号化・サンプル例
2 Python入門 基本文法
Python
スポンサーリンク

コメント