1

我必须用 Java 编写客户端提供的 Ruby 代码。该代码使用密钥和 Base64 编码来形成 hmac 值。我尝试用 Java 编写类似的代码,但生成的 hmac 值与 Ruby 脚本结果不匹配。请找到下面的 Java 和 Ruby 代码块以及结果输出。

Java 代码:

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 输出:哈希:[B@72a32604

红宝石代码:

  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

红宝石输出:哈希:Nxe7tOBsbxLpsrqUJjncrPFI50E=

4

1 回答 1

0

正如评论中提到的,您正在打印字节数组的描述,而不是内容:

代替:

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

和:

System.out.println("hash: " + new String(hash, StandardCharsets.UTF_8));
于 2014-11-25T15:58:22.557 回答