暗号化モジュールPyCryptodomeを使った暗号化である。
ドキュメント
Crypto.Cipher
AES暗号化を行なう。
インストール
pip install pycryptodome
インポート
from Crypto.Cipher import AES
暗号化
平文ファイル全体を読み込んで、一括で暗号化して、nonce, tagと一緒に暗号化ファイルに書き出す。
# Read Input File
with open(filename, 'rb') as file1:
input_data = file1.read() # Read Original File as Binary
# Encryption
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(input_data)
# Write New File from Encrypted Data
with open(filename+suffix, 'wb') as file2:
# nonce and tar are 16 bytes
[ file2.write(data) for data in (cipher.nonce, tag, ciphertext) ]
- ファイルに書き出すところはリスト内包表記を使った。
- nonce, tag, encrypted_dataの順番を読み出す時に間違わないようにすること。
復号化
暗号化ファイル全体を読み込んで、nonce, tag, 暗号化データを抜き出して一括で復号化して、平文ファイルに書き出す。
with open(filename, 'rb') as file1:
input_data = file1.read() # Read Original File as Binary
# nonce and tar are 16 bytes.
nonce = input_data[0:16]
tag = input_data[16:32]
ciphertext = input_data[32:]
cipher = AES.new(key, AES.MODE_EAX, nonce)
output_data = cipher.decrypt_and_verify(ciphertext, tag)
with open(filename.replace(suffix,''), 'wb') as file2:
file2.write(output_data)
- 上記暗号化で作成した暗号化ファイルを読み込んでいる。
- nonce, tag, encrypted_dataの順番を書き込んだときと一致させること。
Crypto.Random
ランダムなバイト型を生成する。
インポート
from Crypto.Random import get_random_bytes
乱数生成(バイト型)
key = get_random_bytes(16)