Browse Source

add check function for BIP39

fixes #393
patch-2
Devrandom 11 years ago
parent
commit
efb62b08b7
  1. 26
      lib/BIP39.js
  2. 1
      test/test.BIP39.js

26
lib/BIP39.js

@ -48,6 +48,32 @@ BIP39.entropy2mnemonic = function(wordlist, buf) {
return mnemonic;
}
BIP39.check = function(wordlist, mnemonic) {
var words = mnemonic.split(' ');
var bin = "";
for (var i = 0; i < words.length; i++) {
var ind = wordlist.indexOf(words[i]);
if (ind < 0)
return false;
bin = bin + ("00000000000" + ind.toString(2)).slice(-11);
}
if (bin.length % 11 != 0) {
throw new Error("internal error - entropy not an even multiple of 11 bits - " + bin.length);
}
var cs = bin.length / 33;
var hash_bits = bin.slice(-cs);
var nonhash_bits = bin.slice(0, bin.length - cs);
var buf = new Buffer(nonhash_bits.length / 8);
for (var i = 0; i < nonhash_bits.length / 8; i++) {
buf.writeUInt8(parseInt(bin.slice(i * 8, (i + 1) * 8), 2), i);
}
var hash = coinUtil.sha256(buf);
var expected_hash_bits = hash[0].toString(2);
expected_hash_bits = ("00000000" + expected_hash_bits).slice(-8).slice(0, cs);
return expected_hash_bits == hash_bits;
}
BIP39.mnemonic2seed = function(mnemonic, passphrase) {
if (!passphrase)
passphrase = "";

1
test/test.BIP39.js

@ -153,6 +153,7 @@ describe('BIP39', function() {
var seed = vector[2];
var mnemonic1 = BIP39.entropy2mnemonic(BIP39WordlistEn, new Buffer(code, 'hex'));
var seed1 = BIP39.mnemonic2seed(mnemonic, 'TREZOR');
BIP39.check(BIP39WordlistEn, mnemonic).should.be.true;
mnemonic1.should.equal(mnemonic);
seed1.toString('hex').should.equal(seed)
}

Loading…
Cancel
Save