物联网onenet的token算法

1.Token的组成

version:2018-10-31

res:products/123123/devices/78329710

设备级格式为:products/{产品id}/devices/{设备名字}

et:是时间戳

method:支持md5、sha1、sha256

sign:经过复杂运算

2.sign运算

1、对设备密钥进行base64解码,结果是个密钥;

2、进行 StringForSignature字符串的建立,结果作为明文;

3、用第一个步的密钥对第二部的明文,进行签名的加密运算;

4、对第三步的结果进行base64的编码,结果就是sign;

3.进行URL编码

对res和sign进行URL编码;

最终得到token;

4.整体一句话总结

这是一段 生成 OneNet 设备接入 Token 的完整代码 流程 = 拼接参数 → 解码密钥 → HMAC 签名 → Base64 编码 → URL 编码 → 最终 Token

复制代码
#ifndef __ONENET_TOKEN_H__
#define __ONENET_TOKEN_H__

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

// 签名算法枚举
typedef enum {
    SIG_METHOD_MD5,
    SIG_METHOD_SHA1,
    SIG_METHOD_SHA256
} sig_method_e;

// 对外接口:生成 OneNet Token
int32_t dev_token_generate(char* token,
                          sig_method_e method,
                          uint32_t exp_time,
                          const char* product_id,
                          const char* dev_name,
                          const char* access_key);

#ifdef __cplusplus
}
#endif

#endif

.c

复制代码
#include "onenet_token.h"
#include <stdio.h>
#include <string.h>
#include "mbedtls/md.h"


// 类型别名
typedef uint8_t  byte;
typedef uint32_t word32;

enum Escaped {
    WC_STD_ENC = 0,
    WC_ESC_NL_ENC,
    WC_NO_NL_ENC
};

#define BAD_FUNC_ARG    -1
#define ASN_INPUT_E     -2
#define BUFFER_E        -3
#define LENGTH_ONLY_E   -4



#ifndef osl_sprintf
    #define osl_sprintf     sprintf
    #define osl_sprintf_ex  sprintf // 如果有_ex版本
    #define osl_strlen      strlen
    #define osl_strcat      strcat
    #define osl_memset      memset
    #define osl_memcpy      memcpy
#endif


enum {
    BAD         = 0xFF,  /* invalid encoding */
    PAD         = '=',
    PEM_LINE_SZ = 64
};


static
const byte base64Decode[] = { 62, BAD, BAD, BAD, 63,   /* + starts at 0x2B */
                              52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
                              BAD, BAD, BAD, BAD, BAD, BAD, BAD,
                              0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
                              10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
                              20, 21, 22, 23, 24, 25,
                              BAD, BAD, BAD, BAD, BAD, BAD,
                              26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
                              36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
                              46, 47, 48, 49, 50, 51
                            };

//解码
int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen)
{
    word32 i = 0;
    word32 j = 0;
    word32 plainSz = inLen - ((inLen + (PEM_LINE_SZ - 1)) / PEM_LINE_SZ );
    const byte maxIdx = (byte)sizeof(base64Decode) + 0x2B - 1;

    plainSz = (plainSz * 3 + 3) / 4;
    if (plainSz > *outLen) return BAD_FUNC_ARG;

    while (inLen > 3) {
        byte b1, b2, b3;
        byte e1 = in[j++];
        byte e2 = in[j++];
        byte e3 = in[j++];
        byte e4 = in[j++];

        int pad3 = 0;
        int pad4 = 0;

        if (e1 == 0)            /* end file 0's */
            break;
        if (e3 == PAD)
            pad3 = 1;
        if (e4 == PAD)
            pad4 = 1;

        if (e1 < 0x2B || e2 < 0x2B || e3 < 0x2B || e4 < 0x2B)
         {

            return ASN_INPUT_E;
        }

        if (e1 > maxIdx || e2 > maxIdx || e3 > maxIdx || e4 > maxIdx) {

            return ASN_INPUT_E;
        }

        e1 = base64Decode[e1 - 0x2B];
        e2 = base64Decode[e2 - 0x2B];
        e3 = (e3 == PAD) ? 0 : base64Decode[e3 - 0x2B];
        e4 = (e4 == PAD) ? 0 : base64Decode[e4 - 0x2B];

        b1 = (byte)((e1 << 2) | (e2 >> 4));
        b2 = (byte)(((e2 & 0xF) << 4) | (e3 >> 2));
        b3 = (byte)(((e3 & 0x3) << 6) | e4);

        out[i++] = b1;
        if (!pad3)
            out[i++] = b2;
        if (!pad4)
            out[i++] = b3;
        else
            break;

        inLen -= 4;
        if (inLen && (in[j] == ' ' || in[j] == '\r' || in[j] == '\n')) {
            byte endLine = in[j++];
            inLen--;
            while (inLen && endLine == ' ') {   /* allow trailing whitespace */
                endLine = in[j++];
                inLen--;
            }
            if (endLine == '\r') {
                if (inLen) {
                    endLine = in[j++];
                    inLen--;
                }
            }
            if (endLine != '\n') {

                return ASN_INPUT_E;
            }
        }
    }
    *outLen = i;

    return 0;
}




static
const byte base64Encode[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                              'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                              'U', 'V', 'W', 'X', 'Y', 'Z',
                              'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                              'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                              'u', 'v', 'w', 'x', 'y', 'z',
                              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                              '+', '/'
                            };


/* make sure *i (idx) won't exceed max, store and possibly escape to out,
 * raw means use e w/o decode,  0 on success */
static int CEscape(int escaped, byte e, byte* out, word32* i, word32 max,
                  int raw, int getSzOnly)
{
    int    doEscape = 0;
    word32 needed = 1;
    word32 idx = *i;

    byte basic;
    byte plus    = 0;
    byte equals  = 0;
    byte newline = 0;

    if (raw)
        basic = e;
    else
        basic = base64Encode[e];

    /* check whether to escape. Only escape for EncodeEsc */
    if (escaped == WC_ESC_NL_ENC) {
        switch ((char)basic) {
            case '+' :
                plus     = 1;
                doEscape = 1;
                needed  += 2;
                break;
            case '=' :
                equals   = 1;
                doEscape = 1;
                needed  += 2;
                break;
            case '\n' :
                newline  = 1;
                doEscape = 1;
                needed  += 2;
                break;
            default:
                /* do nothing */
                break;
        }
    }

    /* check size */
    if ( (idx+needed) > max && !getSzOnly) 
    {
        
        return BUFFER_E;
    }

    /* store it */
    if (doEscape == 0) {
        if(getSzOnly)
            idx++;
        else
            out[idx++] = basic;
    }
    else {
        if(getSzOnly)
            idx+=3;
        else {
            out[idx++] = '%';  /* start escape */

            if (plus) {
                out[idx++] = '2';
                out[idx++] = 'B';
            }
            else if (equals) {
                out[idx++] = '3';
                out[idx++] = 'D';
            }
            else if (newline) {
                out[idx++] = '0';
                out[idx++] = 'A';
            }
        }
    }
    *i = idx;

    return 0;
}


/* internal worker, handles both escaped and normal line endings.
   If out buffer is NULL, will return sz needed in outLen */
static int DoBase64_Encode(const byte* in, word32 inLen, byte* out,
                           word32* outLen, int escaped)
{
    int    ret = 0;
    word32 i = 0,
           j = 0,
           n = 0;   /* new line counter */

    int    getSzOnly = (out == NULL);

    word32 outSz = (inLen + 3 - 1) / 3 * 4;
    word32 addSz = (outSz + PEM_LINE_SZ - 1) / PEM_LINE_SZ;  /* new lines */

    if (escaped == WC_ESC_NL_ENC)
        addSz *= 3;   /* instead of just \n, we're doing %0A triplet */
    else if (escaped == WC_NO_NL_ENC)
        addSz = 0;    /* encode without \n */

    outSz += addSz;

    /* if escaped we can't predetermine size for one pass encoding, but
     * make sure we have enough if no escapes are in input
     * Also need to ensure outLen valid before dereference */
    if (!outLen || (outSz > *outLen && !getSzOnly)) return BAD_FUNC_ARG;

    while (inLen > 2) {
        byte b1 = in[j++];
        byte b2 = in[j++];
        byte b3 = in[j++];

        /* encoded idx */
        byte e1 = b1 >> 2;
        byte e2 = (byte)(((b1 & 0x3) << 4) | (b2 >> 4));
        byte e3 = (byte)(((b2 & 0xF) << 2) | (b3 >> 6));
        byte e4 = b3 & 0x3F;

        /* store */
        ret = CEscape(escaped, e1, out, &i, *outLen, 0, getSzOnly);
        if (ret != 0) break;
        ret = CEscape(escaped, e2, out, &i, *outLen, 0, getSzOnly);
        if (ret != 0) break;
        ret = CEscape(escaped, e3, out, &i, *outLen, 0, getSzOnly);
        if (ret != 0) break;
        ret = CEscape(escaped, e4, out, &i, *outLen, 0, getSzOnly);
        if (ret != 0) break;

        inLen -= 3;

        /* Insert newline after PEM_LINE_SZ, unless no \n requested */
        if (escaped != WC_NO_NL_ENC && (++n % (PEM_LINE_SZ/4)) == 0 && inLen){
            ret = CEscape(escaped, '\n', out, &i, *outLen, 1, getSzOnly);
            if (ret != 0) break;
        }
    }

    /* last integral */
    if (inLen && ret == 0) {
        int twoBytes = (inLen == 2);

        byte b1 = in[j++];
        byte b2 = (twoBytes) ? in[j++] : 0;

        byte e1 = b1 >> 2;
        byte e2 = (byte)(((b1 & 0x3) << 4) | (b2 >> 4));
        byte e3 = (byte)((b2 & 0xF) << 2);

        ret = CEscape(escaped, e1, out, &i, *outLen, 0, getSzOnly);
        if (ret == 0)
            ret = CEscape(escaped, e2, out, &i, *outLen, 0, getSzOnly);
        if (ret == 0) {
            /* third */
            if (twoBytes)
                ret = CEscape(escaped, e3, out, &i, *outLen, 0, getSzOnly);
            else
                ret = CEscape(escaped, '=', out, &i, *outLen, 1, getSzOnly);
        }
        /* fourth always pad */
        if (ret == 0)
            ret = CEscape(escaped, '=', out, &i, *outLen, 1, getSzOnly);
    }

    if (ret == 0 && escaped != WC_NO_NL_ENC)
        ret = CEscape(escaped, '\n', out, &i, *outLen, 1, getSzOnly);

    if (i != outSz && escaped != 1 && ret == 0)
        return ASN_INPUT_E;

    *outLen = i;
    if(ret == 0)
        return getSzOnly ? LENGTH_ONLY_E : 0;
    return ret;
}


