use crate::{
Algorithm, Error, Result,
public::{OpaquePublicKey, OpaquePublicKeyBytes},
};
use alloc::vec::Vec;
use core::fmt::{self, Debug};
use ctutils::{Choice, CtEq};
use encoding::{Decode, Decoder, Encode, Reader};
#[derive(Clone, Encode)]
pub struct OpaqueKeypair {
pub public: OpaquePublicKey,
pub private: OpaquePrivateKeyBytes,
}
impl OpaqueKeypair {
#[must_use]
pub fn new(private_key: Vec<u8>, public: OpaquePublicKey) -> Self {
Self {
public,
private: OpaquePrivateKeyBytes(private_key),
}
}
#[must_use]
pub fn algorithm(&self) -> Algorithm {
self.public.algorithm()
}
pub(super) fn decode_as(
reader: &mut Decoder<impl Reader>,
algorithm: Algorithm,
) -> Result<Self> {
let key = OpaqueKeypairBytes::decode(reader)?;
let public = OpaquePublicKey {
algorithm,
key: key.public,
};
Ok(Self {
public,
private: key.private,
})
}
}
impl CtEq for OpaqueKeypair {
fn ct_eq(&self, other: &Self) -> Choice {
Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
}
}
impl Debug for OpaqueKeypair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpaqueKeypair")
.field("public", &self.public)
.finish_non_exhaustive()
}
}
impl From<&OpaqueKeypair> for OpaquePublicKey {
fn from(keypair: &OpaqueKeypair) -> OpaquePublicKey {
keypair.public.clone()
}
}
#[derive(Decode)]
#[ssh(error = Error)]
pub struct OpaqueKeypairBytes {
pub public: OpaquePublicKeyBytes,
pub private: OpaquePrivateKeyBytes,
}
impl Debug for OpaqueKeypairBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpaqueKeypairBytes")
.field("public", &self.public)
.finish_non_exhaustive()
}
}
#[derive(Clone, Decode, Encode)]
#[ssh(error = Error)]
pub struct OpaquePrivateKeyBytes(Vec<u8>);
impl AsRef<[u8]> for OpaquePrivateKeyBytes {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl CtEq for OpaquePrivateKeyBytes {
fn ct_eq(&self, other: &Self) -> Choice {
self.as_ref().ct_eq(other.as_ref())
}
}
impl Debug for OpaquePrivateKeyBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpaquePrivateKeyBytes")
.finish_non_exhaustive()
}
}
impl From<Vec<u8>> for OpaquePrivateKeyBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}