Skip to content

Instantly share code, notes, and snippets.

@nezza
Created April 24, 2018 13:46
Show Gist options
  • Save nezza/8d3f382eacc6738e324bb631d93ab132 to your computer and use it in GitHub Desktop.
Save nezza/8d3f382eacc6738e324bb631d93ab132 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Simple python code to show how easy it is to generate
# a Bitcoin address using Python.
# Does not store or export the private key!
# Implemented according to https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
import ecdsa
import hashlib
import base58
from ecdsa import SigningKey, SECP256k1
sk = SigningKey.generate(curve=SECP256k1)
vk = sk.get_verifying_key()
# Prepend 04 to public key, rest is 32 bytes X, 32 bytes Y
btc_vk = bytearray("\x04", "ascii") + vk.to_string()
# Generate SHA256 of public key
d = hashlib.sha256(btc_vk)
# Generate RIPEMD-160 hash of the SHA256 hash of the public key
h = hashlib.new('ripemd160')
h.update(d.digest())
# Add 00 for 'main network'
rh = bytearray("\x00", "ascii") + h.digest()
# Hash it twice
eh = hashlib.sha256(rh)
eh2 = hashlib.sha256(eh.digest())
# Last 4 bytes of the double hashed RIPEMD-160 hash (incl. prefix) are the checksum
checksum = eh2.digest()[:4]
# Add checksum to RIPEMD160 extended hash
rh += checksum
address = base58.b58encode(bytes(rh))
print ("Your bitcoin address: " + address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment