1

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=

Rubyist
  • 6,486
  • 10
  • 51
  • 86
  • You're not comparing the right thing: http://stackoverflow.com/questions/1040868/java-syntax-and-meaning-behind-b1ef9157-binary-address – zapl Nov 25 '14 at 13:07
  • 1
    A `byte[]` is not a `String`! Try and print `new String(hash, StandardCharsets.UTF_8)` instead. Also, you should specify an encoding when you `.getBytes()` on a `String`. – fge Nov 25 '14 at 13:13
  • What do you want to find in that code? – Danubian Sailor Nov 25 '14 at 14:04

1 Answers1

0

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));
Christophe Biocca
  • 3,388
  • 1
  • 23
  • 24