This example demonstrates how to use the bip32 compatibility package to generate a new Hierarchical Deterministic (HD) key pair (xPriv and xPub).
The generate_hd_key example showcases:
- Calling
bip32.GenerateHDKeyPairwith a specified seed length (bip32.SecureSeedLength). - Receiving the generated extended private key (xPriv) and extended public key (xPub).
- Verifying the public key via a fingerprint without exposing key material.
// Generate a new HD key pair (xPriv and xPub)
// bip32.SecureSeedLength provides a recommended length for the seed.
xPrivateKey, xPublicKey, err := bip32.GenerateHDKeyPair(bip32.SecureSeedLength)
if err != nil {
log.Fatalf("Error generating HD key pair: %s", err.Error())
}
// Never log raw keys. Use a small fingerprint to confirm success.
fingerprint := sha256.Sum256([]byte(xPublicKey))
log.Printf("Generated HD key pair (xPriv length: %d, xPub fingerprint: %x)", len(xPrivateKey), fingerprint[:8])This section shows the direct use of bip32.GenerateHDKeyPair. This function creates a new master HD key from a randomly generated seed of the given length. It returns the extended private key (xPriv) and the corresponding extended public key (xPub) as strings.
To run this example:
go run generate_hd_key.goThe output will confirm the generated key lengths and show a short fingerprint of the xPub. Each run will produce a different key pair, so securely store the raw keys instead of logging them.
Note:
- The generated xPrivateKey is the master private key for an HD wallet structure. It should be kept extremely secure and never logged in plaintext.
- The xPublicKey can be used to derive child public keys without exposing the private key. Only expose fingerprints when confirming values in logs.
bip32.SecureSeedLengthis typically 32 bytes (256 bits) or 64 bytes (512 bits) for strong security.
To generate a new HD key pair in your application:
- Call
xPriv, xPub, err := bip32.GenerateHDKeyPair(seedLength), whereseedLengthis your desired seed length (e.g.,bip32.SecureSeedLengthorbip32.RecommendedSeedLen). - Handle any potential error during generation.
- Securely store the
xPrivstring. ThexPubstring can be stored less securely if needed for public key derivation. - You can then use the
xPrivorxPubwith functions likebip32.GetHDKeyFromExtendedPrivateKey()orbip32.GetHDKeyFromExtendedPublicKey()to get*bip32.HDKeyobjects, which can then be used to derive child keys.
For more information, see:
- Package Documentation - BIP32 compatibility
- BIP32 Specification
- Derive Child Key Example (Note: this example uses a different derivation method,
ec.PrivateKey.DeriveChild, not directly HD path derivation from an xPriv/xPub but is related to key derivation) - HD Key From xPub Example