Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run node crypto module with browserify

I need to use crypto.pbkdf2 on my browser.

I use browserify to create my javascript file. The asynchronous PBKDF2 function freeze my browser entirely when iterations are larger than 1000.

pbkdf2 freeze

RequireBin example

var crypto = require('crypto');
var iterations = 10;
// var iterations = 8192; // uncomment to freeze the browser
crypto.pbkdf2('password', 'salt', iterations, 32, 'sha256', function (error, key) {
    console.log(key.toString('hex'));
});

How to run node crypto module with browserify ?

Edit:

here the code created by browserify to declare pbkdf2

exports.pbkdf2 = pbkdf2
function pbkdf2 (password, salt, iterations, keylen, digest, callback) {
  if (typeof digest === 'function') {
    callback = digest
    digest = undefined
  }

  if (typeof callback !== 'function') {
    throw new Error('No callback provided to pbkdf2')
  }

  var result = pbkdf2Sync(password, salt, iterations, keylen, digest)
  setTimeout(function () {
    callback(undefined, result)
  })
}
like image 733
Guillaume Vincent Avatar asked Jan 28 '26 03:01

Guillaume Vincent


1 Answers

To fix my problem I use the pbkdf2 module from npm: https://github.com/crypto-browserify/pbkdf2

npm install --save pbkdf2

This package implement a browser version and proxy the node version

Depending on the target you want to reach (browser or node) your bundler (browserify or webpack) will load the appropriate version.

var pbkdf2 = require('pbkdf2');
pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function(error, key) {
...
});
like image 160
Guillaume Vincent Avatar answered Jan 29 '26 15:01

Guillaume Vincent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!