2012-02-06 98 views
10

我試圖端口下面的PHP代碼的JavaScript上的Node.js:在加密的NodeJS

$mac = hash_hmac('SHA256', 'string', 'secret', true);
$coded = base64_encode($mac);

我已經試過如下:

var Crypto = require('crypto');
var code = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA256, 'string', 'secret', { asBytes: true }));

我得到錯誤:

TypeError: Object #Object has no method 'HMAC'

我是新來的node.js,wh我在做錯嗎?

更新:

var code = Crypto.createHmac('SHA256', secret_key).update(to_encode).digest('base64');

回答

10

您想使用createHmac函數。

Crypto.createHmac("SHA256", 'secret').update('string').digest('base64') 
+1

致謝。我得到「必須給hashtype字符串作爲參數」。 – Alex 2012-02-06 19:08:56

+0

@亞歷克斯對不起,文檔不是很好,所以我無法弄清楚它到底需要什麼。希望這能讓你朝着正確的方向前進。 – Tesserex 2012-02-06 19:11:36

+1

Crypto.SHA256應該是'SHA256'。謝謝! – Alex 2012-02-06 19:21:15

0

的方法被稱爲createHmac

> Crypto = require('crypto'); 
{ Credentials: [Function: Credentials], 
    createCredentials: [Function], 
    Hash: [Function], 
    createHash: [Function], 
    Hmac: [Function], 
    createHmac: [Function], 
    Cipher: [Function], 
    createCipher: [Function], 
    createCipheriv: [Function], 
    Decipher: [Function], 
    createDecipher: [Function], 
    createDecipheriv: [Function], 
    Sign: [Function], 
    createSign: [Function], 
    Verify: [Function], 
    createVerify: [Function], 
    DiffieHellman: [Function], 
    createDiffieHellman: [Function], 
    pbkdf2: [Function], 
    randomBytes: [Function], 
    pseudoRandomBytes: [Function], 
    rng: [Function], 
    prng: [Function] } 
+0

我把它從這裏:http://stackoverflow.com/questions/7909288/php-javascript-jquery-base64-sha256-encoding – Alex 2012-02-06 19:06:09

+0

@Alex這可能是一箇舊版本節點 – TimWolla 2012-02-06 19:07:02