Help us understand the problem. What is going on with this article?

Pythonで暗号化と復号化

More than 3 years have passed since last update.

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で暗号化する

teitei_tk
Software Engineer
https://teitei-tk.com/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした