Giter Site home page Giter Site logo

pbkdf2's Introduction

browserify

require('modules') in the browser

Use a node-style require() to organize your browser code and load modules installed by npm.

browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <script> tag.

build status

browserify!

getting started

If you're new to browserify, check out the browserify handbook and the resources on browserify.org.

example

Whip up a file, main.js with some require()s in it. You can use relative paths like './foo.js' and '../lib/bar.js' or module paths like 'gamma' that will search node_modules/ using node's module lookup algorithm.

var foo = require('./foo.js');
var bar = require('../lib/bar.js');
var gamma = require('gamma');

var elem = document.getElementById('result');
var x = foo(100) + bar('baz');
elem.textContent = gamma(x);

Export functionality by assigning onto module.exports or exports:

module.exports = function (n) { return n * 111 }

Now just use the browserify command to build a bundle starting at main.js:

$ browserify main.js > bundle.js

All of the modules that main.js needs are included in the bundle.js from a recursive walk of the require() graph using required.

To use this bundle, just toss a <script src="bundle.js"></script> into your html!

install

With npm do:

npm install browserify

usage

Usage: browserify [entry files] {OPTIONS}

Standard Options:

    --outfile, -o  Write the browserify bundle to this file.
                   If unspecified, browserify prints to stdout.

    --require, -r  A module name or file to bundle.require()
                   Optionally use a colon separator to set the target.

      --entry, -e  An entry point of your app

     --ignore, -i  Replace a file with an empty stub. Files can be globs.

    --exclude, -u  Omit a file from the output bundle. Files can be globs.

   --external, -x  Reference a file from another bundle. Files can be globs.

  --transform, -t  Use a transform module on top-level files.

    --command, -c  Use a transform command on top-level files.

  --standalone -s  Generate a UMD bundle for the supplied export name.
                   This bundle works with other module systems and sets the name
                   given as a window global if no module system is found.

       --debug -d  Enable source maps that allow you to debug your files
                   separately.

       --help, -h  Show this message

For advanced options, type `browserify --help advanced`.

Specify a parameter.
Advanced Options:

  --insert-globals, --ig, --fast    [default: false]

    Skip detection and always insert definitions for process, global,
    __filename, and __dirname.

    benefit: faster builds
    cost: extra bytes

  --insert-global-vars, --igv

    Comma-separated list of global variables to detect and define.
    Default: __filename,__dirname,process,Buffer,global

  --detect-globals, --dg            [default: true]

    Detect the presence of process, global, __filename, and __dirname and define
    these values when present.

    benefit: npm modules more likely to work
    cost: slower builds

  --ignore-missing, --im            [default: false]

    Ignore `require()` statements that don't resolve to anything.

  --noparse=FILE

    Don't parse FILE at all. This will make bundling much, much faster for giant
    libs like jquery or threejs.

  --no-builtins

    Turn off builtins. This is handy when you want to run a bundle in node which
    provides the core builtins.

  --no-commondir

    Turn off setting a commondir. This is useful if you want to preserve the
    original paths that a bundle was generated with.

  --no-bundle-external

    Turn off bundling of all external modules. This is useful if you only want
    to bundle your local files.

  --bare

    Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars
    to just "__filename,__dirname". This is handy if you want to run bundles in
    node.

  --no-browser-field, --no-bf

    Turn off package.json browser field resolution. This is also handy if you
    need to run a bundle in node.

  --transform-key

    Instead of the default package.json#browserify#transform field to list
    all transforms to apply when running browserify, a custom field, like, e.g.
    package.json#browserify#production or package.json#browserify#staging
    can be used, by for example running:
    * `browserify index.js --transform-key=production > bundle.js`
    * `browserify index.js --transform-key=staging > bundle.js`

  --node

    Alias for --bare and --no-browser-field.

  --full-paths

    Turn off converting module ids into numerical indexes. This is useful for
    preserving the original paths that a bundle was generated with.

  --deps

    Instead of standard bundle output, print the dependency array generated by
    module-deps.

  --no-dedupe

    Turn off deduping.

  --list

    Print each file in the dependency graph. Useful for makefiles.

  --extension=EXTENSION

    Consider files with specified EXTENSION as modules, this option can used
    multiple times.

  --global-transform=MODULE, -g MODULE

    Use a transform module on all files after any ordinary transforms have run.

  --ignore-transform=MODULE, -it MODULE

    Do not run certain transformations, even if specified elsewhere.

  --plugin=MODULE, -p MODULE

    Register MODULE as a plugin.

Passing arguments to transforms and plugins:

  For -t, -g, and -p, you may use subarg syntax to pass options to the
  transforms or plugin function as the second parameter. For example:

    -t [ foo -x 3 --beep ]

  will call the `foo` transform for each applicable file by calling:

    foo(file, { x: 3, beep: true })

compatibility

Many npm modules that don't do IO will just work after being browserified. Others take more work.

Many node built-in modules have been wrapped to work in the browser, but only when you explicitly require() or use their functionality.

When you require() any of these modules, you will get a browser-specific shim:

Additionally, if you use any of these variables, they will be defined in the bundled output in a browser-appropriate way:

  • process
  • Buffer
  • global - top-level scope object (window)
  • __filename - file path of the currently executing file
  • __dirname - directory path of the currently executing file

more examples

external requires

You can just as easily create a bundle that will export a require() function so you can require() modules from another script tag. Here we'll create a bundle.js with the through and duplexer modules.

$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js

Then in your page you can do:

<script src="bundle.js"></script>
<script>
  var through = require('through');
  var duplexer = require('duplexer');
  var myModule = require('my-module');
  /* ... */
</script>

external source maps

If you prefer the source maps be saved to a separate .js.map source map file, you may use exorcist in order to achieve that. It's as simple as:

$ browserify main.js --debug | exorcist bundle.js.map > bundle.js

Learn about additional options here.

multiple bundles

If browserify finds a required function already defined in the page scope, it will fall back to that function if it didn't find any matches in its own set of bundled modules.

In this way, you can use browserify to split up bundles among multiple pages to get the benefit of caching for shared, infrequently-changing modules, while still being able to use require(). Just use a combination of --external and --require to factor out common dependencies.

For example, if a website with 2 pages, beep.js:

var robot = require('./robot.js');
console.log(robot('beep'));

and boop.js:

var robot = require('./robot.js');
console.log(robot('boop'));

both depend on robot.js:

module.exports = function (s) { return s.toUpperCase() + '!' };
$ browserify -r ./robot.js > static/common.js
$ browserify -x ./robot.js beep.js > static/beep.js
$ browserify -x ./robot.js boop.js > static/boop.js

Then on the beep page you can have:

<script src="common.js"></script>
<script src="beep.js"></script>

while the boop page can have:

<script src="common.js"></script>
<script src="boop.js"></script>

This approach using -r and -x works fine for a small number of split assets, but there are plugins for automatically factoring out components which are described in the partitioning section of the browserify handbook.

api example

You can use the API directly too:

var browserify = require('browserify');
var b = browserify();
b.add('./browser/main.js');
b.bundle().pipe(process.stdout);

methods

var browserify = require('browserify')

browserify([files] [, opts])

Returns a new browserify instance.

files
String, file object, or array of those types (they may be mixed) specifying entry file(s).
opts
Object.

files and opts are both optional, but must be in the order shown if both are passed.

Entry files may be passed in files and / or opts.entries.

External requires may be specified in opts.require, accepting the same formats that the files argument does.

If an entry file is a stream, its contents will be used. You should pass opts.basedir when using streaming files so that relative requires can be resolved.

opts.entries has the same definition as files.

opts.noParse is an array which will skip all require() and global parsing for each file in the array. Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse.

opts.transform is an array of transform functions or modules names which will transform the source code before the parsing.

opts.ignoreTransform is an array of transformations that will not be run, even if specified elsewhere.

opts.plugin is an array of plugin functions or module names to use. See the plugins section below for details.

opts.extensions is an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. By default browserify considers only .js and .json files in such cases.

