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

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
132
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

Pythonで暗号化と復号化

PyCryptoを使って、AES形式の暗号化を行う

$ pip install pycrypto
aes_cipher.py
import base64
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):
    def __init__(self, key, block_size=32):
        self.bs = block_size
        if len(key) >= len(str(block_size)):
            self.key = key[:block_size]
        else:
            self.key = self._pad(key)

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:]))

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def _unpad(self, s):
        return s[:-ord(s[len(s)-1:])]

後は、認証用の鍵を作成する。

$ python -c "import string, random; print(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)]))"

>>> PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP

usage

cipher = AESCipher("PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP")

# 暗号化
password = cipher.encrypt("hogefuga")
print(password) # -> H/LfZg82FOdHhnructCHzfYnVgCOvjgEUGXXDFpjiYLBHw4Zflk/m2N9zEVwz6eC

#復号化
print(cipher.decrypt(password)) # -> hogefuga

追記

ちょいちょいストックされていて需要がありそうなので、PyPIに登録しました。

$ pip install Simple-AES-Cipher

詳しくはGithubをご覧ください。

参考

Advanced Encryption Standard
PyCryptoで暗号化する

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
132
Help us understand the problem. What are the problem?