Skip to content

Commit

Permalink
✨ 完善示例
Browse files Browse the repository at this point in the history
  • Loading branch information
ChunMengLu committed Sep 10, 2022
1 parent a1114be commit cd24411
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static void main(String[] args) {
.username(username)
.password(password)
.clientId(clientId)
.connectSync(); // 使用同步
.connect();

client.subQos0("/sys/" + productKey + '/' + deviceName + "/thing/event/property/post_reply", (topic, payload) -> {
System.out.println(topic + '\t' + ByteBufferUtil.toString(payload));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@

package net.dreamlu.iot.mqtt.aliyun;

import net.dreamlu.iot.mqtt.core.util.HexUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
Expand Down Expand Up @@ -83,7 +84,7 @@ private static String hmacSha256(String plainText, String key) {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hmacResult = mac.doFinal(plainText.getBytes());
return String.format("%064x", new BigInteger(1, hmacResult));
return HexUtil.encodeToString(hmacResult);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package net.dreamlu.iot.mqtt.huawei;

import net.dreamlu.iot.mqtt.core.util.HexUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.time.Instant;
Expand Down Expand Up @@ -87,27 +89,11 @@ private static String hmacSha256(String message, String tStamp) {
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
hmacSHA256.init(new SecretKeySpec(tStamp.getBytes(), "HmacSHA256"));
byte[] bytes = hmacSHA256.doFinal(message.getBytes());
return byteArrayToHexString(bytes);
return HexUtil.encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/***
* byte数组转16进制字符串
*/
private static String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
hs.append('0');
}
hs.append(stmp);
}
return hs.toString().toLowerCase();
}

}

0 comments on commit cd24411

Please sign in to comment.