【问题标题】:Equivalent to hash_hmac in oppenssl_* functions等价于 oppenssl_* 函数中的 hash_hmac
【发布时间】:2018-03-19 16:05:30
【问题描述】:

什么是等价的:

hash_hmac('sha256', 'data', 'key')

如果我使用的是 openssl_*?

openssl_digest 不带 $key 参数。

【问题讨论】:

    标签: php openssl php-openssl


    【解决方案1】:

    此函数使用 openssl_* 扩展来散列数据和密钥:

    代码

    function openssl_hmac($algo, $data, $key, $raw_output = false)
    {
        $algo = strtolower($algo);
        $pack = 'H' . strlen(openssl_digest('test', $algo));
        $size = 64;
        $opad = str_repeat(chr(0x5C), $size);
        $ipad = str_repeat(chr(0x36), $size);
    
        if (strlen($key) > $size) {
            $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
        } else {
            $key = str_pad($key, $size, chr(0x00));
        }
    
        for ($i = 0; $i < strlen($key) - 1; $i++) {
            $opad[$i] = $opad[$i] ^ $key[$i];
            $ipad[$i] = $ipad[$i] ^ $key[$i];
        }
    
        $output = openssl_digest($opad . pack($pack, openssl_digest($ipad . $data, $algo)), $algo);
    
        return ($raw_output) ? pack($pack, $output) : $output;
    }
    

    用法

    echo openssl_hmac('sha256', 'data', 'key', false);
    

    结果:

    5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0
    

    结果与使用hash_hmac函数时相同:

    echo hash_hmac('sha256', 'data', 'key');
    

    结果:

    5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2021-09-25
      • 2011-06-08
      • 2013-08-14
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多