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 keyfromWif(wif: string): PrivateKey- Import from WIFfromHex(hex: string): PrivateKey- Import from hex stringfromString(str: string): PrivateKey- Import from hex or WIF string
Instance Methods
toWif(): string- Export to WIF formattoHex(): string- Export to hex stringtoPublicKey(): PublicKey- Derive public keysign(hash: number[]): Signature- Sign a hashsignMessage(message: string): Signature- Sign a messageverify(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:
Related Components
Public Keys - Derive public keys from private keys
Signatures - Work with ECDSA signatures
HD Wallets - Hierarchical deterministic key derivation
Transaction - Sign transactions with private keys
Code Examples
Complete Working Examples
See these code features for full implementations:
Example: Complete Key Management
Best Practices
Never hardcode private keys in source code
Use WIF format for human-readable key export
Always verify signatures after creating them
Use compressed keys (default) to save space
Implement proper key backup procedures
Test with testnet keys before using mainnet
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
