-
-
Save shirriff/8e6b5650361bbe78a055 to your computer and use it in GitHub Desktop.
Bitcoin address / key functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Getting NameError: name 'keyUtils" is not defined. Please help.
I've found keyUtils.py here:
https://github.com/gferrin/bitcoin-code/blob/master/keyUtils.py
@Birdinc
you should install the keyutils
pip install keyutils
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
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.
secrets is only supported in Python 3.x
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
Thanks a lot for a great article about bitcoins!!
Can you please post the full source code?
Thanks!