Check if Private Key Matches Address
Verifies if a private key matches a given address by deriving the public key from the private key and comparing it to the provided address.
Returns: boolean - true if the private key matches the address, false otherwise
const matches = await connection.checkAddressMatchesPrivateKey(address, privateKey);Parameters
address:Address- The address to verify againstprivateKey:Uint8Array- The private key in bytes format (array of numbers)
Examples
Check if a private key matches an address:
// Private key as array of numbers (from solana-keygen or environment)
const privateKey = new Uint8Array([/* private key bytes */]);
const address = "GkFTrgp8FcCgkCZeKreKKVHLyzGV6eqBpDHxRzg1brRn";
const matches = await connection.checkAddressMatchesPrivateKey(address, privateKey);
console.log(`Private key matches address: ${matches}`);Verify a wallet loaded from file:
// Load wallet from file
const wallet = await connection.loadWalletFromFile("path/to/keypair.json");
// Check if the loaded wallet's private key matches its address
const matches = await connection.checkAddressMatchesPrivateKey(
wallet.address,
wallet.privateKey
);
if (!matches) {
throw new Error("Wallet private key does not match its address");
}
console.log("Wallet verification successful");Validate environment variable private key:
// Load private key from environment
const privateKeyString = process.env.PRIVATE_KEY;
if (!privateKeyString) {
throw new Error("PRIVATE_KEY environment variable not set");
}
// Parse private key (assuming it's in the array format)
const privateKey = new Uint8Array(
privateKeyString.split(',').map(num => parseInt(num.trim()))
);
const expectedAddress = "GkFTrgp8FcCgkCZeKreKKVHLyzGV6eqBpDHxRzg1brRn";
const matches = await connection.checkAddressMatchesPrivateKey(expectedAddress, privateKey);
if (!matches) {
throw new Error("Environment private key does not match expected address");
}
console.log("Environment private key is valid");See also
- Check if address is a valid public key
- Load Wallet from Environment - Load wallets from environment variables
- Load Wallet from File - Load wallets from files
Last updated on