Skip to content

Commit

Permalink
fix(create-key): use browser MSR-JavaScript-Crypto polyfill
Browse files Browse the repository at this point in the history
It works, but the tests are really slow.
  • Loading branch information
Terreii committed Nov 11, 2020
1 parent f8ec5ff commit 0a2bbca
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 14 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# EditorConfig from https://EditorConfig.org

# top-most EditorConfig file
root = true

# All files
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
55 changes: 41 additions & 14 deletions lib/create-key.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,56 @@
'use strict'

var Buffer = require('buffer/').Buffer
var pbkdf2 = require('pbkdf2')
var Promise = require('lie')
var randomBytes = require('randombytes')
var subtle = (global.crypto && global.crypto.subtle) ||
(global.msCrypto && window.msCrypto.subtle) ||
(global.msrCrypto && window.msrCrypto.subtle) ||
require('./helpers/msrcrypto').subtle

module.exports = function createKey (password, saltArg) {
var digest = 'sha256'
var passwordBuffer = toBuffer(password, 'utf-8', 'password')
var digest = 'SHA-256'
var iterations = 100000
var keyLength = 256 / 8

var salt = saltArg != null && typeof saltArg === 'string' && saltArg.length === 32
? saltArg
: randomBytes(16).toString('hex')
var saltyBuffy = Buffer.from(salt, 'hex')

return subtle.importKey('raw', passwordBuffer, { name: 'PBKDF2' }, false, ['deriveBits'])

return new Promise(function (resolve, reject) {
var saltyBuffy = Buffer.from(salt, 'hex')
.then(function (key) {
return subtle.deriveBits(
{
name: 'PBKDF2',
salt: saltyBuffy,
iterations: iterations,
hash: {
name: digest
}
},
key,
keyLength << 3
)
})

pbkdf2.pbkdf2(password, saltyBuffy, iterations, 256 / 8, digest, function (err, key) {
if (err) {
reject(err)
} else {
resolve({
key: key,
salt: salt
})
.then(function (res) {
return {
key: Buffer.from(res),
salt: salt
}
})
})
}

function toBuffer (thing, encoding, name) {
if (Buffer.isBuffer(thing)) {
return thing
} else if (typeof thing === 'string') {
return Buffer.from(thing, encoding)
} else if (ArrayBuffer.isView(thing)) {
return Buffer.from(thing.buffer)
} else {
throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
}
}

0 comments on commit 0a2bbca

Please sign in to comment.