/* Base64 Encode, PEM style, with \n line endings */
int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen)
{
    return DoBase64_Encode(in, inLen, out, outLen, WC_STD_ENC);
}


/* Base64 Encode, with %0A escaped line endings instead of \n */
int Base64_EncodeEsc(const byte* in, word32 inLen, byte* out, word32* outLen)
{
    return DoBase64_Encode(in, inLen, out, outLen, WC_ESC_NL_ENC);
}

int Base64_Encode_NoNl(const byte* in, word32 inLen, byte* out, word32* outLen)
{
    return DoBase64_Encode(in, inLen, out, outLen, WC_NO_NL_ENC);
}


// 用 mbedtls 实现 HMAC(正确版)
static void hmac_calc(sig_method_e method, const uint32_t *key, uint32_t key_len,
                      const uint8_t *data, uint32_t data_len, uint8_t *out)
{
    const mbedtls_md_info_t *md_info;
    if (method == SIG_METHOD_MD5)      md_info = mbedtls_md_info_from_type(MBEDTLS_MD_MD5);
    else if (method == SIG_METHOD_SHA1)md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
    else                               md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);

    mbedtls_md_context_t ctx;
    mbedtls_md_init(&ctx);
    mbedtls_md_setup(&ctx, md_info, 1);
    mbedtls_md_hmac_starts(&ctx, key, key_len);
    mbedtls_md_hmac_update(&ctx, data, data_len);
    mbedtls_md_hmac_finish(&ctx, out);
    mbedtls_md_free(&ctx);
}
/*****************************************************************************/
/* Local Definitions ( Constant and Macro )                                  */
/*****************************************************************************/
#define DEV_TOKEN_LEN 256
#define DEV_TOKEN_VERISON_STR "2018-10-31"

#define DEV_TOKEN_SIG_METHOD_MD5 "md5"
#define DEV_TOKEN_SIG_METHOD_SHA1 "sha1"
#define DEV_TOKEN_SIG_METHOD_SHA256 "sha256"




