我必须用Java编写客户端提供的Ruby代码。该代码使用密钥和Base64编码来形成hmac值。我试图在Java中编写类似的代码,但结果的hmac值与Ruby脚本结果不匹配。请找到以下Java和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
Ruby代码:
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输出:哈希:Nxe7tOBsbxLpsrqUJjncrPFI50E =
答案 0 :(得分:0)
如评论中所述,您打印的是字节数组的描述,而不是内容:
替换:
System.out.println("hash :" + hash);
使用:
System.out.println("hash: " + new String(hash, StandardCharsets.UTF_8));