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博客

相关推荐
杰克尼35 分钟前
springCloud_day07(MQ高级)
java·spring·spring cloud
NHuan^_^2 小时前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot
Mr_Xuhhh2 小时前
从ArrayList到LinkedList:理解链表,掌握Java集合的另一种选择
java·数据结构·链表
错把套路当深情3 小时前
Java 全方向开发技术栈指南
java·开发语言
han_hanker3 小时前
springboot 一个请求的顺序解释
java·spring boot·后端
MaCa .BaKa3 小时前
44-校园二手交易系统(小程序)
java·spring boot·mysql·小程序·maven·intellij-idea·mybatis
希望永不加班3 小时前
SpringBoot 静态资源访问(图片/JS/CSS)配置详解
java·javascript·css·spring boot·后端
oh LAN3 小时前
RuoYi-Vue-master:Spring Boot 4.x (JDK 17+) (环境搭建)
java·vue.js·spring boot
ch.ju3 小时前
Java程序设计(第3版)第二章——java的数据类型:小数
java
Advancer-4 小时前
RedisTemplate 两种序列化实践方案
java·开发语言·redis