libcrypto.keys

Private and public key objects with format conversions and caching.

class PrivateKey

PrivateKey(key=None, network="bitcoin")

key accepts int, 32 bytes, a 64-character hex string, a WIF string, or None (generate a secure random key). When a WIF is supplied, the detected network overrides the network argument.

Raises KeyError when the key is out of the valid range [1, N-1] or malformed.

Properties

Property Type Description
hex str 64-character hex private key.
bytes bytes 32-byte private key.
int int Integer private key.

Methods

Method Description
to_wif(compressed=True) -> str Export to Wallet Import Format for the key's network.
get_public_key(compressed=True) -> PublicKey Derive the public key (cached per compression flag).
PrivateKey.generate(network="bitcoin") -> PrivateKey Class method for a fresh secure key.
from libcrypto import PrivateKey

pk = PrivateKey("0000000000000000000000000000000000000000000000000000000000000001")
print(pk.hex)
print(pk.to_wif(compressed=True))
print(pk.get_public_key().hex)

KeyError here is a libcrypto-defined subclass of ValueError, not the Python built-in of the same name.

class PublicKey

PublicKey(key)

key is a 33-byte compressed key, a 65-byte uncompressed key, or the hex string form of either.

Properties and methods

Member Description
hex Hex encoding of the public key.
bytes Raw public key bytes.
compressed True when the key is 33 bytes.
get_address(address_type="p2pkh", network="bitcoin") -> str Generate an address directly from the key.
to_compressed() -> PublicKey Return the compressed form.
to_uncompressed() -> PublicKey Return the uncompressed form.
from libcrypto import PrivateKey, PublicKey

pub = PrivateKey(1).get_public_key(compressed=True)
print(pub.get_address("p2wpkh", "bitcoin"))
print(pub.to_uncompressed().hex)