Skip to content

Instantly share code, notes, and snippets.

@vladimirfomene
Last active October 8, 2022 18:53
Show Gist options
  • Save vladimirfomene/b219fafef822d435a1230fa3513ca78f to your computer and use it in GitHub Desktop.
Save vladimirfomene/b219fafef822d435a1230fa3513ca78f to your computer and use it in GitHub Desktop.
import os
import hashlib
import elliptic
import base58
from binascii import unhexlify as decode_hex
from binascii import hexlify
# Constants
n = 115792089237316195423570985008687907852837564279074904382605163141518161494337
generator = (
55066263022277343669578718895168534326250603453777594175500187360389116729240,
32670510020758816978083085130507043184471273380659243275938904335757337482424
)
# Generates base58 bitcoin addresses from public key and prefix.
def generate_base58_format(payload, prefix):
hash256 = hashlib.sha256(decode_hex(prefix + payload)).hexdigest()
checksum = hashlib.sha256(decode_hex(hash256)).hexdigest()
checksum = checksum[:8]
formatted_key = prefix + payload + checksum
return base58.b58encode(decode_hex(formatted_key))
# 1. Generate randomness and hash it with sha256 algorithm.
private_key = None
while True:
entropy = os.urandom(256)
private_key = hashlib.sha256(entropy).hexdigest()
if int(private_key, 16) < n:
break
# 2. Calculate the Public key from the Private key with Elliptic Curve.
public_key = elliptic.EccMultiply(generator, int(private_key, 16))
# 3. Generate a compressed and uncompressed public key
uncompressed_public_key = "04" + hex(public_key[0])[2:] + hex(public_key[1])[2:]
prefix_compressed_public_key = "02" if public_key[1] % 2 == 0 else "03"
compressed_public_key = prefix_compressed_public_key + hex(public_key[0])[2:]
print("Uncompressed Public key: ", uncompressed_public_key)
print("Compressed Public key: ", compressed_public_key)
# 4. Generate bitcoin addresses from uncompressed and compressed publick key
print("Uncompressed Bitcoin Address: ", generate_base58_format(uncompressed_public_key, "00"))
print("Compressed Bitcoin Address: ", generate_base58_format(compressed_public_key, "00"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment