Skip to main content

Crate btc_keygen

Crate btc_keygen 

Source
Expand description

Minimal offline Bitcoin key generator for cold storage.

Generates a secp256k1 private key from OS-provided cryptographic randomness and derives the corresponding WIF, compressed public key, and native SegWit (Bech32) address. Designed for air-gapped key ceremonies.

§Library usage

// 1. Generate a private key from OS randomness
let key = btc_keygen::generate()?;

// 2. Encode as WIF (for wallet import)
let wif = btc_keygen::encode_wif(&key);
println!("{}", wif.expose_str());

// 3. Derive the compressed public key
let pubkey = btc_keygen::derive_pubkey(&key);

// 4. Derive the Bitcoin address
let address = btc_keygen::derive_address(&pubkey);

To use an existing key instead of OS randomness, see PrivateKey::from_bytes and PrivateKey::from_hex.

§Security

  • Entropy comes from the OS CSPRNG via getrandom.
  • Private key bytes are zeroized in memory when PrivateKey is dropped.
  • Secret output never leaves this crate as a String. encode_wif returns a SecretWif and PrivateKey::to_hex returns a SecretKeyHex: fixed-size buffers that zeroize on drop, redact their Debug, and cannot be cloned, copied, or printed with {}. They are filled in place, so no secret-bearing String, Vec, or format! temporary is allocated along the way.
  • Exposing a secret is explicit (expose_bytes, expose_str) and is the point where copies become the caller’s responsibility: writing the bytes to a terminal, or copying them into a String, puts key material in memory this crate cannot erase.
  • PrivateKey::as_bytes and PrivateKey::to_secret_key exist for interoperability and hand out key material the crate no longer controls. In particular secp256k1::SecretKey is Copy and does not erase itself on drop; its non_secure_erase is best-effort.
  • Erasure is best-effort in general. It covers the buffers this crate owns, not memory the OS relocated to swap or a crash dump, not the stack libsecp256k1 uses while deriving a public key, and not copies the optimizer keeps alive. The zeroize crate documents that last limit for itself.
  • No networking code, so the crate cannot leak secrets over the network.
  • Elliptic curve operations use Bitcoin Core’s libsecp256k1.

Structs§

Error
Error returned when key generation fails.
PrivateKey
A validated secp256k1 private key that zeroizes its bytes on drop.
SecretAscii
A fixed-length ASCII secret that zeroizes on drop and redacts its Debug.

Functions§

derive_address
Derives a native SegWit (P2WPKH) Bech32 address from a compressed public key.
derive_pubkey
Derives the compressed public key (33 bytes) from a private key.
encode_wif
Encodes a private key as a Wallet Import Format (WIF) string.
generate
Generates a new Bitcoin private key using OS-provided cryptographic randomness.

Type Aliases§

SecretKeyHex
A raw private key in hexadecimal: exactly 64 lowercase ASCII bytes.
SecretWif
A compressed mainnet WIF: exactly 52 Base58 ASCII bytes.