PHP and Java hmac hash output matches in hex, doesn't match in raw binary. What's happening?

倾然丶 夕夏残阳落幕 提交于 2019-11-30 16:43:51
    3

    I'm no Java expert, but it looks like you're doing two different things...

    You are using htmlentities() in PHP, which is converting characters like ÿ to &yulm;, whereas your Java snipped is trying to dump out UTF-8 data.

    Why are you actually expecting valid UTF-8 data after a HMAC? UTF-8 is for representing Unicode characters, not random hashes.

    Using this in PHP:

    $secret = "922ec205d8e4d0ea06079d60a5336fffd9cf0aea";
    $json = $secret;
    $hmac_a = hash_hmac('sha256',$json,$secret);
    $hmac_b = hash_hmac('sha256',$json,$secret,$raw=true); 
    echo $hmac_a . "\n";
    echo $hmac_b . "\n";
    

    I get the following (in a UTF-8 aware terminal):

    ff21a9e468ac49863e5e992324ac8bc92f239a08100b0f329b087be16f5ad382
    �!��h�I�>^�#$���/#2{�oZӂ
    

    This is entirely expected. $hmac_b is effectively binary being interpreted as UTF-8, so it will be full of invalid UTF-8 sequences. Don't expect it to be characters. You will be better looking at it in as ISO-8859-1 output, which isn't multibyte:

    ff21a9e468ac49863e5e992324ac8bc92f239a08100b0f329b087be16f5ad382
    �!��h�I�>^�#$���/#ï¿2ï¿{�oZÓ
    

    (There's also a control character on the end of that output \x82)

    The point is, you're comparing apples with oranges in pear packaging.

      Your Answer

      By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

      标签
      易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
      该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!