Mnemonic For Master Private Key
Abstract
Motivation
Overview
Implementation
package main
import (
"encoding/hex"
"fmt"
"crypto/sha256"
"github.com/libsv/go-bk/bec"
"github.com/libsv/go-bk/bip39"
)
func main() {
// We generate some random bytes (any method for creating good random data can be used here).
random, _ := bip39.GenerateEntropy(128)
// The random data is encoded as a mnemonic of 12 words using the PBKDF2 function to SHA512 hash of the mnemonic sentence concatenated with the passcode (blank in this case).
mnemonic, seed, _ := bip39.Mnemonic(random, "")
// The private key is a sha256 of the seed bytes, this normalizes the output to 256 bits needed.
privKeyBytes := sha256.Sum256(seed)
// Here we ensure that using the mnemonic in future will result in the same private key.
seed, _ = bip39.MnemonicToSeed(mnemonic, "")
if privKeyBytes != sha256.Sum256(seed) {
panic("mnemonic is invalid")
}
// Type cast a slice of bytes
pkb := make([]byte, 32)
copy(pkb, privKeyBytes[:])
fmt.Println(hex.EncodeToString(pkb))
// > '1ad0895dd317163f0e83499c30bc593dbcc54cad96a5f57b065ce9f700513250'
// Create a PrivKey on the secp256k1 curve.
masterKey, _ := bec.PrivKeyFromBytes(bec.S256(), pkb)
// Derive the corresponding PubKey and log it.
pubKey := masterKey.PubKey()
pubBytes := pubKey.SerialiseCompressed()
fmt.Println(hex.EncodeToString(pubBytes))
// > '021c2361fa1c39e21422b1374c2a08106f99b5425ada71f46f55b8e8e9d4a932db'
}JavaScript
Last updated
Was this helpful?