int32_t dev_token_generate(char* token,sig_method_e method,uint32_t exp_time, const char* product_id,const char* dev_name,const char* access_key)
{
    if (token == NULL || product_id == NULL || access_key == NULL) 
    {
    return -1; // 或者定义一个 BAD_FUNC_ARG 错误码
    }

    uint8_t  base64_data[128] = { 0 };
    char  str_for_sig[64] = { 0 };
    uint8_t  sign_buf[128]   = { 0 };
    uint32_t base64_data_len = sizeof(base64_data);
    const char* sig_method_str    = NULL;
    uint32_t sign_len        = 0;
    uint32_t i               = 0;
    char* tmp             = NULL;

    // -------------------- 1. 拼接 token 前半段 --------------------
    osl_sprintf(token, (const char*)"version=%s", DEV_TOKEN_VERISON_STR);

    if (dev_name) {
        osl_sprintf(token + osl_strlen(token), (const char*)"&res=products%%2F%s%%2Fdevices%%2F%s", product_id, dev_name);
    } else {
        osl_sprintf(token + osl_strlen(token), (const char*)"&res=products%%2F%s", product_id);
    }

    osl_sprintf(token + osl_strlen(token), (const char*)"&et=%lu", exp_time);

    // -------------------- 2. Base64 解码 access_key --------------------
    Base64_Decode((const byte*)access_key, osl_strlen(access_key), base64_data, &base64_data_len);

    // -------------------- 3. 选择算法 --------------------
    if (SIG_METHOD_MD5 == method) 
    {
        sig_method_str = (char*)DEV_TOKEN_SIG_METHOD_MD5;
        sign_len       = 16;
    } 
    else if (SIG_METHOD_SHA1 == method) 
    {

        sig_method_str = (char*)DEV_TOKEN_SIG_METHOD_SHA1;
        sign_len       = 20;
    } 
    else if (SIG_METHOD_SHA256 == method) 
    {

        sig_method_str = (char*)DEV_TOKEN_SIG_METHOD_SHA256;
        sign_len       = 32;
    } 

    osl_sprintf(token + osl_strlen(token), (const char*)"&method=%s", sig_method_str);
    // -------------------- 4. 拼接 待签名字符串 --------------------
    if (dev_name)
     {
        osl_sprintf(str_for_sig, (const char*)"%lu\n%s\nproducts/%s/devices/%s\n%s", exp_time, sig_method_str, product_id, dev_name, DEV_TOKEN_VERISON_STR);
    } 
    else 
    {
        osl_sprintf(str_for_sig, (const char*)"%lu\n%s\nproducts/%s\n%s", exp_time, sig_method_str, product_id, DEV_TOKEN_VERISON_STR);
    }

    // -------------------- 5. HMAC 签名 --------------------

    hmac_calc(method, base64_data, base64_data_len, (const uint8_t*)str_for_sig, osl_strlen(str_for_sig), sign_buf);

    // -------------------- 6. Base64 编码签名 --------------------
    osl_memset(base64_data, 0, sizeof(base64_data));
    base64_data_len = sizeof(base64_data);
    Base64_Encode_NoNl(sign_buf, sign_len, base64_data, &base64_data_len);

    // -------------------- 7. 拼接 sign + URL 编码 --------------------
    osl_strcat(token, (const char*)"&sign=");
    tmp = token + osl_strlen(token);

    for (i = 0; i < base64_data_len; i++) {
        switch (base64_data[i]) {
            case '+':
                osl_strcat(tmp, (const char*)"%2B");
                tmp += 3;
                break;
            case ' ':
                osl_strcat(tmp, (const char*)"%20");
                tmp += 3;
                break;
            case '/':
                osl_strcat(tmp, (const char*)"%2F");
                tmp += 3;
                break;
            case '?':
                osl_strcat(tmp, (const char*)"%3F");
                tmp += 3;
                break;
            case '%':
                osl_strcat(tmp, (const char*)"%25");
                tmp += 3;
                break;
            case '#':
                osl_strcat(tmp, (const char*)"%23");
                tmp += 3;
                break;
            case '&':
                osl_strcat(tmp, (const char*)"%26");
                tmp += 3;
                break;
            case '=':
                osl_strcat(tmp, (const char*)"%3D");
                tmp += 3;
                break;
            default:
                *tmp = base64_data[i];
                tmp += 1;
                break;
        }
    }

    return 0;
}
相关推荐
时空自由民.2 小时前
ST7701和ST7701S区别
单片机
余生皆假期-2 小时前
永磁同步电机的星形 (Y) 和三角形 (Δ) 有何不同?
单片机·嵌入式硬件
点灯小铭2 小时前
基于单片机的空气质量检测仪系统设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
狂奔蜗牛(bradley)2 小时前
嵌入式软件中如何用责任链模式重构串口协议栈
网络·单片机·mcu·重构·责任链模式
时空自由民.3 小时前
LCD显示的图像散乱原因
单片机
taxunjishu3 小时前
速冻食品物联网网关应用 DeviceNet转Profinet提升产线协同效率
物联网·网络协议·自动化
想你依然心痛3 小时前
HarmonyOS 5.0 IoT开发实战:构建分布式智能设备控制中枢与边缘计算网关
分布式·物联网·harmonyos
悠哉悠哉愿意3 小时前
【单片机复习笔记】十三届国赛复盘2
笔记·单片机·嵌入式硬件
清风6666663 小时前
基于单片机的矿井温度、烟雾与甲烷检测通风报警系统设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业