python 版本的 OneNET物联网平台——HTTP推送数据接收

OneNET物联网平台——HTTP推送数据接收

flask框架 写的python版本的 HTTP推送, 消息加密方式:安全模式

用的onenet平台的模拟数据,接受成功!!!

# coding:utf-8
__author__="redhatlxs"
"""
OneNET物联网平台——HTTP推送数据接收
"""
import json
import base64
import hashlib
from Crypto.Cipher import AES
from flask import Flask, request,jsonify

app = Flask(__name__)

def md5_base64(in_str):
    m = hashlib.md5()
    m.update(in_str.encode('utf-8'))
    s = m.hexdigest()
    b = bytearray.fromhex(s)
    sign = base64.b64encode(b).decode()
    return sign


# AES CBC 解密
def decrypt(text, key, iv):
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    plain_text = cryptos.decrypt(text)
    print(plain_text)#接受到的bytes格式的数据
    return bytes.decode(plain_text).rstrip('\x10') #返回模拟数据接受


@app.route('/receive', methods=['GET', 'POST'])
def tuisong():
    token = '123456' #onenet平台配置
    encodekey = "8dGCIJzrWBEKKq5VM9ZP8f6v2ckA78K9TLyBBUAhY18" #one平台配置的加密接受数据
    if request.method == 'GET':
        msg = request.args.get('msg')
        nonce = request.args.get('nonce')
        sign = request.args.get('signature')
        print(msg,nonce,sign)
        new_sign = md5_base64(token + nonce + msg)
        # print("签名", sign)
        # print(new_sign)
        if sign == new_sign:
            return msg
        return jsonify(code=999, errmsg='token fail ,没有返回原样msg')

    dict = request.get_json()
    # print(dict)
    body = dict['enc_msg']
    enc_msg = base64.b64decode(body.encode('utf-8'))
    encodeKey = encodekey + "="
    aes_key = base64.b64decode(encodeKey.encode("utf-8"))
    secure_key = aes_key[0:32]
    iv = aes_key[0:16]
    msg = decrypt(enc_msg, secure_key, iv)
    msg1 = re.search(r"{.*}",msg).group()
    message= json.loads(msg1)
    print("接收数据为", message)
    return "OK"

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

你可能感兴趣的:(python 版本的 OneNET物联网平台——HTTP推送数据接收)