#[cfg(feature = "alloc")]
use crate::buffer::SecretBytes;
use crate::{
buffer::WriteBuffer,
error::Error,
generic_array::{typenum::Unsigned, ArrayLength},
random::KeyMaterial,
};
pub trait KeyGen: Sized {
fn generate(rng: impl KeyMaterial) -> Result<Self, Error>;
#[cfg(feature = "getrandom")]
fn random() -> Result<Self, Error> {
Self::generate(crate::random::default_rng())
}
}
pub trait KeySecretBytes: KeyMeta {
fn from_secret_bytes(key: &[u8]) -> Result<Self, Error>
where
Self: Sized;
fn with_secret_bytes<O>(&self, f: impl FnOnce(Option<&[u8]>) -> O) -> O;
}
pub trait ToSecretBytes {
fn secret_bytes_length(&self) -> Result<usize, Error>;
fn write_secret_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error>;
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_secret_bytes(&self) -> Result<SecretBytes, Error> {
let mut buf = SecretBytes::with_capacity(128);
self.write_secret_bytes(&mut buf)?;
Ok(buf)
}
}
impl<K> ToSecretBytes for K
where
K: KeySecretBytes,
{
fn secret_bytes_length(&self) -> Result<usize, Error> {
Ok(<Self as KeyMeta>::KeySize::USIZE)
}
fn write_secret_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error> {
self.with_secret_bytes(|buf| {
if let Some(buf) = buf {
out.buffer_write(buf)
} else {
Err(err_msg!(MissingSecretKey))
}
})
}
}
pub trait KeyPublicBytes: KeypairMeta {
fn from_public_bytes(key: &[u8]) -> Result<Self, Error>
where
Self: Sized;
fn with_public_bytes<O>(&self, f: impl FnOnce(&[u8]) -> O) -> O;
}
pub trait ToPublicBytes {
fn public_bytes_length(&self) -> Result<usize, Error>;
fn write_public_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error>;
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_public_bytes(&self) -> Result<SecretBytes, Error> {
let mut buf = SecretBytes::with_capacity(128);
self.write_public_bytes(&mut buf)?;
Ok(buf)
}
}
impl<K> ToPublicBytes for K
where
K: KeyPublicBytes,
{
fn public_bytes_length(&self) -> Result<usize, Error> {
Ok(<Self as KeypairMeta>::PublicKeySize::USIZE)
}
fn write_public_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error> {
self.with_public_bytes(|buf| out.buffer_write(buf))
}
}
pub trait KeypairBytes {
fn from_keypair_bytes(key: &[u8]) -> Result<Self, Error>
where
Self: Sized;
fn with_keypair_bytes<O>(&self, f: impl FnOnce(Option<&[u8]>) -> O) -> O;
fn to_keypair_bytes_buffer<B: WriteBuffer>(&self, out: &mut B) -> Result<(), Error> {
self.with_keypair_bytes(|buf| {
if let Some(buf) = buf {
out.buffer_write(buf)
} else {
Err(err_msg!(MissingSecretKey))
}
})
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_keypair_bytes(&self) -> Result<SecretBytes, Error> {
let mut buf = SecretBytes::with_capacity(128);
self.to_keypair_bytes_buffer(&mut buf)?;
Ok(buf)
}
}
pub trait KeyMeta {
type KeySize: ArrayLength<u8>;
}
pub trait KeypairMeta: KeyMeta {
type PublicKeySize: ArrayLength<u8>;
type KeypairSize: ArrayLength<u8>;
}