Jan 10, 2024

How to use DALEK to generate key pair and verify signature?

ED-2559

Steps

  • Setup your Rust environment
  • Add ed25519-dalek to your Cargo.toml
  • Generate Key pair
  • Sign the Message
  • Verify the Message
  • Complete code

I. Setup your RUST environment

cargo new dalek_example
cd dalek_example

II. Add crates: ed25519-dalek and rand as a dependency

[dependencies]
ed25519-dalek = "1.0.1"
rand = "0.7.0"
base64 = "0.21"

III. Generate keypair, sign message, and verify signature

extern crate rand;
extern crate ed25519_dalek;
extern crate base64;

use ed25519_dalek::{Keypair, Signature, Signer, Verifier};
use rand::rngs::OsRng;
use base64::{engine::general_purpose, Engine};

fn main() {
    // Generate a key pair
    let mut csprng = OsRng{};
    let keypair: Keypair = Keypair::generate(&mut csprng);

    // The message to sign
    let message: &[u8] = b"This is a test message";

    // Sign the message
    let signature: Signature = keypair.sign(message);

    // Verify the signature
    match keypair.public.verify(message, &signature) {
        Ok(_) => println!("Signature is valid!"),
        Err(_) => println!("Signature is invalid!"),
    }

    // Serialize to Base64
    let public_key_base64 = general_purpose::STANDARD.encode(keypair.public.as_bytes());
    let secret_key_base64 = general_purpose::STANDARD.encode(keypair.secret.as_bytes());
    let signature_base64 = general_purpose::STANDARD.encode(signature.to_bytes());

    // Print the keys and signature in Base64
    println!("Public Key (Base64): {}", public_key_base64);
    println!("Private Key (Base64): {}", secret_key_base64);
    println!("Signature (Base64): {}", signature_base64);
    println!("Message: {}", String::from_utf8_lossy(message));
}

You can find complete code at:

https://github.com/Nepalichhoro/Cryptography_in_Rust/tree/main/dalek_example


Thanks for reading! If you want to see future content, you can follow me on Twitter or get connected over at LinkedIn.


Support My Content

If you find my content helpful, consider supporting a humanitarian cause (building homes for elderly people in rural Terai region of Nepal) that I am planning with your donation:

Ethereum (ETH)

0xB62409A5B227D2aE7D8C66fdaA5EEf4eB4E37959

Thank you for your support!