I am trying to generate the HMAC SHA1 key using few parameters in Apex, but seems the output is different from that of the java code

My Apex Code:

String privateKey = 'bc30540b248aa5eb717c133ae3038222113f2a77';
String input = '[email protected]:55:34Z';
Blob Signature = Crypto.generateMac('HmacSHA1', Blob.ValueOf(input), Blob.ValueOf(privateKey));
System.debug('Final sign ='+ EncodingUtil.urlEncode(EncodingUtil.base64encode(Signature), 'UTF-8'));

Java code:

    String key = "bc30540b248aa5eb717c133ae3038222113f2a77";
    String data = "[email protected]:55:34Z";
    byte[] decodedKey = Hex.decodeHex(key.toCharArray());
    SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    byte[] dataBytes = data.getBytes("UTF-8");
    byte[] signatureBytes = mac.doFinal(dataBytes);
    String signature = new String(Base64.encodeBase64(signatureBytes), "UTF-8");
    String signatureParam = URLEncoder.encode(signature, "UTF-8");
    System.out.println("signatureParam = " + signatureParam); 

Output from the Apex code is

Final sign = m491puKdMNVcbmlQgUhe547853w%3D

Output from the Java code is

signatureParam = GeJ38GfvibEuH%2B84VZeANAy75kU%3D

Not sure what I am missing in the Apex code? Any advice is appreciated.

  • 1
    Possibly duplicate of salesforce.stackexchange.com/questions/92589/…
    – Lance Shi
    Commented Sep 23, 2015 at 5:04
  • Hi @Shi I followed the steps which was mentioned in the article you mentioned and I am not decoding my the key in my case. Even then I am not getting the same results. Therefore I posted this question.
    – Aren
    Commented Sep 23, 2015 at 5:38
  • Okay, to clarify. The -1 is not coming from me. I am not sure where is it coming from.
    – Lance Shi
    Commented Sep 23, 2015 at 5:47

1 Answer 1


In your Java code, you are unencoding the private key from hex, but you are not doing that in Apex. So, you need to modify your code to the following:

Blob privateKey = EncodingUtil.convertFromHex('bc30540b248aa5eb717c133ae3038222113f2a77');
String input = '[email protected]:55:34Z';
Blob Signature = Crypto.generateMac('HmacSHA1', Blob.ValueOf(input), privateKey);
System.debug('Final sign ='+ EncodingUtil.urlEncode(EncodingUtil.base64encode(Signature), 'UTF-8'));

That does give the same result as your Java


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .