DEV Community

Cover image for Dissecting BIP-39 Under the Hood: How Mnemonic Phrases and Private Keys Work (With Python Code)
George
George

Posted on

Dissecting BIP-39 Under the Hood: How Mnemonic Phrases and Private Keys Work (With Python Code)

Introduction

BIP-39 (Bitcoin Improvement Proposal 39) is a standard that converts random entropy bits into human-readable mnemonic phrases. These 12–24-word phrases are used to recover cryptocurrency wallets. In this article, we will explore how BIP-39 works at the code level and write a Python example to generate a mnemonic phrase and derive a private key.

How Does a Mnemonic Phrase Work

1. Generating Entropy

BIP-39 starts with creating random entropy (128–256 bits). For example, 128 bits of entropy produce 12 words, while 256 bits produce 24 words. More entropy means higher security.

2. Checksum Addition

A checksum is appended to the entropy. Its length depends on the entropy size:

  • 128 bits → 4-bit checksum
  • 256 bits → 8-bit checksum This allows verifying the phrase’s correctness during wallet recovery.

3. Mapping to a Wordlist

The combined bits are split into 11-bit groups, each corresponding to a word from BIP-39’s predefined list (2048 words). For example, 01011010101 might map to apple.

Practice: Generating a Mnemonic in Python

Here’s a Python code snippet to generate a mnemonic phrase. We will use the hashlib and bitstring libraries.

import hashlib
import secrets
from bitstring import BitArray

# Generate entropy (128 bits)
entropy = secrets.token_bytes(16)  # 16 bytes = 128 bits

# Add checksum
entropy_bits = BitArray(entropy).bin
checksum_length = len(entropy_bits) // 32
hash_entropy = hashlib.sha256(entropy).digest()
checksum = BitArray(hash_entropy).bin[:checksum_length]

full_bits = entropy_bits + checksum

# Split into 11-bit chunks
indices = []
for i in range(0, len(full_bits), 11):
    chunk = full_bits[i:i+11]
    indices.append(int(chunk, 2))

# Load BIP-39 wordlist (example)
bip39_words = [
    "abandon", "ability", "able", ..., "zoo"
]  # Full list: https://bip39-phrase.com/

mnemonic = " ".join([bip39_words[index] for index in indices])
print("Mnemonic phrase:", mnemonic)
Enter fullscreen mode Exit fullscreen mode

Converting a Mnemonic to a Private Key

According to BIP-39, the mnemonic and an optional passphrase are converted into a 512-bit seed using PBKDF2-HMAC-SHA512. This seed is used to derive private keys via BIP-32/BIP-44.

import hashlib
import hmac

# Password (optional)
passphrase = ""
salt = "mnemonic" + passphrase

# PBKDF2
seed = hashlib.pbkdf2_hmac(
    "sha512",
    mnemonic.encode("utf-8"),
    salt.encode("utf-8"),
    2048,  # Recommended iterations
    64     # Seed length (64 bytes = 512 bits)
)

print("Seed (hex):", seed.hex())
Enter fullscreen mode Exit fullscreen mode

How Do BIP-32 and BIP-44 Work?

  • BIP-32 (HD Wallets) enables hierarchical key derivation from a single seed.
  • BIP-44 defines a structure for multi-currency wallets (e.g., m/44'/0'/0' for Bitcoin).

To derive private keys, use derivation paths. For example:

from bip32utils import BIP32Key

# Example for Bitcoin (BIP-44)
bip32_key = BIP32Key.fromEntropy(seed)
child_key = bip32_key.ChildKey(0x80000000)  # Hardened path
private_key = child_key.WalletImportFormat()
print("Private key:", private_key)
Enter fullscreen mode Exit fullscreen mode

Tools for Working with BIP-39

To test mnemonics or convert phrases to private keys, use these tools:

Critical Warnings

1. Entropy Security

Always use cryptographically secure generators (e.g., Python’s secrets). Avoid homemade solutions.

2. Offline Generation

Tools like Ian Coleman’s BIP39 should run offline to eliminate leakage risks.

3. Never Share Your Seed Phrase

Your seed phrase equals your private key. Even open-source tools should be audited for backdoors.

Conclusion

BIP-39 bridges human-readable phrases and cryptographic keys. Understanding its mechanics helps build secure wallets and avoid critical mistakes. For testing, online tools can be used, but always store real assets in trusted hardware wallets.

Additional Resources:

Runner H image

An AI Agent That Handles Life, Not Just Work

From ordering flowers to booking your dinner — let Runner H turn your ideas into actions. No prompts, no hassle. Just outcomes.

Try for Free

Top comments (0)

Runner H image

Automate Your Workflow in Slack, Gmail, Notion & more

Runner H connects to your favorite tools and handles repetitive tasks for you. Save hours daily. Try it free while it’s in beta.

Try for Free

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay