pycrypto
というモジュールはメンテナンスが止まっているので、pycryptodome
をつかう
pip install pycryptodome
暗号化、復号化の関数
from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto import Random def create_aes(password, iv): sha = SHA256.new() sha.update(password.encode()) key = sha.digest() return AES.new(key, AES.MODE_CFB, iv) def encrypt(decrypted_data, password): iv = Random.new().read(AES.block_size) return iv + create_aes(password, iv).encrypt(decrypted_data.encode()) def decrypt(encrypted_data, password): iv, cipher = encrypted_data[:AES.block_size], encrypted_data[AES.block_size:] return create_aes(password, iv).decrypt(cipher)
使い方
password = "alpha" s_strings = "secret sentence." enc = encrypt(s_strings, password) print(enc) dec = decrypt(enc, password) print(dec)
出力
b'\x99\n\x04\xd9u\xcf\x9c\x9aC\xf4\x91\xf2\x1b\x86P?\x81]X\x8dX\xc7\xe2m\xb5)\xd3\n\xd0\x94\xbd\x1b' b'secret sentence.'
あまり関係ないが、バイト列だと読みづらいので、base64化するコードも書いておく
import base64 enc_base64 = base64.b64encode(enc).decode('utf-8') print("base64:",enc_base64) print("元 :",base64.b64decode(enc_base64))
参照
Advanced Encryption Standard - Wikipedia