ssh-key 0.7.0-rc.13

Pure Rust implementation of SSH key file format decoders/encoders as described in RFC4251/RFC4253 and OpenSSH key formats, as well as "sshsig" signatures and certificates (including certificate validation and certificate authority support), with further support for the `authorized_keys` and `known_hosts` file formats.
Documentation
//! Keys for the ML-DSA-44 and Ed25519 composite signature algorithm.

use crate::{
    Algorithm, Error, Result,
    composite::{PublicKeyBytes, derive_public_key},
    private::Ed25519PrivateKey,
    public::Ed25519PublicKey,
};
use core::fmt;
use ctutils::{Choice, CtEq};
use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
use ml_dsa::{EncodedSignature, EncodedVerifyingKey, MlDsa44, Seed};
use rand_core::CryptoRng;
use signature::{Keypair, KeypairRef};
use zeroize::Zeroizing;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

/// MLDSA44-Ed25519-SHA512 composite public key.
///
/// Encoded as the 1312-byte ML-DSA public key followed by the 32-byte Ed25519 public key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct MlDsa44Ed25519PublicKey {
    pub(super) mldsa: PublicKeyBytes<MlDsa44>,
    ed25519: Ed25519PublicKey,
}

impl MlDsa44Ed25519PublicKey {
    /// Size of an encoded composite public key in bytes.
    pub const BYTE_SIZE: usize =
        size_of::<EncodedVerifyingKey<MlDsa44>>() + Ed25519PublicKey::BYTE_SIZE;

    /// Size of an encoded composite signature in bytes.
    pub const SIGNATURE_SIZE: usize =
        size_of::<EncodedSignature<MlDsa44>>() + ed25519_dalek::SIGNATURE_LENGTH;

    /// Parse the concatenated ML-DSA and Ed25519 public keys.
    ///
    /// # Errors
    /// Returns [`encoding::Error::Length`] if the input has the wrong length.
    pub fn new(key: impl AsRef<[u8]>) -> Result<Self> {
        Self::decode_bytes(&mut Decoder::new(key.as_ref())?)
    }

    /// Get the SSH algorithm for this public key.
    #[must_use]
    pub fn algorithm(&self) -> Algorithm {
        Algorithm::MlDsa44Ed25519
    }

    /// Borrow the Ed25519 component. Component keys must be used exclusively in this composite.
    #[must_use]
    pub fn ed25519(&self) -> &Ed25519PublicKey {
        &self.ed25519
    }

    /// Get the concatenated encoding of both public keys.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(Self::BYTE_SIZE);
        bytes.extend_from_slice(self.mldsa.as_slice());
        bytes.extend_from_slice(self.ed25519.as_ref());
        bytes
    }

    fn decode_bytes(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        if reader.remaining_len() != Self::BYTE_SIZE {
            return Err(encoding::Error::Length.into());
        }
        let mut mldsa = PublicKeyBytes::<MlDsa44>::default();
        reader.read(mldsa.as_mut_slice())?;
        let ed25519 = Ed25519PublicKey(Decode::decode(reader)?);
        Ok(Self { mldsa, ed25519 })
    }
}

impl TryFrom<&[u8]> for MlDsa44Ed25519PublicKey {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        Self::new(bytes)
    }
}

impl Decode for MlDsa44Ed25519PublicKey {
    type Error = Error;

    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        reader.read_prefixed(Self::decode_bytes)
    }
}

impl Encode for MlDsa44Ed25519PublicKey {
    fn encoded_len(&self) -> encoding::Result<usize> {
        Ok(4 + Self::BYTE_SIZE)
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        Self::BYTE_SIZE.encode(writer)?;
        writer.write(self.mldsa.as_slice())?;
        writer.write(self.ed25519.as_ref())
    }
}

impl fmt::Display for MlDsa44Ed25519PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.mldsa.as_slice() {
            write!(f, "{byte:02x}")?;
        }
        write!(f, "{:x}", self.ed25519)
    }
}

/// MLDSA44-Ed25519-SHA512 composite private key.
///
/// Stores the ML-DSA seed followed by the Ed25519 seed. Each is 32 bytes.
#[derive(Clone)]
pub struct MlDsa44Ed25519PrivateKey {
    pub(super) mldsa: Zeroizing<Seed>,
    ed25519: Ed25519PrivateKey,
}

impl MlDsa44Ed25519PrivateKey {
    /// Size of an encoded composite private key in bytes.
    pub const BYTE_SIZE: usize = size_of::<Seed>() + Ed25519PrivateKey::BYTE_SIZE;

