我想用MQTT客户端进行收发的测试,但是根据文档上的描述计算出的计算出的结果与文档中提供的结果不相符,请帮我看一下是哪里有问题,谢谢啦!
我计算的结果:
hmacsha1 : +v2Co9YCs3+w+ot4kvJKR3+FGhQ=
clientId : 12345|securemode=3,signmethod=hmacsha1,timestamp=789|
username : device&pk
password : 2B7632436F39594373332B772B6F74346B764A4B52332B464768513D
代码:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Test
{
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String hmacsha1(String key, String data) {
byte[] result = null;
try {
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
//用给定密钥初始化 Mac 对象
mac.init(signinKey);
//完成 Mac 操作
byte[] rawHmac = mac.doFinal(data.getBytes());
result = Base64.encodeBase64(rawHmac);
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
} catch (InvalidKeyException e) {
System.err.println(e.getMessage());
}
if (null != result) {
return new String(result);
} else {
return null;
}
}
public static String convert2HexString(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
public static void main( String[] args )
{
// 三元
String deviceName = "device";
String deviceSecret = "secret";
String productKey = "pk";
// 配置信息
String clientId = "12345";
String signmethod = "hmacsha1";
int securemode = 3;
int timestamp = 789;
String content = String.format("clientId%sdeviceName%sproductKey%stimestamp%d", clientId, deviceName, productKey, timestamp);
String mqttclientId = String.format("%s|securemode=%d,signmethod=%s,timestamp=%d|", clientId, securemode, signmethod, timestamp);
String username = String.format("%s&%s", deviceName, productKey);
String sha1 = hmacsha1(deviceSecret, content);
String password = convert2HexString(sha1).toUpperCase();
// 显示输出
System.out.println("hmacsha1 : " + sha1);
System.out.println("clientId : " + mqttclientId);
System.out.println("username : " + username);
System.out.println("password : " + password);
}
}