opts.basedir is the directory that browserify starts bundling from for filenames that start with ..

opts.paths is an array of directories that browserify searches when looking for modules which are not referenced using relative path. Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling browserify command.

opts.commondir sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module.

opts.fullPaths disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with.

opts.builtins sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution.

opts.bundleExternal boolean option to set if external modules should be bundled. Defaults to true.

When opts.browserField is false, the package.json browser field will be ignored. When opts.browserField is set to a string, then a custom field name can be used instead of the default "browser" field.

When opts.insertGlobals is true, always insert process, global, __filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false.

When opts.detectGlobals is true, scan all files for process, global, __filename, and __dirname, defining as necessary. With this option npm modules are more likely to work but bundling takes longer. Default true.

When opts.ignoreMissing is true, ignore require() statements that don't resolve to anything.

When opts.debug is true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser.

When opts.standalone is a non-empty string, a standalone module is created with that name and a umd wrapper. You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'. The global export will be sanitized and camel cased.

Note that in standalone mode the require() calls from the original source will still be around, which may trip up AMD loaders scanning for require() calls. You can remove these calls with derequire:

$ npm install derequire
$ browserify main.js --standalone Foo | derequire > bundle.js

opts.insertGlobalVars will be passed to insert-module-globals as the opts.vars parameter.

opts.externalRequireName defaults to 'require' in expose mode but you can use another name.

opts.bare creates a bundle that does not include Node builtins, and does not replace global Node variables except for __dirname and __filename.

opts.node creates a bundle that runs in Node and does not use the browser versions of dependencies. Same as passing { bare: true, browserField: false }.

Note that if files do not contain javascript source code then you also need to specify a corresponding transform for them.

All other options are forwarded along to module-deps and browser-pack directly.

b.add(file, opts)

Add an entry file from file that will be executed when the bundle loads.

If file is an array, each item in file will be added as an entry file.

b.require(file, opts)

Make file available from outside the bundle with require(file).

The file param is anything that can be resolved by require.resolve(), including files from node_modules. Like with require.resolve(), you must prefix file with ./ to require a local file (not in node_modules).

file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.

If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.

Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')

b.bundle(cb)

Bundle the files and their dependencies into a single javascript file.

Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results.

b.external(file)

Prevent file from being loaded into the current bundle, instead referencing from another bundle.

If file is an array, each item in file will be externalized.

If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled.

