Port Python hmac on Java produsing different result

159 views Asked by At

I don't know Python( Trying port this Python script on Java (Google Music Api (unoficial)):

import base64
import hmac
from hashlib import sha1

base = "11"
key = "34ee7983-5ee6-4147-aa86-443ea062abf774493d6a-2a15-43fe-aace-e78566927585"
salt = '1386759932759'

mac = hmac.new(key, base, sha1) 
mac.update(salt)
sig = base64.urlsafe_b64encode(mac.digest())
print sig;
#nYVoP7wXhJAMGLlY4mcCwfIilMw=

Java version:

String sig = "";
String salt = "1386759932759";
String base_string = "11";
String key = "34ee7983-5ee6-4147-aa86-443ea062abf774493d6a-2a15-43fe-aace-e78566927585";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm());
    mac.init(secret);
    mac.update(salt.getBytes("UTF-8"));
    byte[] digest = mac.doFinal(base_string.getBytes());
    sig = new String(android.util.Base64.encode(digest, android.util.Base64.URL_SAFE));
} catch (Exception e) {
    e.printStackTrace();
}
AQUtility.debug("computeSignature",sig);
//Return: H2in0WNfxSCEz3CHNrMVbqfgXt4=

Why result different? Help pls(

1

There are 1 answers

0
recoilme On BEST ANSWER

Found error. Need do base before salt:

String sig = "";
String salt = "1386759932759";
String base_string = "11";
String key = "34ee7983-5ee6-4147-aa86-443ea062abf774493d6a-2a15-43fe-aace-e78566927585";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm());
    mac.init(secret);
    mac.update(base_string.getBytes());
    byte[] digest = mac.doFinal(salt.getBytes());
    sig = new String(android.util.Base64.encode(digest, android.util.Base64.URL_SAFE));
} catch (Exception e) {
    e.printStackTrace();
}
AQUtility.debug("computeSignature",sig);
//nYVoP7wXhJAMGLlY4mcCwfIilMw=