Python Encryption v2
Login

Python Encryption v2

Encryption Class

Create a new Encryption.py file and paste in the following Python code.

from Crypto.Cipher import AES
import json, base64, hashlib

pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)


class Encryption:
    def __init__(self, iv_key, secret_key):
        self.iv_key = iv_key
        self.secret_key = secret_key
        self.algorithm = AES.MODE_CBC

    def encrypt(self, payload):

        secret = hashlib.sha256(self.secret_key.encode()).hexdigest()[:32]
        iv = hashlib.sha256(self.iv_key.encode()).hexdigest()[:16]

        cipher = AES.new(secret.encode('utf-8'), self.algorithm, iv.encode('utf-8'))
        crypt = cipher.encrypt(pad(payload).encode())

        return base64.b64encode(base64.b64encode(crypt)).decode('utf-8')

Encryption Class Usage (Flask)

For this example, we went with the Flask micro-framework to give a realistic illustration. Also note that pycypto has been deprecated and hence we will be pycryptodome.

Use the commands below to setup this Python demo if you do not have a Flask app already. We will also be using Python 3 for this exercise. A more comprehensive guide can be found here.

Step 1: Create a virtual environment $ python3 -m venv venv

Step 2: Activate the virtual environment $ . venv/bin/activate

Step 3: Install the Flask micro-framework $ pip install Flask

Step 4: Install the pycryptodome library $ pip install pycryptodome

Create a file checkout-encryption.py in the project directory and paste in the following code. Open a terminal session in your project directory and run the application using the commands:

Step 1: Export the Flask app into your environment export FLASK_APP=checkout-encryption.py

Step 2: Export the port to use export FLASK_RUN_PORT=3000

Step 3: Run the flask app python -m flask run

from flask import Flask, request, jsonify, render_template
from templates.encryption import Encryption
import json

from flask_cors import CORS

app = Flask(__name__)

CORS(app, support_credentials=True)


@app.route('/checkout-encryption', methods=["POST"])
def checkout_encryption():
    access_key = "<YOUR_ACCESS_KEY>"
    iv_key = "<YOUR_IV_KEY>"
    secret_key = "<YOUR_SECRET_KEY>"

    encryption_params = Encryption(iv_key, secret_key)
    payload = json.dumps(request.get_json())
    json_data = request.get_json()

    encrypted_params = encryption_params.encrypt(payload)

    json_string = json.dumps({
        "params": encrypted_params,
        "accessKey": access_key,
        "countryCode": json_data["countryCode"]
    })

    response = app.response_class(
        response=json_string,
        status=200,
        mimetype='application/json'
    )
    return response


if __name__ == '__main__':
    app.run()