PythonでAES暗号を取り扱わなければならなくなったので備忘録代わりにメモ。
まずはPyCryptoをインストール。
$ pip install PyCrypto
それではAESの暗号化、復号化してみるよ。
こんなコード書いてみた。
CBCモードで初期ベクトルは乱数を使ってる。
import os
import hashlib
from Crypto.Cipher import AES
# key and initial vector
secret_key = hashlib.sha256('This is secret passphrase.').digest()
iv = os.urandom(16)
# plain text
plain_text = 'A' * 16
# encrypt
aes = AES.new(secret_key, AES.MODE_CBC, iv)
encrypt_data = aes.encrypt(plain_text)
# decrypt
aes = AES.new(secret_key, AES.MODE_CBC, iv)
decrypt_data = aes.decrypt(encrypt_data)
# output result
print 'plain text: %s' % (plain_text)
print 'initial vector: %s' % (iv.encode('hex'))
print 'encrypt: %s' % (encrypt_data.encode('hex'))
print 'decrypt: %s' % (decrypt_data)
そいでは実行してみましょう。
$ python test001.py plain text: AAAAAAAAAAAAAAAA initial vector: 1e37825a3af0345564c9694c4e0a65e7 encrypt: b631aa2387fc7870b38e2008b44e5c0e decrypt: AAAAAAAAAAAAAAAA $ python test001.py plain text: AAAAAAAAAAAAAAAA initial vector: c881768a26d219bde12e708e588d5e3b encrypt: d3fb0ac082c734c0b66e58c501c40e74 decrypt: AAAAAAAAAAAAAAAA $ python test001.py plain text: AAAAAAAAAAAAAAAA initial vector: eedff20172c9712f1493ca0d1b482b33 encrypt: 353823f2a4d25e7f3050e0d99e079538 decrypt: AAAAAAAAAAAAAAAA
うん、ちゃんと動いてるみたい。