diff --git a/README.md b/README.md index fdb0246..e099c20 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,21 @@ assert!(keys.public.len() == PUBLICKEYBYTES); assert!(keys.expose_secret().len() == SECRETKEYBYTES); ``` +### Restoring a Keypair +```rust +use pqc_dilithium::*; +use crate::params::{PUBLICKEYBYTES, SECRETKEYBYTES}; +use std::convert::TryInto; + +// Assuming you have public and secret key bytes +let public_bytes: Vec = vec![0u8; PUBLICKEYBYTES]; // Example byte vectors +let secret_bytes: Vec = vec![0u8; SECRETKEYBYTES]; + +// Restore the keypair +let restored_keypair = Keypair::new(public_bytes, secret_bytes); +assert!(restored_keypair.is_ok()); +``` + ### Signing ```rust let msg = "Hello".as_bytes(); diff --git a/src/api.rs b/src/api.rs index 3a29494..9f1dfda 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,3 +1,5 @@ +use std::convert::TryInto; + use crate::params::{PUBLICKEYBYTES, SECRETKEYBYTES, SIGNBYTES}; use crate::sign::*; @@ -16,10 +18,38 @@ impl std::fmt::Debug for Keypair { pub enum SignError { Input, + ConversionFailed, Verify, } impl Keypair { + /// Constructs a new `Keypair` from public and secret key bytes. + /// + /// # Errors + /// Returns `SignError::ConversionFailed` if the byte vectors are not of the expected length. + /// + /// # Example + /// ``` + /// # use pqc_dilithium::*; + /// # use crate::params::{PUBLICKEYBYTES, SECRETKEYBYTES}; + /// let public = vec![0u8; PUBLICKEYBYTES]; + /// let secret = vec![0u8; SECRETKEYBYTES]; + /// let keypair = Keypair::new(public, secret); + /// assert!(keypair.is_ok()); + /// ``` + pub fn new( + pub_bytes: Vec, + sec_bytes: Vec, + ) -> Result { + let public = pub_bytes + .try_into() + .map_err(|_| SignError::ConversionFailed)?; + let secret = sec_bytes + .try_into() + .map_err(|_| SignError::ConversionFailed)?; + Ok(Self { public, secret }) + } + /// Explicitly expose secret key /// ``` /// # use pqc_dilithium::*;