How to create Public Private Keypairs in Rust

Using secp256k1

Rust bindings for Pieter Wuille’s secp256k1 library, which is used for fast and accurate manipulation of ECDSA signatures on the secp256k1 curve. Such signatures are used extensively by the Bitcoin network and its derivatives.


This article shows the code used to create a public/private keypair using secp.generate_keypair in Rust.


use secp256k1::{PublicKey,SecretKey,rand::{rngs,SeedableRng}};
use anyhow::Result;

// Create a keypair using seed
pub fn create_keypair() ->Result <(SecretKey, PublicKey)>{
    let secp = secp256k1::Secp256k1::new();
    let mut rng = rngs::StdRng::seed_from_u64(89899);
    Ok(secp.generate_keypair(&mut rng))


fn main() -> Result<()>{
    let keypair = create_keypair().unwrap();
    println!("secret key = {}", keypair.0);
    println!("public key = {}", keypair.1);

Also, make sure you update your Cargo.toml file:



bitcoin = { version = "0.29.1", features = ["serde", "base64", "rand"] }

secp256k1 = { version = "0.20.3", features = ["rand"] }

anyhow = "1.0.47"
See the Private and Public keys being created with the code

For more on secp 256k1 see :

Important : in Production:

“The private key must remain secret at all times because revealing it to third parties is equivalent to giving them control over the bitcoins secured by that key. The private key must also be backed up and protected from accidental loss, because if it’s lost it cannot be recovered and the funds secured by it are forever lost, too.”
Andreas M. Antonopoulos, Mastering Bitcoin: Unlocking Digital Cryptocurrencies