Custom Python WIF Auditor
Custom Python WIF Auditor
In this final guide, we will build a Python script that converts a raw Hexadecimal Private Key into the Wallet Import Format (WIF). We will implement both the Legacy (5) and Compressed (K/L) logic.
The WIF Encoder
import hashlib
# Base58 Alphabet
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def encode_base58(b):
"""Encodes bytes into a Base58 string."""
n = int.from_bytes(b, 'big')
res = ""
while n \u003e 0:
n, r = divmod(n, 58)
res = ALPHABET[r] + res
# Handle leading zeros
pad = 0
for byte in b:
if byte == 0: pad += 1
else: break
return (ALPHABET[0] * pad) + res
def to_wif(hex_key, compressed=True):
print(f"--- WIF Encoding Audit ({'Compressed' if compressed else 'Legacy'}) ---")
# 1. Start with the Version Byte (0x80 for Mainnet)
payload = bytes.fromhex("80") + bytes.fromhex(hex_key)
# 2. Add Compression Flag if requested
if compressed:
payload += bytes.fromhex("01")
# 3. Calculate Checksum (Double SHA256)
sha1 = hashlib.sha256(payload).digest()
sha2 = hashlib.sha256(sha1).digest()
checksum = sha2[:4]
# 4. Final Payload
final_data = payload + checksum
# 5. Encode to Base58
wif_string = encode_base58(final_data)
print(f"[*] Raw Hex: {hex_key}")
print(f"[*] WIF: {wif_string}")
return wif_string
# --- Simulation ---
# A test private key
test_key = "1e994233519b6ec6655c8983995f3244b41b9976378c8a149c47e8c3725f778d"
# Generate Legacy WIF (Starts with 5)
to_wif(test_key, compressed=False)
print("\n--- Next Audit ---")
# Generate Compressed WIF (Starts with K or L)
to_wif(test_key, compressed=True)
How to Run the Auditor
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
wif_encoder.py. -
Run it using
python3 wif_encoder.py.
Technical Takeaways
-
Version Byte: If you change
80toef, the script will generate Testnet WIF keys (starting with9orc). -
Checksum: The 4 bytes at the end are what make your wallet say "Invalid Key" if you make a typo.
-
K vs L: Depending on the value of your private key, the
0x01suffix will push the Base58 result into either theKrange or theLrange.
Congratulations! You have completed the WIF Private Key (Encoding Secrets) module. You now understand how to safely transport the "Nuclear Codes" of your Bitcoin wealth.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: