美文网首页区块链研习社区块链
HD Wallet 系列 - 助记词与种子

HD Wallet 系列 - 助记词与种子

作者: tpkeeper | 来源:发表于2019-09-29 11:01 被阅读0次

原文地址:tpkeep.com

参考 bip39

  • 定义了助记词的生成规则
  • 定义了由助记词导出种子的规则
  • 定义了助记词 wordlist,目前包含7种语言,每种 2048个单词
  • 助记词到种子的推导是单向的

助记词的生成

  1. 产生一个随机数作为熵 entropy,长度为 128-256 bits,必须为 32 bits 的整数倍
  2. 然后在 entropy 尾部 append 校验位,校验位即entropy 的 sha256 的前几位,位数如下:
entropy checksum entropy+checksum mnemonic
128 4 132 12
160 5 165 15
192 6 198 18
224 7 231 21
256 8 264 24
  1. 然后 将 entropy+checksum 按 11 bits 分组,每组 11bits,大小为 0 ~ 2^11-1 即 0 ~ 2047,刚好映射 wordlist 里的单词
  2. 单词以空格隔开转换为字符串

助记词生成种子

  1. 准备:
    参数 1 作为密码:助记词字符串
    参数 2 作为盐:"mnemonic"+passphrase(可选的),
    参数 3 作为循环次数: 2048 ,
    参数 4 作为 hash 函数:HMAC-SHA512
    参数 5 作为派生key长度:512bits

  2. 将参数传入 PBKDF2 函数,得到 512 bits 的 seeds

代码实战

代码参考:https://github.com/tpkeeper/addrtool/blob/master/mnemonic_test.go

func TestGenMnemonic(t *testing.T) {
    //生成熵
    entropyBytes,_:=bip39.NewEntropy(128)
    t.Log("entropyBytes:",entropyBytes)

    //生成助记词
    mnemonic,_:=bip39.NewMnemonic(entropyBytes)
    t.Log("mnemonic:",mnemonic)
}
func TestMnemonicToSeed(t *testing.T) {
    mnemonic :="chef fiction deputy stage pudding pink skirt often decade drift music loop"
    //助记词生成种子 password 为空
    seed:=bip39.NewSeed(mnemonic,"")
    t.Log("seed:",hex.EncodeToString(seed))
}

//output:
//entropyBytes: [158 45 139 248 16 245 71 178 223 231 241 118 0 211 244 134]
//mnemonic: owner hobby wrap capable federal sunny legend wreck invite alley wood aspect
//seed: 04ef53d66b17fdfb6538c5d183f0b0569fc1c79d07f044f7670c3038aff411e5abcbe8c457b584d0c1e3504ab94fb311f9097a793c20dfc746a87087ed5dc119

相关文章

网友评论

    本文标题:HD Wallet 系列 - 助记词与种子

    本文链接:https://www.haomeiwen.com/subject/omzzuctx.html