Skip to content

Instantly share code, notes, and snippets.



Last active Oct 18, 2016
What would you like to do?
Pythonで暗号化と復号化 ref:
import base64
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key, block_size=32): = block_size
if len(key) >= len(str(block_size)):
self.key = key[:block_size]
self.key = self._pad(key)
def encrypt(self, raw):
raw = self._pad(raw)
iv =
cipher =, 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.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:]))
def _pad(self, s):
return s + ( - len(s) % * chr( - len(s) %
def _unpad(self, s):
return s[:-ord(s[len(s)-1:])]
$ pip install pycrypto
$ python -c "import string, random; print(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)]))"
>>> PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP
cipher = AESCipher("PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP")
# 暗号化
password = cipher.encrypt("hogefuga")
print(password) # -> H/LfZg82FOdHhnructCHzfYnVgCOvjgEUGXXDFpjiYLBHw4Zflk/m2N9zEVwz6eC
print(cipher.decrypt(password)) # -> hogefuga
$ pip install Simple-AES-Cipher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment