原文地址:tpkeep.com
参考 bip39
- 定义了助记词的生成规则
- 定义了由助记词导出种子的规则
- 定义了助记词 wordlist,目前包含7种语言,每种 2048个单词
- 助记词到种子的推导是单向的
助记词的生成
- 产生一个随机数作为熵 entropy,长度为 128-256 bits,必须为 32 bits 的整数倍
- 然后在 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 |
- 然后 将 entropy+checksum 按 11 bits 分组,每组 11bits,大小为 0 ~ 2^11-1 即 0 ~ 2047,刚好映射 wordlist 里的单词
- 单词以空格隔开转换为字符串
助记词生成种子
-
准备:
参数 1 作为密码:助记词字符串
参数 2 作为盐:"mnemonic"+passphrase(可选的),
参数 3 作为循环次数: 2048 ,
参数 4 作为 hash 函数:HMAC-SHA512
参数 5 作为派生key长度:512bits -
将参数传入 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
网友评论