我一直在尝试用Javascript编码HMAC算法,但是到了某种程度,我无法弄清楚出了什么问题。我到了创建内部哈希的地步,但是使用SHA1时,返回的值与FIPS 198文档示例A1中指定的值不匹配(步骤6)。

/*
function hmac (key, message)
    if (length(key) > blocksize) then
        key = hash(key) // keys longer than blocksize are shortened
    end if
    if (length(key) < blocksize) then
        key = key ∥ [0x00 * (blocksize - length(key))] // keys shorter than blocksize are zero-padded ('∥' is concatenation)
    end if

    o_key_pad = [0x5c * blocksize] ⊕ key // Where blocksize is that of the underlying hash function
    i_key_pad = [0x36 * blocksize] ⊕ key // Where ⊕ is exclusive or (XOR)

    return hash(o_key_pad ∥ hash(i_key_pad ∥ message)) // Where '∥' is concatenation
end function
*/

/*
STEPS
Step 1
Table 1: The HMAC Algorithm
STEP-BY-STEP DESCRIPTION
If the length of K = B: set K0 = K. Go to step 4.
Step 2 If the length of K > B: hash K to obtain an L byte string, then append (B-L)
      zeros to create a B-byte string K0 (i.e., K0 = H(K) || 00...00). Go to step 4.
Step 3 If the length of K < B: append zeros to the end of K to create a B-byte string K0
      (e.g., if K is 20 bytes in length and B = 64, then K will be appended with 44
     zero bytes 0x00).
Step 4 Exclusive-Or K0 with ipad to produce a B-byte string: K0  ̄ ipad.
Step 5 Append the stream of data 'text' to the string resulting from step 4:
      (K0  ̄ ipad) || text.
Step 6 Apply H to the stream generated in step 5: H((K0  ̄ ipad) || text).
Step 7 Exclusive-Or K0 with opad: K0  ̄ opad.
Step 8 Append the result from step 6 to step 7:
      (K0  ̄ opad) || H((K0  ̄ ipad) || text).
Step 9 Apply H to the result from step 8:
      H((K0  ̄ opad )|| H((K0  ̄ ipad) || text)).
Step 10 Select the leftmost t bytes of the result of step 9 as the MAC.
*/

/*
FIPS PUB 198, The Keyed-Hash Message Authentication Code
http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf

A.1
SHA-1 with 64-Byte Key
*/


//Check sha1 hashers
if ($u.sha1("test") !==  CryptoJS.SHA1("test").toString()) {
    throw new Error("hasher output mismatch");
}

var key = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f";
var k0 = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f";
var k0ipad = "36373435323330313e3f3c3d3a3b383926272425222320212e2f2c2d2a2b282916171415121310111e1f1c1d1a1b181906070405020300010e0f0c0d0a0b0809";
var k0opad = "5c5d5e5f58595a5b54555657505152534c4d4e4f48494a4b44454647404142437c7d7e7f78797a7b74757677707172736c6d6e6f68696a6b6465666760616263";
var ipt = "36373435323330313e3f3c3d3a3b383926272425222320212e2f2c2d2a2b282916171415121310111e1f1c1d1a1b181906070405020300010e0f0c0d0a0b080953616d706c65202331";
var h1 = "bcc2c68cabbbf1c3f5b05d8e7e73a4d27b7e1b20";
var message = "Sample #1";
var result = "";

function hmac(key, message) {
    key = key.replace(/\s*/g, "");

    var swap = false, // for swap endianess
        length = key.length,
        blockSize = 64 * 2, // for sha 1 = 64, as hex * 2
        ml = message.length,
        i = 0,
        o_key_pad = "",
        i_key_pad = "",
        ikeypmessage = "",
        hipt,
        temp1,
        temp2;

    // 1. If the length of K = B: set K0 = K. Go to step 4.
    if (length !== blockSize) {
        // 2. If the length of K > B: hash K to obtain an L byte string, then append (B-L)
        //    zeros to create a B-byte string K0 (i.e., K0 = H(K) || 00...00). Go to step 4.
        //    Actually in code, goto step3 ri append zeros
        if (length > blockSize) {
            key = $u.sha1(key);
        }

        // 3. If the length of K < B: append zeros to the end of K to create a B-byte string K0
        //   (e.g., if K is 20 bytes in length and B = 64, then K will be appended with 44
        //   zero bytes 0x00).
        while (key.length < blockSize) {
            key += "0";
            i += 1;
        }
    }

    // check against the FIP198 example
    if (key !== k0) {
        console.log(key, k0);
        throw new Error("key and k0 mismatch");
    }

    // 4. Exclusive-Or K0 with ipad to produce a B-byte string: K0  ̄ ipad.
    // 7. Exclusive-Or K0 with opad: K0  ̄ opad.
    i = 0;
    while (i < blockSize) {
        temp1 = parseInt(key.slice(i, i + 2), 16);

        temp2 = (temp1 ^ 0x36).toString(16);
        i_key_pad += temp2.length > 1 ? temp2 : "0" + temp2;

        temp2 = (temp1 ^ 0x5c).toString(16);
        o_key_pad += temp2.length > 1 ? temp2 : "0" + temp2;

        i += 2;
    }

    if (i_key_pad !== k0ipad) {
        console.log(i_key_pad, k0ipad);
        throw new Error("i_key_pad and k0ipad mismatch");
    }

    if (o_key_pad !== k0opad) {
        console.log(o_key_pad, k0opad);
        throw new Error("o_key_pad and k0opad mismatch");
    }

    // 5. Append the stream of data 'text' to the string resulting from step 4:
    //    (K0  ̄ ipad) || text.
    i = 0;
    temp1 = "";
    while (i < ml) {
        temp1 += message.charCodeAt(i).toString(16);
        i += 1;
    }

    ikeypmessage = i_key_pad + temp1;
    if (ikeypmessage !== ipt) {
        console.log(i_key_pad + temp1, ipt);
        throw new Error("i_key_pad + temp1 and ipt mismatch");
    }

    // convert hex string to ucs2 string
    ml = ikeypmessage.length;
    temp1 = [];
    i = 0;
    while (i < ml) {
        // for changinging endianess
        if (swap) {
            temp1[i >> 1] = ikeypmessage.charAt(i + 1) + ikeypmessage.charAt(i);
        } else {
            temp1[i >> 1] = ikeypmessage.slice(i, i + 2);
        }

        i += 2;
    }

    // for changinging endianess
    if (swap) {
        temp1.reverse();
    }

    // convert byte to ucs2 string
    ml = temp1.length;
    temp2 = "";
    i = 0;
    while (i < ml) {
        temp2 += String.fromCharCode(parseInt(temp1[i], 16));
        i += 1;
    }

    ikeypmessage = temp2;

    // This is the point where it goes bottom up
    // 6. Apply H to the stream generated in step 5: H((K0  ̄ ipad) || text).
    console.log(ikeypmessage);
    hipt = $u.sha1(ikeypmessage);
    if (hipt !== h1) {
        console.log(hipt, h1);
        throw new Error("hipt and h1 mismatch");
    }
}

console.log(hmac(key, message));


这段代码可用于jsfiddle,如果有人可以向我指出我要去哪里的错误,将不胜感激。

我尝试将十六进制字符串转换为ucs2字符串并更改字节序,但都给了我不同的结果,但没有一个与示例匹配。

最佳答案

您的问题是您的测试向量错误。您的密码:


  000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f


并且您的消息“ Sample #1”来自示例A.1:在FIPS 198a中具有64字节密钥的SHA-1,而您的预期输出是:


  74766e5f6913e8cb6f7f108a11298b15010c353a


来自示例A.2:具有20字节密钥的SHA-1。示例A.1的正确的第一阶段哈希输出为:


  bcc2c68cabbbf1c3f5b05d8e7e73a4d27b7e1b20


另请注意,NIST已发布了更新的,更全面的test vectors for HMAC-SHA-1 and HMAC-SHA-2集。



好的,我发现了第二个问题。偷看$u.sha1()的源代码,该函数开始于:

var msg = internal.utf8EncodeToCharCodeArray(str)


也就是说,它期望其输入为Unicode字符串,并在对哈希进行哈希处理之前使用UTF-8编码将其转换为八位字节字符串。特别是,这意味着代码点高于127的字符将转换为多个字节。

不幸的是,HMAC构造仅对原始八位位组字符串起作用,而不对Unicode字符串起作用。更糟糕的是,似乎没有任何方法可以将原始八位位组字符串提供给$u.sha1()。 UTF-8转换是自动完成的,您需要在HMAC中哈希的八位位组字符串几乎不可能成为任何Unicode字符串的有效UTF-8编码。

但是,如果改用CryptoJS,则可以将八位字节字符串(或十六进制表示形式)转换为WordArray并将其直接传递给CryptoJS.SHA1()

var words = CryptoJS.enc.Latin1.parse(ikeypmessage);
hipt = CryptoJS.SHA1(words).toString();


当然,如果您使用的是CryptoJS,首先将密钥和消息转换为WordArray,然后直接与它们一起使用将更加容易和有效。或者,您可以只使用内置的CryptoJS.HmacSHA1()方法。

关于javascript - 坚持在JavaScript中实现HMAC,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16041982/

10-12 13:10