<?php

namespace app\controller;

class HMACMD5
{


    public function HMAC($data)
    {
        $key = strToUtf8(config('hard.SigSecret'));
        $data = strToUtf8($data);

        $b = 64; // byte length for md5
        if (strlen($key) > $b) {
            $key = pack("H32", md5($key));
        }
        $key = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad;
        $k_opad = $key ^ $opad;

        return strtoupper(md5($k_opad . pack("H32", md5($k_ipad . $data))));
    }
}

function strToUtf8($str)
{
    $encode = mb_detect_encoding($str, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
    if ($encode == 'UTF-8') {
        return $str;
    } else {
        return mb_convert_encoding($str, 'UTF-8', $encode);
    }
}
