Dustin-Ray / capyCRYPT

An experimental high-performance cryptosystem.
MIT License
12 stars 1 forks source link

feature: serialization for keypair #16

Closed Dustin-Ray closed 5 months ago

Dustin-Ray commented 1 year ago

This is useful for the CLI/GUI to accept KeyPair objects to use in any asymmetric operations. Otherwise, we have to copy and paste public/private key values which is possible but cumbersome. Here's an example of where we ultimately want to end up after solving issue #21 using the capycrypt CLI to generate KeyPair objects:

capycrypt create_keypair --pw "testpassword" --owner "Dave Bowman" --curve "E448" --d 256 --output keypair.json

To achieve this, we only need to make a few changes: In cargo.toml: Add the following:

[dependencies]
serde = { version = "1.0", features = ["derive"] }

Then, in lib.rs where KeyPair is defined, we need to make the following modifcations:

use serde::Serialize;
use std::fmt;

#[derive(Serialize)]
struct KeyPair {
    owner: String,
    // ... other fields ...
}

impl fmt::Display for KeyPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", serde_json::to_string_pretty(&self).unwrap())
    }
}

impl KeyPair {
    // ... your new function and other methods ...

    pub fn save_to_file(&self, filename: &str) -> std::io::Result<()> {
        std::fs::write(filename, self.to_string())
    }
}

Finally, to write the KeyPair to a JSON, do the following:

let keypair = KeyPair {
    owner: "Frank Poole".to_string(),
    // ... initialize other fields ...
};

keypair.save_to_file("keypair.json").unwrap();

That's it for this issue!

Dustin-Ray commented 7 months ago

@omibo everything is in place for you to follow the above steps to get everything working