LoginSignup
5

More than 3 years have passed since last update.

DJango で AES 暗号を行う

Last updated at Posted at 2019-11-06

ライブラリインストール

$ pip install pycryptodome
$ pip install pycryptodomex

settings.py に キーを記載

$ vim settings.py
# AES 暗号
try:
   from .aes_key import *
except ImportError:
   AES_KEY='oDZC5a6rhyukFmKCbPS6M45TFROLmrlB'
$ vim aes_key.py
AES_KEY='dMchLlLllvrDtQUxXDLpAWr2v1EdjuLU'

確認

$ python manage.py shell
from project.settings import *
print(AES_KEY)

cipherクラスの作成

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Padding


class AESCipher(object):
   def __init__(self, key):
       self.key = (hashlib.md5(key.encode('utf-8')).hexdigest()).encode('utf-8')

   def encrypt(self, raw):
       iv = Random.get_random_bytes(AES.block_size)
       cipher = AES.new(self.key, AES.MODE_CBC, iv)
       data = Padding.pad(raw.encode('utf-8'), AES.block_size, 'pkcs7')
       return base64.b64encode(iv + cipher.encrypt(data)).decode('utf-8')

   def decrypt(self, enc):
       enc = base64.b64decode(enc.encode('utf-8'))
       iv = enc[:AES.block_size]
       cipher = AES.new(self.key, AES.MODE_CBC, iv)
       data = Padding.unpad(cipher.decrypt(enc[AES.block_size:]), AES.block_size, 'pkcs7')
       return data.decode('utf-8')

呼出し

import random
import string
from project.lib.cipher import AESCipher

raw_text = 'こんにちは'

key = 'y6lLepZQpppdzjkeG5MhUaaaRCychpDd'
print('key:' + key)

cipher = AESCipher(key)

encrypted_text = cipher.encrypt(raw_text)
print(encrypted_text)

decrypted_text = cipher.decrypt(encrypted_text)
print(decrypted_text)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5