gpt4 book ai didi

java - java中的散列json

转载 作者:行者123 更新时间:2023-11-30 04:36:11 26 4
gpt4 key购买 nike

我正在尝试连接到 Grooveshark api。这是 Grooveshark 签署请求的指南: http://developers.grooveshark.com/tuts/public_api

这就是我签署数据的方式。但我收到错误:“签名无效”。我应该形成 JsonObject 还是数据可以是 String?

String data = "{\"method\":\"getArtistSearchResults\",\"parameters\":{\"query\":\"adele\"},\"header\":{\"wsKey\":\"concertboom\"}}";

String key = "XXXXX";

SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] result = mac.doFinal(data.getBytes());

BASE64Encoder encoder = new BASE64Encoder();

signature = encoder.encode(result);

最佳答案

如果我们要查看 http://developers.grooveshark.com/docs/public_api/v3/ ,以下代码应该可以工作:

    private static final String EXPECTED_SIGNATURE = "cd3ccc949251e0ece014d620bbf306e7";

@Test
public void testEnc() throws NoSuchAlgorithmException, InvalidKeyException {
String key = "key";
String secret = "secret";
String payload = "{'method': 'addUserFavoriteSong', 'parameters': {'songID': 0}, 'header': {'wsKey': 'key', 'sessionID': 'sessionID'}}";

String signature = getHmacMD5(payload, secret);
assertEquals(EXPECTED_SIGNATURE, signature);

}

public static String getHmacMD5(String payload, String secret) {
String sEncodedString = null;
try {
SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(key);

byte[] bytes = mac.doFinal(payload.getBytes("UTF-8"));

StringBuffer hash = new StringBuffer();

for (int i=0; i<bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
sEncodedString = hash.toString();
}
catch (UnsupportedEncodingException e) {}
catch(InvalidKeyException e){}
catch (NoSuchAlgorithmException e) {}
return sEncodedString ;
}

关于java - java中的散列json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13469938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com