index: use secureRandom and add missing tests

This commit is contained in:
Daniel Cousens 2014-06-23 17:56:08 +10:00
parent b6798c95f8
commit e569aeb6d7
3 changed files with 30 additions and 4 deletions

View File

@ -1,5 +1,6 @@
var CryptoJS = require('crypto-js')
var crypto = require('crypto')
var secureRandom = require('secure-random')
var includeFolder = require('include-folder')
var path = require('path')
@ -32,10 +33,12 @@ BIP39.prototype.entropyToMnemonic = function(entropy) {
return words.join(' ')
}
BIP39.prototype.generateMnemonic = function(strength) {
BIP39.prototype.generateMnemonic = function(strength, rng) {
strength = strength || 128
var entropy = crypto.randomBytes(strength/8).toString('hex')
return this.entropyToMnemonic(entropy)
rng = rng || secureRandom
var hex = rng.randomBuffer(strength / 8).toString('hex')
return this.entropyToMnemonic(hex)
}
BIP39.prototype.validate = function(mnemonic) {

View File

@ -16,7 +16,8 @@
"dependencies": {
"crypto-js": "^3.1.2-2",
"require-json-tree": "~1.1.0",
"include-folder": "~0.7.0"
"include-folder": "~0.7.0",
"secure-random": "1.0.0"
},
"devDependencies": {
"mocha": "^1.17.1",

View File

@ -27,6 +27,28 @@ describe('entropyToMnemonic', function() {
})
})
describe('generateMnemonic', function() {
it('generates a mnemonic', function() {
var mnemonic = bip39.generateMnemonic(96)
var words = mnemonic.split(' ')
assert.equal(words.length, 9)
})
it('allows a custom RNG to be used', function() {
var rng = {
randomBuffer: function(size) {
var buffer = new Buffer(size)
buffer.fill(4) // guaranteed random
return buffer
}
}
var mnemonic = bip39.generateMnemonic(64, rng)
assert.equal(mnemonic, 'advice cage absurd amount doctor act')
})
})
describe('validate', function() {
vectors.forEach(function(v, i) {
it('passes check ' + i, function() {