Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

Generate HD Key Pair Example

This example demonstrates how to use the bip32 compatibility package to generate a new Hierarchical Deterministic (HD) key pair (xPriv and xPub).

Overview

The generate_hd_key example showcases:

  1. Calling bip32.GenerateHDKeyPair with a specified seed length (bip32.SecureSeedLength).
  2. Receiving the generated extended private key (xPriv) and extended public key (xPub).
  3. Verifying the public key via a fingerprint without exposing key material.

Code Walkthrough

Generating the HD Key Pair

// 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.

Running the Example

To run this example:

go run generate_hd_key.go

The 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.SecureSeedLength is typically 32 bytes (256 bits) or 64 bytes (512 bits) for strong security.

Integration Steps

To generate a new HD key pair in your application:

  1. Call xPriv, xPub, err := bip32.GenerateHDKeyPair(seedLength), where seedLength is your desired seed length (e.g., bip32.SecureSeedLength or bip32.RecommendedSeedLen).
  2. Handle any potential error during generation.
  3. Securely store the xPriv string. The xPub string can be stored less securely if needed for public key derivation.
  4. You can then use the xPriv or xPub with functions like bip32.GetHDKeyFromExtendedPrivateKey() or bip32.GetHDKeyFromExtendedPublicKey() to get *bip32.HDKey objects, which can then be used to derive child keys.

Additional Resources

For more information, see: