I've got a 32-bytes private key. I want to calculate the corresponding public key of this private key. How can I achieve this with Rust? I can't find such a function in solana-sdk
crate.
2 Answers
If you look at the keypair
module in solana-sdk
, you'll find keypair_from_seed
to do exactly what you want: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/fn.keypair_from_seed.html. With the keypair, you can get the public key:
let keypair = keypair_from_seed(<YOUR_PRIVATE_KEY_BYTES_HERE>).unwrap();
let public_key = keypair.pubkey();
-
Oh! At first glance I thought this is to create a
KeyPair
from a BIP32 seed. But the source code shows that it IS creating from a private key. Then why is this function namedkeypair_from_seed
? Besides, another functionkeypair_from_seed_and_derivation_path
is actually creatingKeyPair
from BIP32 seed (and a derivation path). The namekeypair_from_seed
is somewhat confusing.– YanCommented Oct 27 at 1:32 -
1I definitely agree with you there, I get confused about the function every time and have to look at the implementation to be sure what it does!– Jon CCommented Oct 28 at 9:56
To calculate the corresponding public key from a 32-byte private key in Rust, you won’t directly find this functionality in the solana-sdk
crate. However, Solana uses Ed25519 for cryptographic signing, which means you can use the popular Rust crate called ed25519-dalek
for this purpose.
- Install the
ed25519-dalek
crate: This crate provides all the necessary tools to generate a public key from a private key using theEd25519
signature scheme. - Use the
ed25519-dalek::Keypair::from_bytes
function to convert the 32-byte private key into a keypair, and then extract the public key from it.
In your Cargo.toml, include this dependency [dependencies] ed25519-dalek = "1.0"
try out this Rust code to convert a 32-byte private key into a corresponding public key
use ed25519_dalek::{Keypair, SecretKey, PublicKey};
use ed25519_dalek::Signer;
fn main() {
// Your 32-byte private key
let private_key_bytes: [u8; 32] = [/* Your 32-byte private key here */];
// Convert the private key bytes to a SecretKey object
let secret_key = SecretKey::from_bytes(&private_key_bytes).expect("Invalid private key");
// Generate the corresponding PublicKey
let public_key: PublicKey = (&secret_key).into();
// Print out the public key in bytes
println!("Public key: {:?}", public_key.to_bytes());
}
SecretKey is the 32-byte private key wrapped in the SecretKey type from ed25519-dalek.
PublicKey: The public key is derived from the private key by using (&secret_key).into()
, which automatically converts the secret key into its corresponding public key.
public_key.to_bytes()
gives you the byte representation of the public key.
-
3Also pro tip: answers like these can be generated using ChatGPT (in fact this one, is) Commented Oct 15 at 22:48