腾讯物联网云平台 密钥 MQTT参数生成及密码加密算法实现

Posted 穿着裤衩扮超人!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了腾讯物联网云平台 密钥 MQTT参数生成及密码加密算法实现相关的知识,希望对你有一定的参考价值。

腾讯物联网云平台 密钥 MQTT参数生成及密码加密算法实现

腾讯云三元组

首先在腾讯物联网云平台创建好项目、产品、设备,然后获取该设备的三元组。下面通过我的创建的产品作为示例:
ProductID:IAYFFH3EO2
DeviceName:dev3
DeviceSecret: xjOShbtCetQmvEaJ75RJ1g==
#获取clinetID、Username、Password
clientID:IAYFFH3EO2dev3(ProductID+DeviceName)

Username:IAYFFH3EO2dev3;12010126;HD3CI;1635759071( c l i e n t i d ; {clientid}; clientid;{sdkappid}; c o n n i d ; {connid}; connid;{expiry})
sdkappid、connid可随机生成,但注意字符个数sdkappid为8个字符,connid为5个字符。expiry为失效时间戳,即超过该时间戳后该密钥失效。Username可通过后面的加密算法自动生成,不需要自行生成。

Password:password 是由Username和DeviceSecret进行hmacSha1或者hmacSha256生成的,而且DeviceSecret是通过base64加密生成的,在生成Password前需要DeviceSecret解密base64,再进行hmacSha1或者hmacSha256加密生成。

腾讯云也提供了几种语言的算法实现,目前试过python的脚本是hmacsha256算法脚本且能正常生成参数但是我们是进行C开发的所以不适合通过调用python脚本来生成。其提供的C是hmacsha1算法但是工程不完整的而且是HAL平台的。本人通过下载腾讯云的sdk将一部分代码提取了出来,实现c通过hmacsha1算法生成clientID、Username、Password。
test.c

#include "limits.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "utils_base64.h"
#include "utils_hmac.h"
#include <time.h>
#include <string.h>

/* Max size of base64 encoded PSK = 64, after decode: 64/4*3 = 48*/
#define DECODE_PSK_LENGTH 48

/* MAX valid time when connect to MQTT server. 0: always valid */
/* Use this only if the device has accurate UTC time. Otherwise, set to 0 */
#define MAX_ACCESS_EXPIRE_TIMEOUT (60 * 1000)  //过期时间我这里设置的是1分钟,只要每次连接前都生成一次这里可以设置为0

/* Max size of conn Id  */
#define MAX_CONN_ID_LEN (6)

/* IoT C-SDK APPID */
#define QCLOUD_IOT_DEVICE_SDK_APPID     "12010126"   //sdkappid设置的固定值
#define QCLOUD_IOT_DEVICE_SDK_APPID_LEN (sizeof(QCLOUD_IOT_DEVICE_SDK_APPID) - 1)

static void HexDump(uint8_t *pData, uint16_t len)
{
    int i;

    for (i = 0; i < len; i++) {
        if (i % 32 == 0) {
            printf("\\n");
        }
        printf(" %02X", pData[i]);
    }
    printf("\\n");
}


int main(int argc, char **argv)
{
    char *product_id    = NULL;
    char *device_name   = NULL;
    char *device_secret = NULL;

    char *username     = NULL;
    int   username_len = 0;
    char  conn_id[MAX_CONN_ID_LEN];

    char password[51]      = {0};
    char username_sign[41] = {0};

    char   psk_base64decode[DECODE_PSK_LENGTH];
    size_t psk_base64decode_len = 0;

    long cur_timestamp = 0;

    if (argc != 4) {
        printf("please ./qcloud-mqtt-sign product_id device_name device_secret\\r\\n");
        return -1;
    }

    product_id    = argv[1];
    device_name   = argv[2];
    device_secret = argv[3];

    /* first device_secret base64 decode */
    qcloud_iot_utils_base64decode((unsigned char *)psk_base64decode, DECODE_PSK_LENGTH, &psk_base64decode_len,(unsigned char *)device_secret, strlen(device_secret));
    //base64_decode(device_secret, psk_base64decode);
    printf("device_secret base64 decode:");


    HexDump(psk_base64decode, psk_base64decode_len);

    /* second create mqtt username
     * [productdevicename;appid;randomconnid;timestamp] */
    cur_timestamp = time(NULL) + MAX_ACCESS_EXPIRE_TIMEOUT / 1000;
    if (cur_timestamp <= 0 || MAX_ACCESS_EXPIRE_TIMEOUT <= 0) {
        cur_timestamp = LONG_MAX;
    }

    // 20 for timestampe length & delimiter
    username_len = strlen(product_id) + strlen(device_name) + QCLOUD_IOT_DEVICE_SDK_APPID_LEN + MAX_CONN_ID_LEN + 20;
    username     = (char *)malloc(username_len);
    if (username == NULL) {
        printf("malloc username failed!\\r\\n");
        return -1;
    }

    snprintf(username, username_len, "%s%s;%s;%s;%ld", product_id, device_name, QCLOUD_IOT_DEVICE_SDK_APPID,"HD3CI", cur_timestamp);  //connid设置的固定值HD3CI

    /* third use psk_base64decode hamc_sha1 calc mqtt username sign crate mqtt
     * password */
    utils_hmac_sha1(username, strlen(username), username_sign, psk_base64decode, psk_base64decode_len);

    //Hmacsha256_enc(psk_base64decode,psk_base64decode_len,username,strlen(username),username_sign);
    printf("username sign: %s\\r\\n", username_sign);
    snprintf(password, 51, "%s;hmacsha1", username_sign);

    printf("Client ID: %s%s\\r\\n", product_id, device_name);
    printf("username : %s\\r\\n", username);
    printf("password : %s\\r\\n", password);

    free(username);

    return 0;
}

