#!/usr/bin/python
# -*- coding: UTF-8 -*-
import base64
import hashlib
import hmac
import random
import string
import time
import sys
# 生成指定长度的随机字符串
def RandomConnid(length):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
# 生成接入物联云需要的各参数
def IotHmac(productID, devicename, devicePsk):
# 1. 生成connid为一个随机字符串,方便后台定位问题
connid = RandomConnid(5)
# 2. 生成过期时间,表示签名的过期时间,从纪元1970年1月1日 00:00:00 UTC 时间至今秒数的 UTF8 字符串
expiry = int(time.time()) + 60 * 60
# 3. 生成MQTT的clientid部分, 格式为${productid}${devicename}
clientid = "{}{}".format(productID, devicename)
# 4. 生成mqtt的username部分, 格式为${clientid};${sdkappid};${connid};${expiry}
username = "{};12010126;{};{}".format(clientid, connid, expiry)
# 5. 对username进行签名,生成token
token = hmac.new(devicePsk.decode("base64"), username, digestmod=hashlib.sha256).hexdigest()
# 6. 根据物联云通信平台规则生成password字段
password = "{};{}".format(token, "hmacsha256")
return {
"clientid" : clientid,
"username" : username,
"password" : password
}
if __name__ == '__main__':
print IotHmac("OJUY82FOJI", "LED", "eXoydgs5YQx4Xcxhud+rxQ==")
腾讯云生成秘钥代码
猜你喜欢
转载自blog.csdn.net/jiejiemcu/article/details/99231670
今日推荐
周排行