Private Keys

Overview

The PrivateKey class is a fundamental component of the BSV TypeScript SDK that handles elliptic curve private key operations. Private keys are 256-bit numbers used to sign transactions and prove ownership of Bitcoin.

Purpose

This component provides:

  • Private key generation from random data or WIF (Wallet Import Format)

  • DER signature creation and verification

  • Public key derivation

  • WIF encoding/decoding

  • Message signing capabilities

Basic Usage

Generating a New Private Key

import { PrivateKey } from '@bsv/sdk'

// Generate a random private key
const privateKey = PrivateKey.fromRandom()

// Get the private key as hex string
const hex = privateKey.toHex()

// Get WIF (Wallet Import Format) representation
const wif = privateKey.toWif()

Creating from Existing Key Material

Key Features

1. Signature Generation

Create DER-encoded signatures for transaction signing:

2. Public Key Derivation

Derive the corresponding public key:

3. WIF Encoding/Decoding

WIF (Wallet Import Format) provides a compact representation:

4. Message Signing

Sign arbitrary messages for authentication:

API Reference

Constructor

  • number: The private key as a BigNumber (optional)

  • compressed: Whether to use compressed format (default: true)

Static Methods

  • fromRandom(): PrivateKey - Generate random private key

  • fromWif(wif: string): PrivateKey - Import from WIF

  • fromHex(hex: string): PrivateKey - Import from hex string

  • fromString(str: string): PrivateKey - Import from hex or WIF string

Instance Methods

  • toWif(): string - Export to WIF format

  • toHex(): string - Export to hex string

  • toPublicKey(): PublicKey - Derive public key

  • sign(hash: number[]): Signature - Sign a hash

  • signMessage(message: string): Signature - Sign a message

  • verify(hash: number[], signature: Signature): boolean - Verify signature

Common Patterns

Deterministic Key Generation

Secure Key Storage

Transaction Signing Pattern

Security Considerations

1. Key Generation

Always use cryptographically secure random number generation:

2. Key Storage

Never store private keys in plain text:

3. Memory Management

Clear sensitive data when no longer needed:

Code Examples

Complete Working Examples

See these code features for full implementations:

Example: Complete Key Management

Best Practices

  1. Never hardcode private keys in source code

  2. Use WIF format for human-readable key export

  3. Always verify signatures after creating them

  4. Use compressed keys (default) to save space

  5. Implement proper key backup procedures

  6. Test with testnet keys before using mainnet

  7. Use HD wallets (BRC-42) for multiple addresses

Troubleshooting

Common Issues

Invalid WIF string:

Signature verification fails:

Further Reading

Status

Complete - Production ready

Last updated