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

相关推荐
幽络源小助理7 分钟前
SpringBoot基于JavaWeb的城乡居民基本医疗信息管理系统
java·spring boot·学习
欧阳有财10 分钟前
[java八股文][Mysql面试篇]日志
java·mysql·面试
TDengine (老段)19 分钟前
使用 StatsD 向 TDengine 写入
java·大数据·数据库·时序数据库·iot·tdengine·涛思数据
真实的菜22 分钟前
JVM类加载系统详解:深入理解Java类的生命周期
java·开发语言·jvm
N_NAN_N1 小时前
类图+案例+代码详解:软件设计模式----原型模式
java·设计模式·原型模式
佛祖保佑永不宕机1 小时前
maven引入本地jar包
java·maven·jar
默默coding的程序猿1 小时前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
在未来等你1 小时前
JVM调优实战 Day 15:云原生环境下的JVM配置
java·jvm·性能优化·虚拟机·调优
funnycoffee1231 小时前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为
Java初学者小白1 小时前
秋招Day15 - Redis - 缓存设计
java·数据库·redis·缓存