Skip to content

Instantly share code, notes, and snippets.

@shirriff
Last active March 14, 2021 23:28
Show Gist options
  • Save shirriff/8e6b5650361bbe78a055 to your computer and use it in GitHub Desktop.
Save shirriff/8e6b5650361bbe78a055 to your computer and use it in GitHub Desktop.
Bitcoin address / key functions
def privateKeyToWif(key_hex):
return utils.base58CheckEncode(0x80, key_hex.decode('hex'))
def privateKeyToPublicKey(s):
sk = ecdsa.SigningKey.from_string(s.decode('hex'), curve=ecdsa.SECP256k1)
vk = sk.verifying_key
return ('\04' + sk.verifying_key.to_string()).encode('hex')
def pubKeyToAddr(s):
ripemd160 = hashlib.new('ripemd160')
ripemd160.update(hashlib.sha256(s.decode('hex')).digest())
return utils.base58CheckEncode(0, ripemd160.digest())
def keyToAddr(s):
return pubKeyToAddr(privateKeyToPublicKey(s))
# Warning: this random function is not cryptographically strong and is just for example
private_key = ''.join(['%x' % random.randrange(16) for x in range(0, 64)])
print keyUtils.privateKeyToWif(private_key)
print keyUtils.keyToAddr(private_key)
@kostaz
Copy link

kostaz commented Aug 2, 2014

Thanks a lot for a great article about bitcoins!!
Can you please post the full source code?
Thanks!

@Birdinc
Copy link

Birdinc commented Aug 5, 2014

Getting NameError: name 'keyUtils" is not defined. Please help.

@kostaz
Copy link

kostaz commented Aug 10, 2014

@bellaj
Copy link

bellaj commented Jan 31, 2016

@Birdinc
you should install the keyutils

pip install keyutils

@chainhead
Copy link

Just curious...how do you mean this statement? What is a strong alternative?

Warning: this random function is not cryptographically strong and is just for example

@visrian
Copy link

visrian commented Dec 20, 2017

This is probably really late but a strong alternative is the python secrets module, I believe (https://docs.python.org/3/library/secrets.html). You can use secrets.randbits(k) to generate a random k bit integer.

@spicyramen
Copy link

secrets is only supported in Python 3.x

@spicyramen
Copy link

import binascii
import os
import keyUtils

# Generate a 256 bits key
private_key = binascii.hexlify(os.urandom(32))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment