Skip to content

Instantly share code, notes, and snippets.

@teitei-tk
Last active October 18, 2016 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teitei-tk/75ddab6f254c5ab0397a to your computer and use it in GitHub Desktop.
Save teitei-tk/75ddab6f254c5ab0397a to your computer and use it in GitHub Desktop.
Pythonで暗号化と復号化 ref: http://qiita.com/teitei_tk/items/0b8bae99a8700452b718
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:])]
$ 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