1

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

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

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);
4

1 回答 1

2

如果我们要查看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 ;
    }
于 2012-11-20T10:25:37.130 回答