2014-11-25 67 views
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 =

+0

你”重新比较不正确的东西:http://stackoverflow.com/questions/1040868/java-syntax-and-meaning-behind-b1ef9157-binary-address – zapl 2014-11-25 13:07:21

+1

一个'byte []'不是'字符串'!尝试并打印'新的字符串(hash,StandardCharsets.UTF_8)'。另外,当你在'String'的'.getBytes()'时,你应该指定一个编码。 – fge 2014-11-25 13:13:36

+0

你想在代码中找到什么? – 2014-11-25 14:04:28

回答

0

正如评论mentionned,你打印你的字节数组,而不是内容的描述:

替换:

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

有了:

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