    /// Generate fresh seeds for both components.
    ///
    /// # Errors
    /// Propagates errors from [`Self::from_bytes`].
    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
        let mut seed = Zeroizing::new([0u8; Self::BYTE_SIZE]);
        rng.fill_bytes(seed.as_mut_slice());
        Self::from_bytes(&seed)
    }

    /// Parse the two concatenated seeds. Both must be dedicated to this composite key.
    ///
    /// # Errors
    /// Returns [`encoding::Error::Length`] if either seed has the wrong length.
    /// The fixed-size input guarantees the required lengths.
    pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Result<Self> {
        let (mldsa, ed25519) = bytes.split_at(size_of::<Seed>());
        Ok(Self {
            mldsa: Zeroizing::new(mldsa.try_into()?),
            ed25519: ed25519.try_into()?,
        })
    }

    /// Get the concatenated encoding of both private seeds.
    #[must_use]
    pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
        let mut bytes = [0u8; Self::BYTE_SIZE];
        let (mldsa, ed25519) = bytes.split_at_mut(size_of::<Seed>());
        mldsa.copy_from_slice(self.mldsa.as_slice());
        ed25519.copy_from_slice(self.ed25519.as_ref());
        bytes
    }

    /// Borrow the Ed25519 component. Component keys must be used exclusively in this composite.
    #[must_use]
    pub fn ed25519(&self) -> &Ed25519PrivateKey {
        &self.ed25519
    }

    /// Derive the composite public key from both seeds.
    ///
    /// # Errors
    /// Key derivation for these fixed-size seeds is infallible.
    pub fn public_key(&self) -> Result<MlDsa44Ed25519PublicKey> {
        Ok(MlDsa44Ed25519PublicKey {
            mldsa: derive_public_key::<MlDsa44>(&self.mldsa),
            ed25519: Ed25519PublicKey::from(&self.ed25519),
        })
    }

    /// Private key material used for the deterministic checkint hash.
    pub(crate) fn checkint_bytes(&self) -> &[u8] {
        self.mldsa.as_slice()
    }
}

impl TryFrom<&[u8]> for MlDsa44Ed25519PrivateKey {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        Self::from_bytes(bytes.try_into()?)
    }
}

impl CtEq for MlDsa44Ed25519PrivateKey {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.mldsa.as_slice().ct_eq(other.mldsa.as_slice()) & self.ed25519.ct_eq(&other.ed25519)
    }
}

impl Eq for MlDsa44Ed25519PrivateKey {}

impl PartialEq for MlDsa44Ed25519PrivateKey {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

impl fmt::Debug for MlDsa44Ed25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MlDsa44Ed25519PrivateKey")
            .finish_non_exhaustive()
    }
}

/// MLDSA44-Ed25519-SHA512 composite keypair.
///
/// OpenSSH encodes the public key and the concatenated private seeds as two SSH strings.
#[derive(Clone)]
pub struct MlDsa44Ed25519Keypair {
    /// Public key.
    pub public: MlDsa44Ed25519PublicKey,
    /// Private key.
    pub private: MlDsa44Ed25519PrivateKey,
}

impl MlDsa44Ed25519Keypair {
    /// Generate a random composite keypair.
    ///
    /// # Errors
    /// Propagates errors from private key generation and public key derivation.
    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<Self> {
        Self::new(MlDsa44Ed25519PrivateKey::random(rng)?)
    }

    /// Derive a keypair from its two dedicated component seeds, ML-DSA first.
    ///
    /// # Errors
    /// Propagates errors from private key decoding and public key derivation.
    pub fn from_seed(seed: &[u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]) -> Result<Self> {
        Self::new(MlDsa44Ed25519PrivateKey::from_bytes(seed)?)
    }

    /// Get the SSH algorithm for this keypair.
    #[must_use]
    pub fn algorithm(&self) -> Algorithm {
        self.public.algorithm()
    }

    fn new(private: MlDsa44Ed25519PrivateKey) -> Result<Self> {
        Ok(Self {
            public: private.public_key()?,
            private,
        })
    }
}

impl AsRef<MlDsa44Ed25519PublicKey> for MlDsa44Ed25519Keypair {
    fn as_ref(&self) -> &MlDsa44Ed25519PublicKey {
        &self.public
    }
}

impl KeypairRef for MlDsa44Ed25519Keypair {
    type VerifyingKey = MlDsa44Ed25519PublicKey;
}

impl CtEq for MlDsa44Ed25519Keypair {
    fn ct_eq(&self, other: &Self) -> Choice {
        Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
    }
}

impl Eq for MlDsa44Ed25519Keypair {}

impl PartialEq for MlDsa44Ed25519Keypair {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

impl Decode for MlDsa44Ed25519Keypair {
    type Error = Error;

    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
        let public = MlDsa44Ed25519PublicKey::decode(reader)?;
        let mut seed = Zeroizing::new([0u8; MlDsa44Ed25519PrivateKey::BYTE_SIZE]);
        let private =
            MlDsa44Ed25519PrivateKey::try_from(reader.read_string_bytes(seed.as_mut_slice())?)?;
        if private.public_key()? != public {
            return Err(Error::PublicKey);
        }
        Ok(Self { public, private })
    }
}

impl Encode for MlDsa44Ed25519Keypair {
    fn encoded_len(&self) -> encoding::Result<usize> {
        [
            self.public.encoded_len()?,
            4,
            MlDsa44Ed25519PrivateKey::BYTE_SIZE,
        ]
        .checked_sum()
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        self.public.encode(writer)?;
        MlDsa44Ed25519PrivateKey::BYTE_SIZE.encode(writer)?;
        writer.write(self.private.mldsa.as_slice())?;
        writer.write(self.private.ed25519.as_ref())
    }
}

impl fmt::Debug for MlDsa44Ed25519Keypair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MlDsa44Ed25519Keypair")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

impl From<MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
    fn from(keypair: MlDsa44Ed25519Keypair) -> Self {
        keypair.public
    }
}

impl From<&MlDsa44Ed25519Keypair> for MlDsa44Ed25519PublicKey {
    fn from(keypair: &MlDsa44Ed25519Keypair) -> Self {
        keypair.verifying_key()
    }
}