非プログラマーのショルダーハックへの簡易的な対処や、端末内に保管するファイルに含まれる特定文字列の難読化処理としてPyCryptodomeを使ってみよう。
補足するとオリジナルのPyCryptoは2013年10月を最後にアップデートされていないためPyCryptodomeを使用している。
開発環境:
Python 3.9.2
参考情報:
下記のように簡易な手順で文字列が暗号化されている。行頭に「b」が付与されているのは、バイト列リテラルだからだ。
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>> import os
>>>
plaintext = 'Foo\\#B\'AR\"Baz\\'
>>> encoded = plaintext.encode()
>>> key = get_random_bytes(16)
>>> cipher = AES.new(key, AES.MODE_EAX)
>>> encrypted, tag = cipher.encrypt_and_digest(encoded)
>>>
>>> encoded
b'Foo\\#B\'AR"Baz\\'
>>> key
b'\xea\xa3M\xd9\x90Hj\x82\xb9\xe7\xf8s\x19\xe88J'
>>> tag
b'\xec\x97\xc1\xa9\x1f\xf3]\x1a\xd9\xd0M3\x97\xa8\xdd\xee'
>>> cipher.nonce
b'\xf1\xde\x96\x1b\xca\x04\xe9\x08\xdaO.Wj(\x16\xed'
>>> encrypted
b'\xf10^[\xc9\xee8\x02\x82\xbd\x8e\xd5\xae\x1d'
暗号/復号のために関数を用意しても良いだろう。
def encrypt_text(plaintext, enc):
try:
encoded = plaintext.encode(enc)
except Exception as e:
print(e)
else:
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
encrypted, mtag = cipher.encrypt_and_digest(encoded)
return key, cipher.nonce, mtag, encrypted
def decrypt_text(key, nonce, mtag, encrypted, enc):
try:
cipher = AES.new(key, AES.MODE_EAX, nonce)
decrypted = cipher.decrypt_and_verify(encrypted, mtag)
except Exception as e:
print(e)
else:
plaintext = decrypted.decode(enc)
return plaintext
暗号化前の文字列と復号化後の文字列を比較してみよう。AESといえばECBやCBCのようにInitialization Vectorがなぜサンプルコードに無いのかと疑問を感じたかも知れないが、EAXのように初期化ベクトルの不要なモードもある。
>>> plaintext = 'Foo\\#B\'AR\"Baz\\'
>>> enc = 'utf-8'
>>> edata = encrypt_text(plaintext, enc)
>>> edata
(b'\xea\xa3M\xd9\x90Hj\x82\xb9\xe7\xf8s\x19\xe88J', b'\xf1\xde\x96\x1b\xca\x04\xe9\x08\xdaO.Wj(\x16\xed', b'\xec\x97\xc1\xa9\x1f\xf3]\x1a\xd9\xd0M3\x97\xa8\xdd\xee', b'\xf10^[\xc9\xee8\x02\x82\xbd\x8e\xd5\xae\x1d')
>>> plaintext2 = decrypt_text(*edata, enc)
>>> plaintext == plaintext2
True # 同じ値になる
>>> print(plaintext)
Foo\#B'AR"Baz\
>>> print(plaintext2)
Foo\#B'AR"Baz\ # 当たり前だが復号化しても同じ文字列
関連ファイル:
PyCryptodomeのバージョン:
Package Version
------------ ---------
pycryptodome 3.10.1
まとめ:
特に理由がなければ解析しやすいECBを選択するのは避けよう
復号化に必要な情報は忘れず保管しよう
システム的に重要な情報を含んだファイルは機密性を高くしよう