0

One of the part of API auth is to create bodyHash as a part of headers. The documentation is laconic:

Hash of the message body using the HMAC Sha256 algorithm. Your secret key is used to generate the hash.

And they provided an example in Java:

import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AuthorizationMacHeader {
    private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
    private static final String UTF8_ENCODING = "UTF-8";
/**
 * @param key_id
 *            : Your key id
 * @param secret_key
 *            : Your secret key
 * @param payload
 *            : payload
 * @return
 * @throws Exception
 */

 // create the bodyHash value by hashing the payload and encoding it
 SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(UTF8_ENCODING), 
 HMAC_SHA256_ALGORITHM);
 Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
 mac.init(signingKey);
 byte[] rawBodyHash = mac.doFinal(payload.getBytes(UTF8_ENCODING));
 String bodyHash = Base64.encodeBase64String(rawBodyHash);

So what I did in Ruby was:

require 'json'
require 'base64'
require 'openssl'

KEY_ID = 'Syb6i+sRygAGCgxLQJ4NwwKcT5'
SECRET_KEY = 'Mnkh4r3QXgwZ3vmcE='

payload = { some: 'hash' }.to_json

mac = Base64.strict_encode64(OpenSSL::HMAC.digest('SHA256', SECRET_KEY, payload))

puts mac
 => "DzWVea1hH+F3S2SuYWfyBjGCJI0bJ4393+kH1dU6LFc="

But I'm not sure if this is correct because the Java class has UTF8_ENCODING part. I don't understand what this is all about?

If something will be unclear, full example of java class below: https://gist.github.com/mrmuscle1234/881144360e13ac1ac1794610c456d035

3
  • I cannot reproduce the posted result of the Ruby code with the posted input data. And what is the input data and the result of the Java code? On my machine the results of both codes are identical (using the same input data). What exactly is the problem?
    – Topaco
    Nov 23, 2021 at 13:05
  • @Topaco I added 3 libraries in the Ruby code, should be fine now. The problem is described in the question - I don't know if my Ruby class will produce the same results as a Java class. I don't know how to test this Java class and I don't know why there is the UTF8_ENCODING part.
    – mr_muscle
    Nov 23, 2021 at 13:34
  • 1
    The Java code produces the same result: jdoodle.com/iembed/v0/k2W. In Ruby code it is implicitly UTF-8 encoded, you can also explicitly use SECRET_KEY = 'Mnkh4r3QXgwZ3vmcE='.encode('utf-8') without changing the result, s. online here: replit.com/@3hK8cL8H24hwiS7/ProudUnfitMigration.
    – Topaco
    Nov 23, 2021 at 13:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.