b.ignore(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be ignored.

Instead you will get a file with module.exports = {}.

b.exclude(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be excluded.

If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.

b.transform(tr, opts={})

Transform source code before parsing it for require() calls with the transform function or module name tr.

If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source.

If tr is a string, it should be a module name or file path of a transform module with a signature of:

var through = require('through');
module.exports = function (file) { return through() };

You don't need to necessarily use the through module. Browserify is compatible with the newer, more verbose Transform streams built into Node v0.10.

Here's how you might compile coffee script on the fly using .transform():

var coffee = require('coffee-script');
var through = require('through');

b.transform(function (file) {
    var data = '';
    return through(write, end);

    function write (buf) { data += buf }
    function end () {
        this.queue(coffee.compile(data));
        this.queue(null);
    }
});

Note that on the command-line with the -c flag you can just do:

$ browserify -c 'coffee -sc' main.coffee > bundle.js

Or better still, use the coffeeify module:

$ npm install coffeeify
$ browserify -t coffeeify main.coffee > bundle.js

If opts.global is true, the transform will operate on ALL files, despite whether they exist up a level in a node_modules/ directory. Use global transforms cautiously and sparingly, since most of the time an ordinary transform will suffice. You can also not configure global transforms in a package.json like you can with ordinary transforms.

Global transforms always run after any ordinary transforms have run.

Transforms may obtain options from the command-line with subarg syntax:

$ browserify -t [ foo --bar=555 ] main.js

or from the api:

b.transform('foo', { bar: 555 })

In both cases, these options are provided as the second argument to the transform function:

module.exports = function (file, opts) { /* opts.bar === 555 */ }

Options sent to the browserify constructor are also provided under opts._flags. These browserify options are sometimes required if your transform needs to do something different when browserify is run in debug mode, for example.

b.plugin(plugin, opts)

Register a plugin with opts. Plugins can be a string module name or a function the same as transforms.

plugin(b, opts) is called with the browserify instance b.

For more information, consult the plugins section below.

b.pipeline

There is an internal labeled-stream-splicer pipeline with these labels:

  • 'record' - save inputs to play back later on subsequent bundle() calls
  • 'deps' - module-deps
  • 'json' - adds module.exports= to the beginning of json files
  • 'unbom' - remove byte-order markers
  • 'unshebang' - remove #! labels on the first line
  • 'syntax' - check for syntax errors
  • 'sort' - sort the dependencies for deterministic bundles
  • 'dedupe' - remove duplicate source contents
  • 'label' - apply integer labels to files
  • 'emit-deps' - emit 'dep' event
  • 'debug' - apply source maps
  • 'pack' - browser-pack
  • 'wrap' - apply final wrapping, require= and a newline and semicolon

You can call b.pipeline.get() with a label name to get a handle on a stream pipeline that you can push(), unshift(), or splice() to insert your own transform streams.

b.reset(opts)

Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times.

This function triggers a 'reset' event.

package.json

browserify uses the package.json in its module resolution algorithm, just like node. If there is a "main" field, browserify will start resolving the package at that point. If there is no "main" field, browserify will look for an "index.js" file in the module root directory. Here are some more sophisticated things you can do in the package.json:

browser field

There is a special "browser" field you can set in your package.json on a per-module basis to override file resolution for browser-specific versions of files.

For example, if you want to have a browser-specific module entry point for your "main" field you can just set the "browser" field to a string:

"browser": "./browser.js"

or you can have overrides on a per-file basis:

"browser": {
  "fs": "level-fs",
  "./lib/ops.js": "./browser/opts.js"
}

Note that the browser field only applies to files in the local module, and like transforms, it doesn't apply into node_modules directories.

browserify.transform

You can specify source transforms in the package.json in the browserify.transform field. There is more information about how source transforms work in package.json on the module-deps readme.

For example, if your module requires brfs, you can add

"browserify": { "transform": [ "brfs" ] }

to your package.json. Now when somebody require()s your module, brfs will automatically be applied to the files in your module without explicit intervention by the person using your module. Make sure to add transforms to your package.json dependencies field.

events

b.on('file', function (file, id, parent) {})

b.pipeline.on('file', function (file, id, parent) {})

When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve.

You could use the file event to implement a file watcher to regenerate bundles when files change.

b.on('package', function (pkg) {})

b.pipeline.on('package', function (pkg) {})

When a package file is read, this event fires with the contents. The package directory is available at pkg.__dirname.

b.on('bundle', function (bundle) {})

When .bundle() is called, this event fires with the bundle output stream.

b.on('reset', function () {})

When the .reset() method is called or implicitly called by another call to .bundle(), this event fires.

b.on('transform', function (tr, file) {})

b.pipeline.on('transform', function (tr, file) {})

When a transform is applied to a file, the 'transform' event fires on the bundle stream with the transform stream tr and the file that the transform is being applied to.

plugins

For some more advanced use-cases, a transform is not sufficiently extensible. Plugins are modules that take the bundle instance as their first parameter and an option hash as their second.

Plugins can be used to do perform some fancy features that transforms can't do. For example, factor-bundle is a plugin that can factor out common dependencies from multiple entry-points into a common bundle. Use plugins with -p and pass options to plugins with subarg syntax:

browserify x.js y.js -p [ factor-bundle -o bundle/x.js -o bundle/y.js ] \
  > bundle/common.js

For a list of plugins, consult the browserify-plugin tag on npm.

list of source transforms

There is a wiki page that lists the known browserify transforms.

If you write a transform, make sure to add your transform to that wiki page and add a package.json keyword of browserify-transform so that people can browse for all the browserify transforms on npmjs.org.

third-party tools

There is a wiki page that lists the known browserify tools.

If you write a tool, make sure to add it to that wiki page and add a package.json keyword of browserify-tool so that people can browse for all the browserify tools on npmjs.org.

changelog

Releases are documented in changelog.markdown and on the browserify twitter feed.

license

MIT

browserify!

pbkdf2's People

Contributors

bre7 avatar calvinmetcalf avatar chaeron avatar dcousens avatar dominykas avatar fanatid avatar timonegk avatar tniessen avatar webmaster128 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pbkdf2's Issues

deoptimization

I've been benchmarking and the new version is consistently slower then the old version, so need to look into it

Ripemd160 throws when used

/lib/sync-browser.js:51
  h.copy(this.opad, this.blocksize)
    ^

TypeError: Cannot read property 'copy' of undefined

I don't think this path is under test at all.

In 9.0.0, sha1 is not defaulted

The existing API assumes that it does default to sha1, and hence throws:

TypeError [ERR_INVALID_ARG_TYPE]: The "digest" argument must be one of type string or null

In tests

Issue with microtime on windows after 3.0.11

After update to 3.0.11 in package.json have appeared microtime. It is break npm install on windows with error

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.targets(36,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK vers ion in the project property pages or by right-clicking the solution and selecting "Retarget solution". [c:\Work\Afisha8 \Afisha17BE\node_modules\microtime\build\microtime.vcxproj]

Is it possible to do this package dev depency? Like @pirelenito said #63 ?

Browser truncation results different

node 6

mnemonicメートルガバヴァぱばぐゞちぢ十人十色

bW5lbW9uaWPjg6Hjg7zjg4jjg6vjgqvjgpnjg4/jgpnjgqbjgpnjgqHjga/jgprjga/jgpnjgY/jgpnjgp3jgpnjgaHjgaHjgpnljYHkurrljYHoibI=

browser

mnemonicメートルガ�゙ヴァ�゚�゙�゙�゙��゙�人�色 

bW5lbW9uaWPDo8aSwqHDo8aSwrzDo8aSy4bDo8aSwqvDo+KAmsKrw6PigJrihKLDo8aSwo/Do+KAmuKEosOj4oCawqbDo+KAmuKEosOj4oCawqHDo8KBwq/Do+KAmsWhw6PCgcKvw6PigJrihKLDo8KBwo/Do+KAmuKEosOj4oCawp3Do+KAmuKEosOjwoHCocOjwoHCocOj4oCa4oSiw6XCjcKBw6TCusK6w6XCjcKBw6jigLDCsg==

Issue in pbkdf2/lib/default-encoding.js

In last release there's an issue in pbkdf2/lib/default-encoding.js. In line 5

else if (global.process && global.process.version) { //code }

instead of global.process.version, exactly version is typed like global."v18.6.0". This causes problem on npm install command. Kindly fix this issue. Thank you!

hash generate with v3.0.4 doesn't be the same with v3.0.5 because node 0.10

In 3.0.4 pbkdf2 generate a hash correctly with digest parameter sha256.
With 3.0.5 pbkdf2 generate a hash silently ignoring 'sha256' and use sha1 instead.

  • Tape tests doesn't pass with node 0.10.
  • Pbkdf2 doesn't support node 0.10 anymore ?
  • If this is the case can we add { "engines" : { "node" : ">=0.12" } } in package.json
  • This is an important change not being represented in version number :-( ~3.0.4 in my package.json

Node pbkdf2 defaults to `ascii` encoding?

Is this intentional or a bug? Its burning me as the browserify code [now] defaults to utf8 for strings because it encodes it as a Buffer straight away. Whereas the node seems to be defaulting string inputs to ascii encoding.

This therefore gives completely different results to what is expected... sigh.

See ea1ddaf for tests.

@calvinmetcalf do you know if this is meant to be the case? Node bug?

3.0.6 upgrade completely broke some old code..

3.0.6 got auto-updated via the following path:

│ ├─┬ [email protected]
│ │ ├─┬ [email protected]
│ │ │ ├── [email protected]

https://github.com/crypto-browserify/pbkdf2/blob/master/browser.js#L3 this line caused the problem with process.version undefined. (cannot access split of undefined)

Just FYI, had to handle an emergency operations was not immediately evident what's going on as it's pretty deep in dependencies..

How to improve the performance

I'm using a library called bip39 that uses this function:

function mnemonicToSeed (mnemonic, password) {
  var mnemonicBuffer = Buffer.from(unorm.nfkd(mnemonic), 'utf8')
  var saltBuffer = Buffer.from(salt(unorm.nfkd(password)), 'utf8')

  return pbkdf2(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512')
}

(See source code)

However, pbkdf2 is taking about 1500 ms to finish on my computer and browser. (and I have a new and fast laptop)

Is there any way this function could be improve to increase the performance?

The biggest problem is that it blocks the entire JS thread and thus freezes my web-app's UI completely. The user can't even scroll.

I was also wondering if it's maybe possible to split the work between multiple event loop cycles?
Or have an effect that's similar to "time slicing" as explained by Evan You of VueJS here in this presentation: https://youtu.be/8Hgt9HYaCDA?t=1995

But I'm not an expert on the subject so pardon me if I'm saying things that don't make sense. 😀

Related thread: bitcoinjs/bip39#99

Ability to use browser's native implementation

With the Web Cryptography API becoming a W3C Recommendation as of 26th of January of 2017, we could safely implement pbkdf2 natively for some browsers (i.e. Chrome and Firefox). I know we are browserifying crypto here, but maybe we could fallback to the native methods if implemented.

Would you be interested in having such a fallback in this repo? It's pretty popular and other people seem to use it a lot in the browser. Here's how I implemented it for github.com/jjperezaguinaga/deniable.website.

const pbkdf2Native = (password, salt, iterations, digest, mode, keylen) =>
    (window.crypto.subtle||window.crypto.webkitSubtle).importKey('raw', password, {name: 'PBKDF2'}, false, ['deriveKey'])
        .then(baseKey => (window.crypto.subtle||window.crypto.webkitSubtle).deriveKey({name: 'PBKDF2', salt, iterations, hash: digest, baseKey, {'name': mode, 'length': keylen*8}, true, ['encrypt', 'decrypt']))
        .then(key => (window.crypto.subtle||window.crypto.webkitSubtle).exportKey('raw', key))

I can make a PR to detect window and leverage on it based on the options given, since it seems the API has some limitations (e.g. keylen for mode has to be either 128 or 256 bits, see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey). You can see how lesspass is using it alongside this repository for a reference of what we could do.

👋 @jprichardson!

Tests failing for Node 6

Looks to be an issue with Buffers and utf8/binary again.
Did something change in Node 6 that is going to make us incompatible?

@feross any ideas?

process.version in browser.js

On line 3 of browser.js:
parseInt(process.version.split('.')[0].slice(1), 10)
the process global variable doesn't exist in browsers, so this throws an error and breaks at this point.

Different result between nodejs and php

I have diferent result processing same data in php. It should be the same.

Php code:
var_dump(bin2hex($key)); var_dump(bin2hex($result)); $d_key = hash_pbkdf2('sha1',$key,$result,64000,32,true); var_dump(bin2hex($d_key));
Nodejs code
` var pbkdf2 = require('pbkdf2');

        console.log(new Buffer(key));

        console.log(new Buffer(salt));

        var result = pbkdf2.pbkdf2Sync(new Buffer(key),new Buffer(salt),64000,32,'sha256');

        console.log(result);`

Php result
string(64) "3132333435363738393031323334353637383930313233343536373839303132" string(64) "6162636465663132333461626364656631323334616263646566313233343132" string(64) "bbcc7e635af5bdb6d5532c92524e776779ffb6d979848d6416e0a05089998cc4"
Nodejs result
`<Buffer 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32>

<Buffer 61 62 63 64 65 66 31 32 33 34 61 62 63 64 65 66 31 32 33 34 61 62 63 64 65 66 31 32 33 34 31 32>

<Buffer ea 5b 2b 27 d2 4a 16 ef b8 35 e0 ae be 82 ec a1 fe 20 37 8d f1 09 bc a6 2e 5d 8f 43 cc b2 50 01>
`

My fault. Sorry, sha1

Issues after 3.0.11 update

I have the following section of code in my program, which was working before the update:

var crypto = require('crypto') /* istanbul ignore next */ if (crypto.pbkdf2Sync.toString().indexOf('keylen, digest') === -1) { throw new Error('Unsupported crypto version') }

After updating 3.0.11, pbkdf2Sync is undefined and so my code is failing. Any information on why this may be happening would be greatly appreciated.

Allow using this library with Uint8Array

Would it be possible to except not only Buffer and string for password/salt but also Uint8Array?

All my crypto code uses Uint8Array for both browser and nodejs and it would be cool to be able to use the JS standard type directly.

Browser field no longer points to browser.js

Which results in the following error when we try to run our tests:

  TypeError: undefined is not an object (evaluating 'crypto.pbkdf2Sync.toString')
  at webpack:///~/pbkdf2/index.js:3:0 <- tests.webpack.js:130564

PR incoming...

version change from 3.0.7 to 3.1.0

hello, sorry to bother you. My framework is react, I find the version is 3.0.7,and it works well when npm run build. but today the version is 3.1.0, I can't npm run build successfully, I want to know how to fix it.
and the pbkdf2 is not in my pachage.json. Thank you very much

The value "NaN" is invalid for option "size"

calvinmetcalf/crypto-pouch#75 - using that package, got error, investigated and found that for some reason digest argument on the other side become fully capitalized, which in turn make package failed to get size of corresponding digest in sync-browser.js file:

  var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
  var opad = Buffer.allocUnsafe(blocksize + sizes[alg])

as alg === 'SHA-256', sizes['SHA-256'] is undefined, so result sum is NaN.

Uncaught TypeError: Cannot read property 'split' of undefined in browser.js line 22 prevails

Using v.3.0.9, I still encounter the Uncaught TypeError: Cannot read property 'split' of undefined error in browser.js, line 22.

├─ [email protected]
│  └─ create-hmac@^1.1.2

I am using the pbkdf2 library with webpack without browserify.

A workaround is to import var process = require('process') at the top of the browser.js file.

Do you have ideas how we could get a proper solution for this issue?

Performance worse than sjcl lib

@dcousens asked for a ticket ;)

performance on various engines is a lot worse compared to the 'sjcl' package.
see benchmarking test repo: https://github.com/rubensayshi/pbkdf2-benchmark

the most significant one is when using the old UIWebView on IOS (currently still the default for cordova apps without using a 3rd party plugin to upgrade to WKWebView) where it's close to a 10x difference.
but for the future WKWebView will not become the default to use in cordova 4.0.0+.

for chrome (on all platforms) there's also a significant difference between the 2 libs.

for w/e reason firefox sjcl is actually slower ... but (my) firefox is scrap xD

Incompatibility with rn-nodeify

When i Run my postinstall script, in a previous version of pbkdf2 (3.0.8), the rn-nodeify replace the "process.version" with the current version of node
MicrosoftTeams-image (2)
In the actual version the rn-nodeify brokes the code
MicrosoftTeams-image (3)

node: pbkdf2-compat dropped compatibility for custom algorithm 3.0.0

3.0.0 was published without support for a custom hash algorithm in node.
As such, the defacto example (and main reason for this library before it was used in browserify) is now broken in Node 0.10.

var compat = require('pbkd2f-compat')
var derivedKey = compat.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') // currently SHA1!!!

We need to merge #5 ASAP, and probably unpublish 3.0.0.

Name

The name should be pbkdf2 instead of pbkd2f on npm.

Ownership

@dcousens can you either publish version 3.0.0 or give me permission to? publicEncrypt and browserify-sign are waiting on this to be modularized

diffrent results in 0.10 and iojs

password: test
salt (in hex format): 7b970da6a2fddaba
iterations: 1000
length: 64
algo: sha512

gives me

e6d98ba1993f1e721dab924cec8ca8e7af4b40035553da88aec486131afc0f88ff40a29467911fb58c042ede9701551f0b4b06b4207b2a831d90783aab3095da

in 0.10

but in iojs

7c89cceaea1811b0aeaf23587fadb4b80580d9b26c7e7489ec56f9f0a84c1b612c788ddfb4a86dee8e5be70d4742b84ff3e818e3b83aa68d21db5b4d9f70dc8e

DoS with long password

If you enter a long password it will take significantly longer. This runs in O(pwLen * rounds) time instead of in O(pwLen + rounds) time.

Ideally you'd want to do a cached HMAC for a 2x speed increase (on normal sized passwords):

var cachedCtx = createHmac(digest, password)

...

-var T = createHmac(digest, password).update(block1).digest()
+var T = "cachedCtx.clone()".update(block1).digest()

...

-U = createHmac(digest, password).update(U).digest()
+U = "cachedCtx.clone()".update(U).digest()

Their are some problems with the "create-hmac" package and once those are fixed cached HMAC will be the best way to go. See browserify/createHmac#27. Also I do not know the proper way to clone an object in Node.js. Thus the quotes around cachedCtx.clone().

Make microtime a devDependency again

Placing it in the optionalDependencies (8423738) makes it being installed on consumers of this library, which shouldn't be required.

Is there another reason?

Thanks for the amazing work on this library.

Increase testing coverage

As of https://travis-ci.org/crypto-browserify/pbkdf2/jobs/159199947

------------------|----------|----------|----------|----------|----------------|
File              |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
------------------|----------|----------|----------|----------|----------------|
 pbkdf2/          |      100 |    96.55 |      100 |      100 |                |
  browser.js      |      100 |    94.44 |      100 |      100 |                |
  index.js        |      100 |      100 |      100 |      100 |                |
  precondition.js |      100 |      100 |      100 |      100 |                |
------------------|----------|----------|----------|----------|----------------|
All files         |      100 |    96.55 |      100 |      100 |                |
------------------|----------|----------|----------|----------|----------------|

The browser.js coverage isn't 100%.
We should fix that.

different results on MacOSX and Debian

given the program:

var pbkdf2 = require('pbkdf2');
console.log(pbkdf2.hashSync('password', 'salt', 10000, 32, 'sha256'));

on my mac I get:

$ uname -a
Darwin Jamess-Mac-mini 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64
$ cat node_modules/pbkdf2/package.json | grep version
  "version": "0.0.5",
$ node testhash.js 
5ec02b91a4b59c6f59dd5fbe4ca649ec

and on my linux machine

uname -a
Linux brooks 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u2 x86_64 GNU/Linux
$ cat node_modules/pbkdf2/package.json | grep version
  "version": "0.0.5",
$ node testhash.js 
a2c2646186828474b754591a547c18f1

I would expect these hashes to be the same.

In the electronic application, when I start nodeintegration, the program appears default-encoding.js? 9f9d:10 Uncaught TypeError: Cannot read property 'split' of undefined

var defaultEncoding
/* istanbul ignore next */
if (global.process && global.process.browser) {
defaultEncoding = 'utf-8'
} else if (global.process && global.process.version) {
console.log('process.version', process.version) // undefined
console.log('global.process.version', global.process.version) // v12.18.3

// This line needs to be modified to "global.process.version"
// var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)

// like this
var pVersionMajor = parseInt(global.process.version.split('.')[0].slice(1), 10)

defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'

} else {
defaultEncoding = 'utf-8'
}
module.exports = defaultEncoding

pbkdf2 failing on some development environments

The current dependency on pbkdf2 v3.1.1 causes some development environments to error due to a check on the process object. This has been resolved in version v3.1.2

Suggest up'reving pbkdf2 dependency to v3.1.2.

works on browser?

Does this library works with es6 imports ?

const key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const output = pbkdf2.pbkdf2Sync(normalisedMasterPassword, key, 100000, 32, 'sha256');

Screenshot from 2019-06-21 15-23-50

I am getting error as in screenshot

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.