如何 运行 使用 browserify 节点加密模块

How to run node crypto module with browserify

我需要在我的浏览器上使用 crypto.pbkdf2

我使用 browserify 创建我的 javascript 文件。当迭代次数大于 1000 时,异步 PBKDF2 函数会完全冻结我的浏览器。

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'));
});

如何使用 browserify 运行 节点加密模块?

编辑:

这里是 browserify 创建的声明 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)
  })
}

为了解决我的问题,我使用了 npm 中的 pbkdf2 模块:https://github.com/crypto-browserify/pbkdf2

npm install --save pbkdf2

这个包实现了一个browser version and proxy the node version

根据您想要达到的目标(浏览器或节点),您的捆绑器(browserify 或 webpack)将加载适当的版本。

var pbkdf2 = require('pbkdf2');
pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function(error, key) {
...
});