到目前爲止我們能產生隨機的合法助記詞了,接下來我們要用這些助記詞生成RootSeed。
生成過程直接調用接口,但是裏面的原理卻很複雜。
這裏需要用到pbkdf2函數。關於這個函數的說明,在BIP39裏有,我就不翻譯了,內容如下:
To create a binary seed from the mnemonic, we use the PBKDF2 function with a mnemonic
sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" + passphrase
(again in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512
is used as the pseudo-random function. The length of the derived key is 512 bits (= 64 bytes).
關於這裏的密碼,各個錢包用的密碼都不同,例如TREZOR硬件錢包使用“TREZOR”作爲密碼,也可以不用密碼,傳入空字符串。
實現代碼如下:
import (
"crypto/sha512"
"errors"
"golang.org/x/crypto/pbkdf2"
"strings"
)
//助記詞單詞之間一定要用空格隔開,不能用其他符號隔開
func Mnemonics2RootSeed(mnemonics, passphrase string) ([]byte, error) {
words := strings.Split(mnemonics, " ")
wordAmount := len(words)
if !(wordAmount >= 12 && wordAmount <=24 && wordAmount%3==0) {
return nil,errors.New("invalid mnmonic words")
}
return pbkdf2.Key([]byte(mnemonics), []byte("mnemonic"+passphrase), 2048, 64, sha512.New ),nil
}
測試代碼:
func TestMnemonicWords2RootSeed(t *testing.T) {
//t.SkipNow()
t.Run("test use words to generate root seed", func(t *testing.T) {
var (
words = "glow laugh acquire menu anchor evil occur put hover renew calm purpose"
seed []byte
err error
want = "afab97eb2f25d6c4cd3ca02674ab362a3c851a7c81b017a411345453ce869cb09ff8508d359a1091f0eb1b52c988fc686dcc21b2e57129a8036ea351808c2ee5"
got string
)
if seed,err = Mnemonics2RootSeed(words, "TREZOR"); err != nil {
t.Error(err)
return
}
got = hex.EncodeToString(seed)
if want != got {
t.Error("error seed")
t.Error("want:", want)
t.Error("got:", got)
}
})
}
(全文完)
參考鏈接:
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki