Merge pull request #4 from dcousens/rand

Generate Random Mnemonic
This commit is contained in:
Wei Lu 2014-06-26 10:13:44 +08:00
commit 0ea7f03a4b
3 changed files with 28 additions and 4 deletions

View File

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

View File

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

View File

@ -27,6 +27,26 @@ 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 = 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() { describe('validate', function() {
vectors.forEach(function(v, i) { vectors.forEach(function(v, i) {
it('passes check ' + i, function() { it('passes check ' + i, function() {