助记词ChecksumException

@Test(expected = MnemonicException.MnemonicChecksumException.class)
public void testBadChecksum() throws Exception {
   String code="bless cloud wheel regular tiny venue bird web grief security dignity zoo"; 
   List words = WHITESPACE_SPLITTER.splitToList(code);
   mc.check(words);
 }
for (String word : words) {
    // Find the words index in the wordlist.
    int ndx;
    if (bip39Language.getLanguageType() == BIP39Language.Language.CHINESE_SIMPLIFIED) {
        ndx = bip39Language.wordList.indexOf(word);
    } else {
        ndx = Collections.binarySearch(this.bip39Language.wordList, word);
    }
    if (ndx < 0) {//该单词不在列表中
        System.out.println("该单词不在列表中 word: " + word + " " + ndx);
        throw new MnemonicException.MnemonicWordException(word);
    }
    System.out.println("单词:" + word + " 位置ndx:"+ndx+" word index:"+wordindex+" 它的11位如下...");
    // Set the next WORDS_LENGTH_BIT bits to the value of the index.
    int concatBitsIndex;
    for (int ii = 0; ii < WORDS_LENGTH_BIT; ++ii) {
        concatBitsIndex = (wordindex * WORDS_LENGTH_BIT) + ii;//11x15=165或者11x12=132
        //concatBits[concatBitsIndex] = (ndx & (1 << (10 - ii))) != 0;
        boolean bitBoolean=(ndx & (1 << (WORDS_LENGTH_BIT - 1 - ii))) != 0;
        System.out.println("    concatBitsIndex: " + concatBitsIndex + " " + bitBoolean);
        concatBits[concatBitsIndex] = bitBoolean;
    }
    ++wordindex;//最大到12、15
}

binarySearch无法对中文助记词排序,看英文文件是从a开始排序好的,中文没有规则,无法二分查找,只能看索引


image.png
public byte[] toEntropy(List words) throws MnemonicChecksumException {
        int checksumLengthBits = concatLenBits / 33;
        int entropyLengthBits = concatLenBits - checksumLengthBits;
        // Extract original entropy as bytes.132/8=16字节
        byte[] entropy = new byte[entropyLengthBits / 8];
        for (int ii = 0; ii < entropy.length; ++ii)
            for (int jj = 0; jj < 8; ++jj)
                if (concatBits[(ii * 8) + jj])
                    entropy[ii] |= 1 << (7 - jj);

        // Take the digest of the entropy.
        byte[] hash = Sha256Hash.hash(entropy);
        boolean[] hashBits = bytesToBits(hash);

        // Check all the checksum bits.
        for (int i = 0; i < checksumLengthBits; ++i) {
            if (concatBits[entropyLengthBits + i] != hashBits[i]) {
                throw new MnemonicException.MnemonicChecksumException();
            }
        }
   }

我们只探讨主流的12位、15位助记词的场景,分成12、15份,每份都是11位
1)在128位后面追加4位校验码。 长度变为了132位,然后分成12份,每份11位值查表得到一个单词, 共记12个助记词。将每个包含11位部分的值与一个已经预先定义2048个单词的字典做对应.
这对助记词在english.txt里都存在,并不是随机取12就可以作为私钥了。concatBits、hashBits一个true、一个false,出现异常
2)15位看下面的图


image.png

你可能感兴趣的:(助记词ChecksumException)