Skip to content

Instantly share code, notes, and snippets.

@satomacoto
Created December 23, 2013 11:51
Show Gist options
  • Save satomacoto/8095862 to your computer and use it in GitHub Desktop.
Save satomacoto/8095862 to your computer and use it in GitHub Desktop.
# cf. https://gist.github.com/crmccreary/5610068
import base64
from Crypto.Cipher import AES
from Crypto import Random
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1])]
class AESCipher:
def __init__(self, key):
"""
Requires hex encoded param as a key
"""
self.key = key
def encrypt(self, raw, iv):
"""
Returns hex encoded encrypted value!
"""
raw = pad(raw)
# iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return cipher.encrypt(raw)
def decrypt(self, enc, iv):
"""
Requires hex encoded param to decrypt
"""
enc = enc
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc))
if __name__ == "__main__":
key = "abcdefghijklmnopqrstuvwxyz012345"
plaintext = "helloword"
key = key[:32]
decryptor = AESCipher(key)
iv = "1234567890123456"
print len(Random.new().read(AES.block_size))
ciphertext = decryptor.encrypt(plaintext, iv)
plaintext = decryptor.decrypt(ciphertext, iv)
print "%s" % plaintext
# -*- coding: utf-8 -*-
import zlib
import umsgpack
from flask import Flask, make_response, request
from AESCipher import AESCipher
app = Flask(__name__)
@app.route('/l')
def l():
"""
list
>>> import umsgpack
>>> import requests
>>> umsgpack.unpackb(requests.get('http://0.0.0.0:5000/l').content)
[1, 2, 3]
"""
return umsgpack.packb([1, 2, 3])
@app.route('/d')
def d():
"""
dictionary
>>> import umsgpack
>>> import requests
>>> msgpack.unpackb(requests.get('http://0.0.0.0:5000/d').content)
{'foo': 'bar'}
"""
return umsgpack.packb({"foo": "bar"})
@app.route('/z')
def z():
"""
compress
"""
res = make_response(zlib.compress(umsgpack.packb(range(10))))
res.headers['Content-Type'] = 'application/zlib'
return res
@app.route('/e')
def e():
"""
encrypt
"""
key = "abcdefghijklmnopqrstuvwxyz012345"
decryptor = AESCipher(key)
iv = request.args.get('iv')
cipher = decryptor.encrypt(umsgpack.packb(range(10)), iv)
return cipher
@app.route('/ez')
def ez():
"""
encrypt and compress
"""
key = "abcdefghijklmnopqrstuvwxyz012345"
decryptor = AESCipher(key)
iv = request.args.get('iv')
cipher = decryptor.encrypt(umsgpack.packb(range(10)), iv)
return zlib.compress(cipher)
@app.route('/ze')
def ze():
"""
compress and encrypt
"""
key = "abcdefghijklmnopqrstuvwxyz012345"
iv = request.args.get('iv')
decryptor = AESCipher(key)
cipher = decryptor.encrypt(zlib.compress(umsgpack.packb(range(10))), iv)
return cipher
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment