You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.5 KiB

//! RSA key serialisation
use super::*;
use crypto::{aes, rsa};
use eyre::eyre;
const PADDING_SZ: usize = 16;
fn new_padding() -> [u8; PADDING_SZ]
{
let mut buf = [0u8; PADDING_SZ];
getrandom::getrandom(&mut buf[..]).expect("Not enough entropy");
buf
}
/// An RSA key body
#[derive(Debug, Serialize, Deserialize)]
pub enum RsaBody
{
Public(RsaPublicBody),
Private(!)
}
impl RsaBody
{
#[cold] fn kind_name(&self) -> &'static str
{
match self {
Self::Public(_) => "Public",
Self::Private(_) => "Private",
}
}
/// Write this RSA key body to a PEM string
pub fn to_pem_string(&self) -> eyre::Result<String>
{
match self {
Self::Public(public) => public.to_pem_string(),
}
.wrap_err_with(|| eyre!("Failed to write RSA key body to PEM string"))
.with_section(|| self.kind_name().header("Kind was"))
}
/// Is this key a public part
pub fn is_public(&self) -> bool
{
if let Self::Public(_) = self {
true
} else {
false
}
}
/// Is this key a private part
pub fn is_private(&self) -> bool
{
if let Self::Private(_) = self {
true
} else {
false
}
}
/// Write RSA body to a binary stream
#[instrument(skip(out))]
pub async fn write_bytes<T: AsyncWrite+?Sized+Unpin>(&self, out: &mut T, ses_enc: &AesKey) -> Result<usize, eyre::Report>
{
match self {
Self::Public(public) => public.write_bytes(out, ses_enc).await,
}
.wrap_err_with(|| eyre!("Failed to write RSA key body to binary stream"))
.with_section(|| self.kind_name().header("Kind was"))
}
/// Write an RSA body to a text stream
#[instrument(skip(out))]
pub async fn write_text<T: AsyncWrite+Unpin+?Sized>(&self, out: &mut T, ses_enc: &AesKey) -> Result<usize, eyre::Report>
{
match self {
Self::Public(public) => public.write_text(out, ses_enc).await,
}
.wrap_err_with(|| eyre!("Failed to write RSA key body to text stream"))
.with_section(|| self.kind_name().header("Kind was"))
}
}
impl KeyBodySerialisable for RsaBody
{
#[inline] fn serialise_text<'a, 'b: 'a, T: AsyncWrite+Unpin+?Sized>(&'a self, out: &'b mut T, ses_enc: &'b AesKey) -> LocalBoxFuture<'a, Result<usize, eyre::Report>>
{
self.write_text(out, ses_enc).boxed_local()
}
#[inline] fn serialise_bytes<'a, 'b: 'a, T: AsyncWrite+Unpin+?Sized>(&'a self, out: &'b mut T, ses_enc: &'b AesKey) -> LocalBoxFuture<'a, Result<usize, eyre::Report>>
{
self.write_bytes(out, ses_enc).boxed_local()
}
}
mod public;
pub use public::*;