# ecdsa - Create Private key and Bitcoin Address

I have the following code:

``````import binascii
import hashlib
from fastecdsa import keys, curve

# generate a private key for curve P256
priv_key = keys.gen_private_key(curve.secp256k1)
print (priv_key)
print ("______")

# get the public key corresponding to the private key we just generated
pub_key = keys.get_public_key(priv_key, curve.secp256k1)
print (pub_key)
``````

Which returns this:

``````68553277193328358088381091283586955911631072878513122367770244549235879948867
______
(defdba7ac050b698bc63134bbc495064b5a99125b023d8ae92d21ca43be77961,
68ed2abc9d36bae64947b94dd15864e3b2f7601b7009c5b9bae8a8775553fea0)
``````

The first one is the private key, and the second one is the public key. How can I convert these numbers to Bitcoin format?

I've tried with this script: https://github.com/bitcoinbook/bitcoinbook/blob/second_edition/code/ec-math.py

But doesn't work in Python 3.5

• Do you want to create the keys in WIF format ?? or do you want to create the associated address to those keys ??
– Matt
Dec 18, 2017 at 10:03
• Both. I'd like to have the private key in WIF and a Bitcoin Address. Dec 18, 2017 at 10:10

I solved the problem. This is the code:

``````import os
import hashlib
from hashlib import sha256

def ripemd160(x):
d = hashlib.new("ripemd160")
d.update(x)
return d

P = 2 ** 256 - 2 ** 32 - 2 ** 9 - 2 ** 8 - 2 ** 7 - 2 ** 6 - 2 ** 4 - 1
G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

xp, yp = p
xq, yq = q

if p == q:
l = pow(2 * yp % P, P - 2, P) * (3 * xp * xp) % P
else:
l = pow(xq - xp, P - 2, P) * (yq - yp) % P

xr = (l ** 2 - xp - xq) % P
yr = (l * xp - l * xr - yp) % P

return xr, yr

def point_mul(p, d):
n = p
q = None

for i in range(256):
if d & (1 << i):
if q is None:
q = n
else:

return q

def point_bytes(p):
x, y = p

return b"\x04" + x.to_bytes(32, "big") + y.to_bytes(32, "big")

def b58_encode(d):
out = ""
p = 0
x = 0

while d[0] == 0:
out += "1"
d = d[1:]

for i, v in enumerate(d[::-1]):
x += v * (256 ** i)

while x > 58 ** (p + 1):
p += 1

while p >= 0:
a, x = divmod(x, 58 ** p)
out += B58[a]
p -= 1

return out

q = point_mul(G, int.from_bytes(privkey, "big"))
hash160 = ripemd160(sha256(point_bytes(q)).digest()).digest()

wif = b"\x80" + privkey
checksum = sha256(sha256(wif).digest()).digest()[:4]
wif += checksum

wif = b58_encode(wif)

print("=========================")

from ecdsa import SigningKey, SECP256k1

sk = SigningKey.generate(curve=SECP256k1)
vk = sk.get_verifying_key()