2013-06-26 59 views
0

這就是我如何在Java產生HMACSHA1簽名在node.js中生成與java相同的hmacSha1簽名?

private static byte[] hmac_sha1(String crypto, byte[] keyBytes, byte[] text) { 
Mac hmac = null; 

    try { 
     hmac = Mac.getInstance(crypto); 
     SecretKeySpec macKey = 
      new SecretKeySpec(keyBytes, "RAW"); 
     hmac.init(macKey); 
     System.out.println("hmac: "+Arrays.toString(keyBytes)); 
     return hmac.doFinal(text); 
} catch (Exception e) { 
    // NOTE. Deviation from reference code. 
    // Reference code prints a stack trace here, which is not what we 
    // want in a production environment, so instead we rethrow. 
    throw new UndeclaredThrowableException(e); 
    } 

} 

我需要幫助生成node.js中相同有人可以幫助我嗎?當人們提到我需要證明我在這裏嘗試的是,我已經寫在node.js中創建一個相同的功能

Ocra.hmacSha1 = function(crypto, keyBytes, text) { 
    var digest, hmac; 
    hmac = nodeCrypto.createHmac(crypto, new Buffer(keyBytes, 'utf8')); 
    console.log(this.bin2String(keyBytes)); 
    digest = hmac.update(new Buffer(text, 'utf8')).digest('hex');   
    return this.hexStr2Bytes(digest); // here i am converting string into bytes array  
}; 

上面的代碼沒有產生預期的效果的代碼。如果我通過這些參數來java代碼 密碼:SHA1 keyBytes:[49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54,55, 56,57,48] 文本:79678265454958727984804583726549455458817848560000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

它們產生不同的結果,並且在node.js中它產生不同的結果。

注:在java中的密碼是HMACSHA1和文本是在陣列不是字符串的形式,你可以在代碼中看到的也是如此。

+1

查看文檔,這很容易:http://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key – gustavohenke

+0

不是最好的問題,沒有顯示已經嘗試過,但它絕對不是「脫離主題」。 –

+0

@owlstead當時我投票決定關閉它,因爲未能「展示對所解決問題的最低限度理解」,包括沒有證明已經嘗試過的東西,因此被***關閉。由於最新的編輯,這現在已經改變。我公平投票,但很早,由於無數的問題,從來沒有改善。 –

回答

0

你在路過的keyBytes在JavaScript版本? new Buffer(keyBytes, 'utf8')幾乎肯定不是你想要的。如果您傳遞的是十六進制編碼的字符串,則需要對其進行十六進制解碼:new Buffer(keyBytes, 'hex')。如果你傳遞一個數組,你必須做new Buffer(keyBytes)

+0

我正通過array [49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54,55,56,57,48]作爲keyBytes。這是OCRA-1的十六進制表示形式:HOTP-SHA1-6:QN08 –

+0

在這種情況下,根據文檔,「新的緩衝區(keyBytes)」應該做到這一點。 – ntoskrnl

+0

如果我嘗試上面提到的解決方案 hmac = nodeCrypto.createHmac(crypto,new Buffer(keyBytes)); console.log(new Buffer(keyBytes)); 我得到空hmac。 –

相關問題