在JavaScript上生成带有UTF-8输入的SHA1 HMAC(不是Node.js)

时间:2017-11-13 20:29:32

标签: javascript utf-8 hmac cryptojs hmacsha1

使用该lib: http://locutus.io/php/misc/pack/ 为hmac缓冲秘密:

var packedSecr = pack('H*', $secret);

比打包时间:

var packedTime = pack('NN', 0, Math.floor((time() + $time_offset) / 30));

这两个字符串都有UTF-8字符,并且与填充的PHP完全一致。 比我需要创建hash_hmac,这里有一个麻烦:

function hash_hmac(str,key){
    var hash = CryptoJS.HmacSHA1(str, key);
    var resInUTF8 = convertWordArrayToUint8Array(hash);
    var string = new TextDecoder('utf-8').decode(resInUTF8);
    console.log(hash.toString());
    /* 5cdc66cb8cf2a08b78f149502e05b9538c7a72a9*/
    console.log(string);
    /* \�fˌ�x�IP.�S�zr� */
    return string;
}

但PHP会使用不同的hmac:

$hmac = hash_hmac('sha1', $packedTime, $bufferedSecret, true);
echo $hmac;
/* v��j��q����V��� */
$hmac = hash_hmac('sha1', $packedTime, $bufferedSecret, false);
echo $hmac;
/* 17761ff6f06ad0db71f0a588fcf002d756c1d1eb */

对于转换WordArray使用的那个迷你库: https://gist.github.com/getify/7325764

如果我只是用“A-z”和“0-9”符号创建hmac,那么一切都很重要。 PHP:

$string = "aBc059";
$secret = "Tcs437";
echo hash_hmac('sha1', $string, $secret, false); 
/* 00012176b13b26f8fdb9f8dfcaf553e9aa0401ac */
echo hash_hmac('sha1', $string, $secret, true);
/* !v�;&�������S�� */

JS:

var string = "aBc059";
var secret = "Tcs437";

hash_hmac(string,secret)

function hash_hmac(str,key){
    var hash = CryptoJS.HmacSHA1(str, key);
    var resInUTF8 = convertWordArrayToUint8Array(hash);
    var string = new TextDecoder('utf-8').decode(resInUTF8);
    console.log(hash.toString());
    /* 00012176b13b26f8fdb9f8dfcaf553e9aa0401ac */
    console.log(string);
    /* !v�;&�������S�� */
    return string;
}

0 个答案:

没有答案