utils_base64.c

/*
 * Tencent is pleased to support the open source community by making IoT Hub
 available.
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.

 * Licensed under the MIT License (the "License"); you may not use this file
 except in
 * compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT

 * Unless required by applicable law or agreed to in writing, software
 distributed under the License is
 * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND,
 * either express or implied. See the License for the specific language
 governing permissions and
 * limitations under the License.
 *
 */

#ifdef __cplusplus
extern "C" {
#endif

#include "utils_base64.h"

#include <stdint.h>
#include <stdlib.h>

static const unsigned char base64_enc_map[64] = {
    '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', '+', '/'};

static const unsigned char base64_dec_map[128] = {
    127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
    127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 62,
    127, 127, 127, 63,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  127, 127, 127, 64,  127, 127, 127, 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,  127, 127, 127, 127, 127, 127, 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,  127, 127, 127, 127, 127};

#define BASE64_SIZE_T_MAX ((size_t)-1) /* SIZE_T_MAX is not standard */

int qcloud_iot_utils_base64encode(unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen)
{
    size_t         i, n;
    unsigned char *p;

    if (slen == 0) {
        *olen = 0;
        return (0);
    }

    n = slen / 3 + (slen % 3 != 0);

    if (n > (BASE64_SIZE_T_MAX - 1) / 4) {
        *olen = BASE64_SIZE_T_MAX;
        return (QCLOUD_ERR_FAILURE);
    }

    n *= 4;

    if ((dlen < n + 1) || (NULL == dst)) {
        *olen = n + 1;
        return (QCLOUD_ERR_FAILURE);
    }

    n = (slen / 3) * 3;

    int C1, C2, C3;
    for (i = 0, p = dst; i < n; i += 3) {
        C1 = *src++;
        C2 = *src++;
        C3 = *src++;

        *p++ = base64_enc_map[(C1 >> 2) & 0x3F];
        *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
        *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];
        *p++ = base64_enc_map[C3 & 0x3F];
    }

    if (i < slen) {
        C1 = *src++;
        C2 = ((i + 1) < slen) ? *src++ : 0;

        *p++ = base64_enc_map[(C1 >> 2) & 0x3F];
        *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];

        if ((i + 1) < slen)
            *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];
        else
            *p++ = '=';

        *p++ = '=';
    }

    *olen = p - dst;
    *p    = 0;

    return (0);
}

int qcloud_iot_utils_base64decode(unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen)
{
    size_t         i, n;
    uint32_t       j, x;
    unsigned char *p;

    /* First pass: check for validity and get output length */
    for (i = n = j = 0; i < slen; i++) {
        /* Skip spaces before checking for EOL */
        x = 0;
        while (i < slen && src[i] == ' ') {
            ++i;
            ++x;
        }

        /* Spaces at end of buffer are OK */
        if (i == slen)
            break;

        if ((slen - i) >= 2 && src[i] == '\\r' && src[i + 1] == '\\n')
            continue;

        if (src[i] == '\\n')
            continue;

        /* Space inside a line is an error */
        if (x != 0)
            return (QCLOUD_ERR_FAILURE);

        if (src[i] == '=' && ++j > 2)
            return (QCLOUD_ERR_FAILURE);

        if (src[i] > 127 || base64_dec_map[src[i]] == 127)
            return (QCLOUD_ERR_FAILURE);

        if (base64_dec_map[src[i]] < 64 && j != 0)
            return (QCLOUD_ERR_FAILURE);

        n++;
    }

    if (n == 0) {
        *olen = 0;
        return (0);
    }

    n = ((n * 6) + 7) >> 3;
    n -= j;

    if (dst == NULL || dlen < n) {
        *olen = n;
        return (QCLOUD_ERR_FAILURE);
    }

    for (j = 3, n = x = 0, p = dst; i > 0; i--, src++) {
        if (*src == '\\r' || *src == '\\n' || *src == ' ')
            continue;

        j -= (base64_dec_map[*src] == 64);
        x = (x << 6) | (base64_dec_map[*src] & 0x3F);

        if (++n == 4) {
            n = 0;
            if (j > 0)
                *p++ = (unsigned char)(x >> 16);
            if (j > 1)
                *p++ = (unsigned char)(x >> 8);
            ESP32上手笔记 | 04 -通过MQTT对接腾讯云IoT Explorer物联网平台(PubSubClient)

4G DTU MQTT连接华为物联网云平台

使用MQTT连接华为云的物联网平台

物联网云平台远程控制源码,响应式布局,MQTT协议 Spring Boot

使用MQTT连接华为云的物联网平台

Qt软件开发: 编写MQTT客户端连接各大物联网平台(主题订阅发布)