\

Pythonでは、文字列のXOR暗号化を行うことが可能です。以下にその方法を示します。

まず、2つの文字列をXORした結果を16進数の文字列で返す関数を定義します。

def crypto_text_to_hex(src_text, key):
    if src_text and key:
        xor_code = key
        while len(src_text) > len(xor_code):
            xor_code += key
        return "".join([chr(ord(data) ^ ord(code)) for (data, code) in zip(src_text, xor_code)]).encode().hex()

次に、16進数の文字列とキーをXORして戻した文字列を返す関数を定義します。

def decrypto_hex_to_text(hex_text, key):
    if hex_text and key:
        try:
            crypt_data = bytes.fromhex(hex_text).decode()
        except ValueError:
            crypt_data = None
        if crypt_data:
            xor_code = key
            while len(crypt_data) > len(xor_code):
                xor_code += key
            return "".join([chr(ord(data) ^ ord(code)) for (data, code) in zip(crypt_data, xor_code)])

これらの関数を使って、文字列の暗号化と復号化を行うことができます。

key = "1234567890"
src_text = "crypto test string"
print("src:" + src_text)
hex_text = crypto_text_to_hex(src_text, key)
print("enc:" + hex_text)
decode_text = decrypto_hex_to_text(hex_text, key)
print("dec:" + decode_text)
if src_text == decode_text:
    print("decode OK.")

このコードは、src_textを暗号化し、その結果をhex_textに格納します。次に、hex_textを復号化し、その結果をdecode_textに格納します。最後に、元のテキスト(src_text)と復号化したテキスト(decode_text)が一致するかどうかを確認します。

以上がPythonで文字列のXOR暗号化を行う方法です。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です