keyPrivateKey

32-byte secp256k1 private key

32-byte secp256k1 private key used for signing transactions and ECDH key derivation.

Overview

PrivateKey is a specialized Bytes32 type representing a secp256k1 private key. It's used for transaction signing and deriving shared secrets via ECDH.

Definition

class PrivateKey(Bytes32):
    """32-byte secp256k1 private key."""

Inheritance

  • Inherits from Bytes32

  • Inherits all validation and construction methods from Bytes32

  • Always exactly 32 bytes

Construction

PrivateKey can be constructed from:

  • Hex strings (with or without "0x" prefix)

  • Raw bytes objects

  • Integer values

Parameters

Parameter
Type
Required
Description

val

bytes | str | int

Yes

The value to convert to a 32-byte private key

Raises

  • ValueError - If the resulting length is not exactly 32 bytes

Examples

From Hex String

Generate Random Private Key

Use with Client

Use with EIP-712 Signing

Security Considerations

  • Never log or print private keys - They provide full control over the account

  • Store securely - Use environment variables or secure key management systems

  • Use OS-provided randomness - os.urandom() for key generation

  • Avoid hardcoding - Never commit private keys to source control

Methods

from_hex_str()

Create a PrivateKey from a hex string, with or without a 0x prefix.

Parameters

Parameter
Type
Required
Description

hex_string

str

Yes

Hex-encoded private key, with or without "0x" prefix

Returns

  • PrivateKey — A new 32-byte private key instance

Example


to_0x_hex()

Inherited from Bytes32. Returns the hex string representation with "0x" prefix. Use carefully with private keys.

Properties

  • Immutable - Cannot be modified after construction

  • Hashable - Can be used as dictionary keys

  • 32 bytes - Always exactly 32 bytes

  • Compatible with bytes - Passes isinstance(x, bytes) checks

Notes

  • Used exclusively for secp256k1 curve operations

  • Compatible with eth_keys.PrivateKey after conversion: eth_keys.PrivateKey(bytes(private_key))

  • No validation is performed on the mathematical validity of the key (i.e., no check that 0 < key < n)

See Also

Last updated