I'm trying to learn how to create a bitcoin address by following this guide. If you scroll down, the first step, step 0, is to have a 256 bit (64 hex) long ECDSA key. I looked into Python Cryptography and am using the code below to test generating keys, but the saved key is always a long (180 characters) base 64 string.
I've tried to read the docs and look at the functions I'm calling on Github but I don't see where I can specify how long the key should be. On line 216 of this file, it says that the key size for secp256k1 is 256 bits by default. Does that mean I'm exporting it wrong?
Alternatively, I've considered generating a random hex string 64 characters long within the range of secp256k1,( 0x1
to 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140
), but I don't see where I can create a private key instance from a string or hex value
gentest.py
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import load_pem_private_key
def gen_key():
private_key = ec.generate_private_key(
ec.SECP256K1(), default_backend()
)
return private_key
def save_key(pk, filename):
pem = pk.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
with open(filename, 'wb') as pem_out:
pem_out.write(pem)
def load_key(filename):
with open(filename, 'rb') as pem_in:
pemlines = pem_in.read()
private_key = load_pem_private_key(pemlines, None, default_backend())
return private_key
if __name__ == '__main__':
pk = gen_key()
filename = 'privkey.pem'
save_key(pk, filename)
pk2 = load_key(filename)
privkey.pem
-----BEGIN PRIVATE KEY-----
MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgQGh8om7IuKSTW637ZQug
SZQHUTv/yQzmM+KxGi1bg0ehRANCAATALLpDeKtfHxEnrgazJUu2z2/esSfzF5bj
Z4B/IBBB9uYHyMtjY8hS926bpXiWql7y7MMZXDSDD/zYWELuJZ1U
-----END PRIVATE KEY-----