Ecryption/Decryption REST Service
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ecryption/Decryption REST Service
=================================
INSTALLATION
------------
python -m venv .venv
source .venv/bin/activate
pip install flask pycryptodome pytest
DEPLOY
------
FLASK_APP=aes.py flask run
USAGE
-----
curl -X POST http://localhost:5000/decrypt -d'encrypted=/gqxzcVtRUlw4nzSETa40dAIq4lOdonshBBjtQfY3ewicIKMwKIllXVZldsTPCGH'
"""
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
from flask import Flask
from flask import request
class AESCipher(object):
"""
AES Cipher tool for conveniently handling CBC mode.
Inspired by https://stackoverflow.com/a/21928790/2235622
"""
def __init__(self, key):
self.bs = 16
self.key = hashlib.sha256(key.encode()).digest()
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.encode('utf-8')))
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:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s) - 1:])]
def test_aes_roundtrip():
""" Test Harness """
cipher = AESCipher('thisisunsafe--changeit!')
to_encrypt = 'MeinSuperGeheimesPasswort1337!'
encrypted = cipher.encrypt(to_encrypt)
print(encrypted)
decrypted = cipher.decrypt(encrypted)
assert to_encrypt == decrypted
"""
Start Web Service
"""
app = Flask(__name__)
cipher = AESCipher('thisisunsafe--changeit!')
@app.route("/decrypt/<to_decrypt>")
def decrypt(to_decrypt):
return cipher.decrypt(to_decrypt)
@app.route("/decrypt", methods=['POST'])
def decrypt_post():
return cipher.decrypt(request.form['encrypted'])
@app.route("/encrypt/<to_encrypt>")
def encrypt(to_encrypt):
return cipher.encrypt(to_encrypt)