【Python】AESを実装しよう

pycryptodomeをインストールします
$ pip3 install pycryptodome

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util import Padding
from hashlib import pbkdf2_hmac

targetText = "hello world"

salt = get_random_bytes(16)
iv = get_random_bytes(16)

passPhrase = "password123"

key = pbkdf2_hmac('sha256', bytes(passPhrase, encoding='utf-8'), salt, 50000, int(128/8))

aes = AES.new(key, AES.MODE_CBC, iv)
data = Padding.pad(targetText.encode('utf-8'), AES.block_size, 'pkcs7')
encrypted = aes.encrypt(data)
print(encrypted)

$ python3 aes.py
b’\x86\xb4V\x7f\xfaN\x83\xc9\x87\x02\xd1\x15z\x19bU’