将HMAC-SHA256函数从Java转换为Ruby

时间:2013-12-22 02:00:55

标签: java ruby hmac sha256

我正在尝试将这个哈希函数从Java转换为Ruby。

Java代码:

  Mac localMac = "HMAC-SHA256";
  String str1 = "a4d1b77bbb1a4a5ca695ad72c84b77e5";
  localMac.init(new SecretKeySpec(str1.getBytes("UTF-8"), localMac.getAlgorithm()));
  byte[] arrayOfByte = localMac.doFinal("{"_uid":"3396112","_csrftoken":"a23482932482sdsf4428","media_id":"616150302791211280_187036957"}");
  BigInteger localBigInteger = new BigInteger(1, arrayOfByte);
  String str3 = String.format("%0" + (arrayOfByte.length << 1) + "x", new Object[] { localBigInteger });
  return str3;

Ruby代码:

require 'openssl'
require 'base64'

secret = "a4d1b77bbb1a4a5ca695ad72c84b77e5"
digest = OpenSSL::Digest::Digest.new('sha256')
hash  = OpenSSL::HMAC.hexdigest(digest, secret,'{"_uid":"3396112","_csrftoken":"a23482932482sdsf4428","media_id":"616150302791211280_187036957"}')
p hash

由于某些原因,哈希从不相同。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

你可以这样做

public static void main(String[] args) {
  String str1 = "a4d1b77bbb1a4a5ca695ad72c84b77e5";
  byte[] keyBytes = str1.getBytes();
  SecretKeySpec localMac = new SecretKeySpec(
      keyBytes, "HmacSHA256");
  final String inputStr = "{\"_uid\":\"3396112\",\"_csrftoken\":"
      + "\"a23482932482sdsf4428\","
      + "\"media_id\":\"616150302791211280_187036957\"}";
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(localMac);
    // Compute the hmac on input data bytes
    byte[] arrayOfByte = mac.doFinal(inputStr
        .getBytes());
    BigInteger localBigInteger = new BigInteger(1,
        arrayOfByte);
    String str3 = String.format("%0"
        + (arrayOfByte.length << 1) + "x",
        new Object[] { localBigInteger });
    System.out.println(str3);
  } catch (InvalidKeyException e) {
    e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  } catch (IllegalStateException e) {
    e.printStackTrace();
  }
}

将输出e48d690dc6825e8f2895845be112fb1e5ee22f5283f2243512d6cca2714e8b35

$ cat test.rb
#!/usr/bin/env ruby

require 'openssl'
require 'base64'

secret = "a4d1b77bbb1a4a5ca695ad72c84b77e5"
digest = OpenSSL::Digest::Digest.new('sha256')
hash  = OpenSSL::HMAC.hexdigest(digest, secret,'{"_uid":"3396112","_csrftoken":"a23482932482sdsf4428","media_id":"616150302791211280_187036957    "}')
p hash
$ ./test.rb
"e48d690dc6825e8f2895845be112fb1e5ee22f5283f2243512d6cca2714e8b35"