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 [email protected]
 * @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博客

相关推荐
吾日三省吾码16 分钟前
Spring 团队详解:AOT 缓存实践、JSpecify 空指针安全与支持策略升级
java·spring·缓存
风象南34 分钟前
SpringBoot的5种日志输出规范策略
java·spring boot·后端
咖啡啡不加糖41 分钟前
深入理解MySQL死锁:从原理、案例到解决方案
java·数据库·mysql
zimoyin43 分钟前
Compose Multiplatform 实现自定义的系统托盘,解决托盘乱码问题
java
啾啾Fun1 小时前
【Java微服务组件】分布式协调P4-一文打通Redisson:从API实战到分布式锁核心源码剖析
java·redis·分布式·微服务·lua·redisson
消失的旧时光-19431 小时前
Android USB 通信开发
android·java
惊鸿一博1 小时前
java_网络服务相关_gateway_nacos_feign区别联系
java·开发语言·gateway
朝新_7 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir8 小时前
Calendar类日期设置进位问题
java·开发语言
季鸢9 小时前
Java设计模式之状态模式详解
java·设计模式·状态模式