Skip to content

Instantly share code, notes, and snippets.

@svenpohl
Created August 28, 2022 16:17
Show Gist options
  • Save svenpohl/3be1cb8f31fcf307d34098fcd93aa45d to your computer and use it in GitHub Desktop.
Save svenpohl/3be1cb8f31fcf307d34098fcd93aa45d to your computer and use it in GitHub Desktop.
Python script for Bitcoin keypair generation
import os
import ecdsa
import binascii
import hashlib
import base58
import base64
#
# So. 28.aug.2022
# Tested with Python 3.10.6
#
var = os.urandom(32);
var = list(var);
#
# Add here some ramdom bytes
#
var[0 ] = 0x04;
# ...
var[3 ] = 0x54;
var[12] = 0x32;
# ...
var[31] = 0xb4;
var = bytes(var);
private_key = binascii.hexlify( var ).decode()
#print("private key: " + private_key)
# Create WIF format for private key (for wallet import)
extended_key = "80"+private_key
first_sha256 = hashlib.sha256(binascii.unhexlify(extended_key)).hexdigest()
second_sha256 = hashlib.sha256(binascii.unhexlify(first_sha256)).hexdigest()
# add checksum to end of extended key
final_key = extended_key+second_sha256[:8]
# Wallet Import Format = base 58 encoded final_key
WIF = base58.b58encode(binascii.unhexlify(final_key))
PRIVATE = WIF;
Private_key = bytes.fromhex(private_key)
signing_key = ecdsa.SigningKey.from_string(Private_key, curve = ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()
public_key2 = public_key.hex();
# ECDSA bitcoin Public Key
pubkey = ( public_key2 );
# See 'compressed form' at https://en.bitcoin.it/wiki/Protocol_documentation#Signatures
compress_pubkey = False
def hash160(hex_str):
sha = hashlib.sha256()
rip = hashlib.new('ripemd160')
sha.update(hex_str)
rip.update( sha.digest() )
#print ( "key_hash = \t" + rip.hexdigest() )
return rip.hexdigest() # .hexdigest() is hex ASCII
if (compress_pubkey):
if (ord(bytearray.fromhex(pubkey[-2:])) % 2 == 0):
pubkey_compressed = '02'
else:
pubkey_compressed = '03'
pubkey_compressed += pubkey[2:66]
hex_str = bytearray.fromhex(pubkey_compressed)
else:
hex_str = bytearray.fromhex(pubkey)
# Obtain key:
key_hash = '00' + hash160(hex_str)
# Obtain signature:
sha = hashlib.sha256()
sha.update( bytearray.fromhex(key_hash) )
checksum = sha.digest()
sha = hashlib.sha256()
sha.update(checksum)
checksum = sha.hexdigest()[0:8]
#print ( "checksum = \t" + sha.hexdigest() )
#print ( "key_hash + checksum = \t" + key_hash + ' ' + checksum )
#print ( "bitcoin address = \t" + base58.b58encode( bytes(bytearray.fromhex(key_hash + checksum)) ).decode('utf-8') )
PUBLIC = base58.b58encode( bytes(bytearray.fromhex(key_hash + checksum)) )
print("New keypair: ------------------------------------------------------------");
print("private key: [ "+ PRIVATE.decode('utf-8') +" ] ")
print("public key : [ "+ PUBLIC.decode('utf-8') +" ] ")
print("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment