MQTT AiotMqttOption.java

复制代码
package mqtt;

import java.math.BigInteger;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * https://linkkit-export.oss-cn-shanghai.aliyuncs.com/paho/android_sameple_code.zip?spm=a2c63.p38356.0.0.488769ccON8nor&file=android_sameple_code.zip
 * MQTT建连选项类,输入设备三元组productKey, deviceName和deviceSecret, 生成Mqtt建连参数clientId,username和password.
 *
 * @author ZengWenFeng
 * @email 117791303@qq.com
 * @mobile 13805029595
 */
public class AiotMqttOption
{
	private String username = "";
	private String password = "";
	private String clientId = "";

	public String getUsername()
	{
		return this.username;
	}

	public String getPassword()
	{
		return this.password;
	}

	public String getClientId()
	{
		return this.clientId;
	}

	/**
	    * 获取Mqtt建连选项对象
	    * @param productKey 产品秘钥
	    * @param deviceName 设备名称
	    * @param deviceSecret 设备机密
	    * @return AiotMqttOption对象或者NULL
	    */
	public AiotMqttOption getMqttOption(String productKey, String deviceName, String deviceSecret)
	{
		if (productKey == null || deviceName == null || deviceSecret == null)
		{
			return null;
		}

		try
		{
			String timestamp = Long.toString(System.currentTimeMillis());

			// clientId
			this.clientId = productKey + "." + deviceName + "|timestamp=" + timestamp + ",_v=paho-android-1.0.0,securemode=2,signmethod=hmacsha256|";

			// userName
			this.username = deviceName + "&" + productKey;

			// password
			String macSrc = "clientId" + productKey + "." + deviceName + "deviceName" + deviceName + "productKey" + productKey + "timestamp" + timestamp;
			String algorithm = "HmacSHA256";
			Mac mac = Mac.getInstance(algorithm);
			SecretKeySpec secretKeySpec = new SecretKeySpec(deviceSecret.getBytes(), algorithm);
			mac.init(secretKeySpec);
			byte[] macRes = mac.doFinal(macSrc.getBytes());
			password = String.format("%064x", new BigInteger(1, macRes));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}

		return this;
	}
}

MQTT常用语物联网上硬件设备和软件之间的通讯通道

Pet Detection System (PDS)_spencer_tseng的博客-CSDN博客

相关推荐
海的透彻4 小时前
dockerfile如何快速构建容器(java服务)
java·开发语言
code2cat4 小时前
Java工具篇之Gradle:用任务图组织构建与交付
java·开发语言·单元测试·gradle
后台模板学习4 小时前
大模型 Prompt 工程在电商订单系统中的踩坑记录
java·python·prompt
w_zero_one5 小时前
算法--构造
java·数据结构·算法
SL_staff5 小时前
制造业订单交付崩盘?用四层协同框架重建交付可信度(技术实践)
java·产品·全栈
SL_staff6 小时前
打破风控迭代死循环:用决策编排重构业务与技术协作链路
java·产品·全栈
Mikko76 小时前
Redis 连接数满了服务端有错误信息吗?连接数不增加却命令超时?6.2 实测连接池、超时与大 key 怎么判定
java·spring boot·redis·后端
.Bryce.6 小时前
从零到一开发技术名词大全:从需求分析到 AI Agent 工程
java·网络·人工智能·agent·需求分析·agent评测
SL_staff6 小时前
JVS-APS的7个刚性约束设计:从无限产能幻觉到可执行排产的工程实践
java·spring cloud·全栈
代码山河8 小时前
基本类型转换:自动类型转换与强制类型转换
java·学习·架构·教程·面向对象·项目