HMAC value calculated from Java is not matching with Ruby code

1k views Asked by At

I have to write client provided Ruby code in Java. The code uses secret key and Base64 encoding to form hmac value. I tried to write similar code in Java but the resulted hmac value is not matching with the Ruby script result. Please find the below block of code for Java & Ruby along with resulted output.

Java Code:

public static void main(String[] args)
    throws NoSuchAlgorithmException, InvalidKeyException
{
    // get an hmac_sha1 key from the raw key bytes
    String secretKey =
        "Ye2oSnu1NjzJar1z2aaL68Zj+64FsRM1kj7I0mK3WJc2HsRRcGviXZ6B4W+/V2wFcu78r8ZkT8=";

    byte[] secretkeyByte = Base64.decodeBase64(secretKey.getBytes());
    SecretKeySpec signingKey = new SecretKeySpec(secretkeyByte, "HmacSHA1");
    // get an hmac_sha1 Mac instance and initialize with the signing key.
    String movingFact = "0";
    byte[] text = movingFact.getBytes();
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    // compute the hmac on input data bytes
    byte[] rawHmac = mac.doFinal(text);
    byte[] hash = Base64.encodeBase64(rawHmac);
    System.out.println("hash :" + hash);
}

Java Output: hash :[B@72a32604

Ruby Code:

  def get_signature()   
    key = Base64.decode64("Ye2oSnu1NjzJar1z2aaL68Zj+64FsRM1kj7I0mK3WJc2HsRRcGviXZ6B4W+/V2wFcu78r8ZkT8=")
    digest = OpenSSL::Digest::Digest.new('sha1')
    string_to_sign = "0"
    hash = Base64.encode64(OpenSSL::HMAC.digest(digest, key, string_to_sign))
    puts "hash: " + hash
  end

Ruby Output: hash: Nxe7tOBsbxLpsrqUJjncrPFI50E=

1

There are 1 answers

0
Christophe Biocca On

As mentionned in the comments, you're printing the description of your byte array, not the contents:

Replace:

System.out.println("hash :" + hash);

With:

System.out.println("hash: " + new String(hash, StandardCharsets.UTF_8));