Use PyCrypto for AES format encryption
$ 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:])]
After that, create a key for authentication.
$ python -c "import string, random; print(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)]))"
>>> PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP
usage
cipher = AESCipher("PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP")
#encryption
password = cipher.encrypt("hogefuga")
print(password) # -> H/LfZg82FOdHhnructCHzfYnVgCOvjgEUGXXDFpjiYLBHw4Zflk/m2N9zEVwz6eC
#Decryption
print(cipher.decrypt(password)) # -> hogefuga
I registered with PyPI because it is a little stocked and there seems to be demand.
$ pip install Simple-AES-Cipher
See Github for more information.
Advanced Encryption Standard Encrypt with PyCrypto
Recommended Posts