Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

DJango で AES 暗号を行う

More than 1 year has passed since last update.

ライブラリインストール

$ 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)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away