开发者

How to encrypt a string using node.js?

开发者 https://www.devze.com 2023-04-07 05:13 出处:网络
I need a node.js equivalent of the following Ruby code: require \'openssl\' digest = OpenSSL::Digest::Digest.new(\'sha1\')

I need a node.js equivalent of the following Ruby code:

    require 'openssl'
    digest = OpenSSL::Digest::Digest.new('sha1')
    signature = OpenSSL::HMAC.hexdigest(digest, 'auth secret', 'some string')

I tried the following in node.js, bu开发者_StackOverflowt the Ruby signature is different from node's

    var crypto, signature;
    crypto = require('crypto');
    signature = crypto.createHash("sha1").update('auth secret').update('some string').digest("hex");


You're on the right track. You need to use the crypto#createHmac method instead of createHash, and pass it your secret (key) when creating it. This will give you what you're looking for:

var crypto = require('crypto')
  , hmac
  , signature;

hmac = crypto.createHmac("sha1", 'auth secret');
hmac.update('some string');

signature = hmac.digest("hex");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号