TeachMeBitcoin

Custom Python HASH160 Auditor

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

Custom Python HASH160 Auditor

In this final guide, we will build a Python script that calculates the HASH160 (Public Key Hash) of a raw public key. This is the exact process your wallet uses to prepare your funds for address encoding.

The HASH160 Auditor

import hashlib

def audit_hash160(pubkey_hex):
    print(f"--- Public Key Hash (HASH160) Audit ---")

    # 1. Convert hex string to raw bytes
    pubkey_bytes = bytes.fromhex(pubkey_hex)
    print(f"[*] Input Key:   {pubkey_hex}")
    print(f"[*] Input Size:  {len(pubkey_bytes)} bytes")

    # 2. Perform SHA-256
    sha256_result = hashlib.sha256(pubkey_bytes).digest()
    print(f"[*] SHA256 Hash: {sha256_result.hex()}")

    # 3. Perform RIPEMD-160
    # Note: On some systems, ripemd160 requires a specific library.
    # We use hashlib.new('ripemd160') which is compatible with OpenSSL.
    try:
        h160 = hashlib.new('ripemd160')
        h160.update(sha256_result)
        hash160_result = h160.hexdigest()

        print(f"[*] RIPEMD160:  {hash160_result}")
        print(f"[SUCCESS] HASH160 (20 bytes): {hash160_result}")

    except Exception as e:
        print(f"[ERROR] RIPEMD160 failed. Ensure your OpenSSL supports it.")
        print(f"Details: {e}")

# --- Simulation ---

# Case: A standard Compressed Public Key
# This corresponds to the first address in many wallets
test_pubkey = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
audit_hash160(test_pubkey)

How to Run the Auditor

  1. Ensure you have Python 3 installed.

  2. Copy the code into a file named hash160_auditor.py.

  3. Run it using python3 hash160_auditor.py.

Technical Takeaways

  1. Endianness: Bitcoin hashing is usually performed on "Big Endian" bytes as shown in the hex.

  2. Double Hashing: The reason for the SHA256 step is to ensure that even if RIPEMD160 has a weakness in the future, the SHA256 layer provides 256 bits of security against a "Collision" attack.

  3. Address Ready: The 20-byte output you see at the end is the exact data that gets encoded into a 1... or bc1... address.

Congratulations! You have completed the Public Key Hash (HASH160) module. You now understand the cryptographic fingerprinting that identifies every Bitcoin user.

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!