Skip to content

Instantly share code, notes, and snippets.

@mguezuraga
Created January 6, 2017 16:02
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 mguezuraga/8c7d2871b635f97c674191481a8763d3 to your computer and use it in GitHub Desktop.
Save mguezuraga/8c7d2871b635f97c674191481a8763d3 to your computer and use it in GitHub Desktop.
import base64
import hashlib
from Crypto.Cipher import AES
BS = 16
key = '74cf0e9a3c2b904e9c445771cdccb3e6ce3e4da7'
def pad(s): return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
def unpad(s): return s[:-ord(s[len(s)-1:])]
class AESCipher:
def __init__(self, key):
self.key = hashlib.sha1(key.encode('utf-8')).hexdigest()[:32]
def encrypt(self, raw):
raw = pad(raw)
iv = 16 * '\x00'
_cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(_cipher.encrypt(raw))
def decrypt(self, enc):
_enc = base64.b64decode(enc)
iv = 16 * '\x00'
_cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(_cipher.decrypt(_enc))
token_txt = "serveradmin:bob:1234567"
cipher = AESCipher(key)
token64 = cipher.encrypt(token_txt)
print('Encrypted text (base64): %s' % (token64))
dec = cipher.decrypt(token64)
print('Decrypted text: %s' % (dec))
@mguezuraga
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment