2012-02-06 28 views
10

Próbuję portu następujący kod php do javascript na node.js:Szyfrowanie w nodejs

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

Próbowałem następujące:

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

otrzymuję błąd:

TypeError: Object #Object has no method 'HMAC'

Jestem nowy w node.js, wh co robię źle?

Aktualizacja:

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

Odpowiedz

10

Chcesz zamiast użyć funkcji createHmac.

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

Dzięki. Otrzymuję "Należy podać ciąg hashtype jako argument". – Alex

+0

@Alex Przykro nam, dokumenty nie są tak wspaniałe, więc nie mogłem dowiedzieć się, co dokładnie chciał. Mam nadzieję, że doprowadzi cię to we właściwym kierunku. – Tesserex

+1

Crypto.SHA256 powinno być "SHA256". Dzięki! – Alex

0

Metoda nazywa 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

Wziąłem ją stąd: http://stackoverflow.com/questions/7909288/php-javascript-jquery-base64-sha256-encoding – Alex

+0

@Alex Prawdopodobnie jest dla starszej wersji węzła – TimWolla