简体   繁体   中英

How do I make a scrypt hash using Node.js's crypto library?

function sha512(s){
    var sha = crypto.createHash('sha512');
    sha.update(s);
    return sha.digest('hex');
};
exports.sha512 = sha512;

I'm using this right now, but I want to switch it to scrypt. How can I do that?

You should use node-scrypt .

It has clear API and good documentation.

var scrypt = require("scrypt");
var scryptParameters = scrypt.params(0.1);

var key = new Buffer("this is a key"); //key defaults to buffer in config, so input must be a buffer

//Synchronous example that will output in hexidecimal encoding
scrypt.hash.config.outputEncoding = "hex";
var hash = scrypt.hash(key, scryptParameters); //should be wrapped in try catch, but leaving it out for brevity
console.log("Synchronous result: "+hash);

//Asynchronous example that expects key to be ascii encoded
scrypt.hash.config.keyEncoding = "ascii";
scrypt.hash("ascii encoded key", {N: 1, r:1, p:1}, function(err, result){
    //result will be hex encoded
    //Note how scrypt parameters was passed as a JSON object
    console.log("Asynchronous result: "+result);
});

I'll throw my implementation out there: https://www.npmjs.org/package/scryptsy .

Here's an example:

var scrypt = require('scryptsy') //npm install --save scryptsy

var key = "pleaseletmein" //can be of type 'Buffer'
var salt = "SodiumChloride" //can be of type 'Buffer'
var data = scrypt(key, salt, 16384, 8, 1, 64)
console.log(data.toString('hex')) 
// => 7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887

Documentation here: http://cryptocoinjs.com/modules/crypto/scryptsy/

Simplified barrysteyn/node-scrypt sync example with (de)serialization:

    let scrypt = require('scrypt')
    let scryptParameters = scrypt.paramsSync(0.1)

    function encode(s) {
      return scrypt.kdfSync(s, scryptParameters).toString('Base64')
    }

    function verify(encoded, s) {
      return scrypt.verifyKdfSync(new Buffer(encoded, 'Base64'), s)
    }

    // Example:
    let s = encode('my password')  // c2NyeXB0AAwAAAAI....
    verify(s, 'my password')   //true
    verify(s, 'my pa$$word')   //false

Tested on node 7.0.0, scrypt 6.0.3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM