Skip to content

Commit f71d3a6

Browse files
fix: maps an IPFS hash name to its forge equivalent
Fixes #12
1 parent 3b8d05a commit f71d3a6

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/keychain.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,26 @@ const NIST = {
1919
minIterationCount: 1000
2020
}
2121

22+
/**
23+
* Maps an IPFS hash name to its forge equivalent.
24+
*
25+
* See https://github.com/multiformats/multihash/blob/master/hashtable.csv
26+
*
27+
* @private
28+
*/
29+
const hashName2Forge = {
30+
'sha1': 'sha1',
31+
'sha2-256': 'sha256',
32+
'sha2-512': 'sha512',
33+
34+
}
2235
const defaultOptions = {
2336
// See https://cryptosense.com/parametesr-choice-for-pbkdf2/
2437
dek: {
2538
keyLength: 512 / 8,
2639
iterationCount: 10000,
2740
salt: 'you should override this value with a crypto secure random number',
28-
hash: 'sha512'
41+
hash: 'sha2-512'
2942
}
3043
}
3144

@@ -120,13 +133,18 @@ class Keychain {
120133
}
121134
this.dek = opts.dek
122135

136+
// Get the hashing alogorithm
137+
const hashAlgorithm = hashName2Forge[opts.dek.hash]
138+
if (!hashAlgorithm)
139+
throw new Error(`dek.hash '${opts.dek.hash}' is unknown or not supported`)
140+
123141
// Create the derived encrypting key
124142
let dek = forge.pkcs5.pbkdf2(
125143
opts.passPhrase,
126144
opts.dek.salt,
127145
opts.dek.iterationCount,
128146
opts.dek.keyLength,
129-
opts.dek.hash)
147+
hashAlgorithm)
130148
dek = forge.util.bytesToHex(dek)
131149
Object.defineProperty(this, '_', { value: () => dek })
132150

test/keychain.spec.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ module.exports = (datastore1, datastore2) => {
4141
expect(Keychain.options).to.exist()
4242
})
4343

44+
it('needs a supported hashing alorithm', () => {
45+
const ok = new Keychain(datastore2, { passPhrase: passPhrase, dek: { hash: 'sha2-256' } })
46+
expect(ok).to.exist()
47+
expect(() => new Keychain(datastore2, { passPhrase: passPhrase, dek: { hash: 'my-hash' } })).to.throw()
48+
})
49+
4450
describe('key name', () => {
4551
it('is a valid filename and non-ASCII', () => {
4652
ks.removeKey('../../nasty', (err) => {

0 commit comments

Comments
 (0)