From f71d3a652186c364a1fc7af518540d316d70abf5 Mon Sep 17 00:00:00 2001 From: Richard Schneider Date: Sun, 10 Dec 2017 17:19:20 +1300 Subject: [PATCH] fix: maps an IPFS hash name to its forge equivalent Fixes #12 --- src/keychain.js | 22 ++++++++++++++++++++-- test/keychain.spec.js | 6 ++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/keychain.js b/src/keychain.js index e4a61d7102..7f9f508555 100644 --- a/src/keychain.js +++ b/src/keychain.js @@ -19,13 +19,26 @@ const NIST = { minIterationCount: 1000 } +/** + * Maps an IPFS hash name to its forge equivalent. + * + * See https://github.com/multiformats/multihash/blob/master/hashtable.csv + * + * @private + */ +const hashName2Forge = { + 'sha1': 'sha1', + 'sha2-256': 'sha256', + 'sha2-512': 'sha512', + +} const defaultOptions = { // See https://cryptosense.com/parametesr-choice-for-pbkdf2/ dek: { keyLength: 512 / 8, iterationCount: 10000, salt: 'you should override this value with a crypto secure random number', - hash: 'sha512' + hash: 'sha2-512' } } @@ -120,13 +133,18 @@ class Keychain { } this.dek = opts.dek + // Get the hashing alogorithm + const hashAlgorithm = hashName2Forge[opts.dek.hash] + if (!hashAlgorithm) + throw new Error(`dek.hash '${opts.dek.hash}' is unknown or not supported`) + // Create the derived encrypting key let dek = forge.pkcs5.pbkdf2( opts.passPhrase, opts.dek.salt, opts.dek.iterationCount, opts.dek.keyLength, - opts.dek.hash) + hashAlgorithm) dek = forge.util.bytesToHex(dek) Object.defineProperty(this, '_', { value: () => dek }) diff --git a/test/keychain.spec.js b/test/keychain.spec.js index d0b61bcc20..75a9f5feba 100644 --- a/test/keychain.spec.js +++ b/test/keychain.spec.js @@ -41,6 +41,12 @@ module.exports = (datastore1, datastore2) => { expect(Keychain.options).to.exist() }) + it('needs a supported hashing alorithm', () => { + const ok = new Keychain(datastore2, { passPhrase: passPhrase, dek: { hash: 'sha2-256' } }) + expect(ok).to.exist() + expect(() => new Keychain(datastore2, { passPhrase: passPhrase, dek: { hash: 'my-hash' } })).to.throw() + }) + describe('key name', () => { it('is a valid filename and non-ASCII', () => { ks.removeKey('../../nasty', (err) => {