Generate Private Key
Overview
Prerequisites
Code Example
import { PrivateKey, HD } from '@bsv/sdk'
// Method 1: Generate a random private key
function generateRandomKey() {
const privateKey = PrivateKey.fromRandom()
console.log('Private Key (WIF):', privateKey.toWif())
console.log('Private Key (Hex):', privateKey.toHex())
console.log('Public Key:', privateKey.toPublicKey().toHex())
console.log('Address:', privateKey.toPublicKey().toAddress())
return privateKey
}
// Method 2: Generate from seed phrase (HD wallet)
function generateFromSeed() {
// Generate a random mnemonic (12 or 24 words)
const mnemonic = HD.generateMnemonic(128) // 128 bits = 12 words, 256 bits = 24 words
console.log('Mnemonic:', mnemonic)
// Derive master key from mnemonic
const seed = HD.fromMnemonic(mnemonic)
const masterKey = PrivateKey.fromHex(seed.privateKey.toHex())
console.log('Master Private Key:', masterKey.toWif())
return { mnemonic, masterKey }
}
// Method 3: Import existing key
function importKey(wifOrHex: string) {
let privateKey: PrivateKey
try {
// Try WIF format first
privateKey = PrivateKey.fromWif(wifOrHex)
} catch {
// Try hex format
privateKey = PrivateKey.fromHex(wifOrHex)
}
console.log('Imported successfully')
console.log('Address:', privateKey.toPublicKey().toAddress())
return privateKey
}
// Method 4: Derive child keys (HD wallet)
function deriveChildKey(masterKey: PrivateKey, path: string) {
// Derive using BIP32 path (e.g., "m/44'/0'/0'/0/0")
const childKey = masterKey.deriveChild(/* derivation params */)
console.log('Child Key:', childKey.toWif())
console.log('Child Address:', childKey.toPublicKey().toAddress())
return childKey
}
// Export keys securely
function exportKey(privateKey: PrivateKey) {
return {
wif: privateKey.toWif(),
hex: privateKey.toHex(),
publicKey: privateKey.toPublicKey().toHex(),
address: privateKey.toPublicKey().toAddress()
}
}
// Example usage
console.log('=== Generate Random Key ===')
const randomKey = generateRandomKey()
console.log('\n=== Generate from Seed Phrase ===')
const { mnemonic, masterKey } = generateFromSeed()
console.log('\n=== Import Existing Key ===')
const importedKey = importKey('L1234...') // Replace with actual WIF
console.log('\n=== Export Key Info ===')
const keyInfo = exportKey(randomKey)
console.log(keyInfo)Explanation
Key Generation Methods
1. Random Key Generation
2. HD Wallet (Mnemonic)
3. Import Existing
4. Child Key Derivation
Key Formats
WIF (Wallet Import Format)
Hexadecimal
Public Key
Address
Security Best Practices
Common Use Cases
Development Testing
Production Wallet
Key Recovery
Related Components
Related Code Features
Learning Path References
Warning
Last updated
