1
我必須用Java編寫客戶端提供的Ruby代碼。該代碼使用密鑰和Base64編碼形成hmac值。我試圖用Java編寫類似的代碼,但是結果的hmac值與Ruby腳本結果不匹配。請查找以下代碼塊,以獲取Java & Ruby以及結果輸出。從Java計算的HMAC值與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);
}
爪哇輸出:哈希:[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
紅寶石輸出:哈希: Nxe7tOBsbxLpsrqU JjncrPFI50E =
你」重新比較不正確的東西:http://stackoverflow.com/questions/1040868/java-syntax-and-meaning-behind-b1ef9157-binary-address – zapl 2014-11-25 13:07:21
一個'byte []'不是'字符串'!嘗試並打印'新的字符串(hash,StandardCharsets.UTF_8)'。另外,當你在'String'的'.getBytes()'時,你應該指定一個編碼。 – fge 2014-11-25 13:13:36
你想在代碼中找到什麼? – 2014-11-25 14:04:28