use super::Kex;
use core::fmt;
use encoding::{Decode, Encode};
use ml_kem::{
Decapsulate, Encapsulate, Generate, KeyExport,
ml_kem_768::{DecapsulationKey, EncapsulationKey},
};
use rand_core::CryptoRng;
use sha2::{Digest, Sha256};
use x25519_dalek::{EphemeralSecret, PublicKey};
use zeroize::{Zeroize, Zeroizing};
#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Init {
mlkem: [u8; 1184],
x25519: [u8; 32],
}
#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Reply {
mlkem: [u8; 1088],
x25519: [u8; 32],
}
pub struct MlKem768X25519 {
mlkem: DecapsulationKey,
x25519: EphemeralSecret,
}
impl Kex for MlKem768X25519 {
const NAME: &'static str = "mlkem768x25519-sha256";
type Hash = Sha256;
type Init = Init;
type Reply = Reply;
type Secret = Secret;
type Error = Error;
fn start<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<(Self, Init), Error> {
let mlkem = DecapsulationKey::generate_from_rng(rng);
let x25519 = EphemeralSecret::random_from_rng(rng);
let init = Init {
mlkem: mlkem.encapsulation_key().to_bytes().into(),
x25519: PublicKey::from(&x25519).to_bytes(),
};
Ok((Self { mlkem, x25519 }, init))
}
fn respond<R: CryptoRng + ?Sized>(rng: &mut R, init: &Init) -> Result<(Reply, Secret), Error> {
let ek = EncapsulationKey::new((&init.mlkem).into())
.map_err(|_| Error::InvalidEncapsulationKey)?;
let (ciphertext, mlkem) = ek.encapsulate_with_rng(rng);
let mlkem = Zeroizing::new(mlkem);
let secret = EphemeralSecret::random_from_rng(rng);
let public = PublicKey::from(&secret);
let x25519 = agree(secret, init.x25519)?;
let reply = Reply {
mlkem: ciphertext.into(),
x25519: public.to_bytes(),
};
Ok((reply, Secret::combine(&mlkem, &x25519)))
}
fn finish(self, reply: &Reply) -> Result<Secret, Error> {
let x25519 = agree(self.x25519, reply.x25519)?;
let mlkem = Zeroizing::new(self.mlkem.decapsulate((&reply.mlkem).into()));
Ok(Secret::combine(&mlkem, &x25519))
}
}
impl fmt::Debug for MlKem768X25519 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MlKem768X25519").finish_non_exhaustive()
}
}
fn agree(secret: EphemeralSecret, peer: [u8; 32]) -> Result<x25519_dalek::SharedSecret, Error> {
let shared = secret.diffie_hellman(&PublicKey::from(peer));
if shared.was_contributory() {
Ok(shared)
} else {
Err(Error::NonContributory)
}
}
#[derive(Encode)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Secret([u8; 32]);
impl Secret {
fn combine(mlkem: &ml_kem::SharedKey, x25519: &x25519_dalek::SharedSecret) -> Self {
Self(
Sha256::new()
.chain_update(mlkem)
.chain_update(x25519.as_bytes())
.finalize()
.into(),
)
}
}
impl AsRef<[u8]> for Secret {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Secret").finish_non_exhaustive()
}
}
impl Drop for Secret {
fn drop(&mut self) {
self.0.zeroize();
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
InvalidEncapsulationKey,
NonContributory,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidEncapsulationKey => "invalid ML-KEM-768 encapsulation key",
Self::NonContributory => "non-contributory X25519 key exchange",
})
}
}
impl core::error::Error for Error {}