Flask Server Crypt Data Test on Raspberry Pi

Environment

  • Raspberry Pi 3B+
  • Stratux AHRS Sensor (MPU9250 + BMP280)
  • Raspbian GNU/Linux 9.4
  • Python 3
  • Flask 1.0.2
  • pycrypto 2.6.1

Crypt Flask Code

mpu_flask_crypt.py

#!/usr/bin/python3
# coding: utf-8

from flask import Flask
import FaBo9Axis_MPU9250
import json
from Crypto.Cipher import AES


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

mpu9250 = FaBo9Axis_MPU9250.MPU9250()

app = Flask(__name__)


@app.route('/')
def hello():
    name = "Top Page"
    return name


@app.route('/api/mpu', methods=['GET'])
def mpu():
    temp = mpu9250.readTemperature()
    accel = mpu9250.readAccel()
    gyro = mpu9250.readGyro()
    mag = mpu9250.readMagnet()
    dic = {"temp": str(temp),
           "accel": {"x": str(accel['x']),
                     "y": str(accel['y']),
                     "z": str(accel['z'])},
           "gyro": {"x": str(gyro['x']),
                    "y": str(gyro['y']),
                    "z": str(gyro['z'])},
           "mag": {"x": str(mag['x']),
                   "y": str(mag['y']),
                   "z": str(mag['z'])}}
    json_str = json.dumps(dic)

    # crypt
    key = 'this is a key123'
    cipher = AES.new(key)
    data = cipher.encrypt(_pad(json_str))
    print(data, type(data))

    return data


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5005)

Decrypt Code

mpu_flask_crypt_decode.py

#!/usr/bin/python3
# coding: utf-8

from Crypto.Cipher import AES
import urllib.request
import json

# get data
response = urllib.request.urlopen('http://x.x.x.x:x/api/mpu')
data = response.read()
# print(data, type(data))

# decrypt
key = 'this is a key123'
cipher = AES.new(key)
data = cipher.decrypt(data)
# print(data, type(data))

# byte > str
data = data.decode('utf-8')
# print(data, type(data))

# delete space, tab and new line
data = data.strip()
# print(data, type(data))

# json str > python dict
data = json.loads(data)
print(data, type(data))

print('accel_x', data['accel']['x'])
print('accel_y', data['accel']['y'])
print('accel_z', data['accel']['z'])

Result

$ python mpu_flask_crypt.py 
 * Serving Flask app "mpu_flask_crypt" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 117-428-274
b'\xf4\xcfCA\xb0~\x0e\x0e;\x088\x80P\x93\x1d\xb0\xa2\xa4\xa6\x8e`p\xb9B9\xd7\x94R\x0e3\xaa\xcbcZ\x8c\xed\xfbW\xea\xac\xaf\xa0\xb5\xc7v\x9fM0>\xa4Z\xcdH\x129\x9a\x83\xd6=]5\xf0\x98S\xa6HI\x9d\t\x1b-+Z\x14Ioi' 
$ python mpu_flask_crypt_decode.py 
{'temp': '39.531', 'mag': {'y': '-35.899', 'x': '13.486', 'z': '-46.636'}, 'gyro': {'y': '1.953', 'x': '-1.472', 'z': '-0.381'}, 'accel': {'y': '0.04', 'x': '1.006', 'z': '-0.06'}} 
accel_x 1.006
accel_y 0.04
accel_z -0.06

Reference