use crate::tls::rustls::error::Error;
use crate::tls::rustls::msgs::enums::NamedGroup;
pub struct KeyExchange {
pub skxg: &'static SupportedKxGroup,
pub privkey: ring::agreement::EphemeralPrivateKey,
pub pubkey: ring::agreement::PublicKey,
}
impl KeyExchange {
pub fn choose(
name: NamedGroup,
supported: &[&'static SupportedKxGroup],
) -> Option<&'static SupportedKxGroup> {
supported.iter().find(|skxg| skxg.name == name).cloned()
}
pub fn start(skxg: &'static SupportedKxGroup) -> Option<Self> {
let rng = ring::rand::SystemRandom::new();
let ours =
ring::agreement::EphemeralPrivateKey::generate(skxg.agreement_algorithm, &rng).ok()?;
let pubkey = ours.compute_public_key().ok()?;
Some(Self {
skxg,
privkey: ours,
pubkey,
})
}
pub fn group(&self) -> NamedGroup {
self.skxg.name
}
pub fn complete<T>(
self,
peer: &[u8],
f: impl FnOnce(&[u8]) -> Result<T, ()>,
) -> Result<T, Error> {
let peer_key = ring::agreement::UnparsedPublicKey::new(self.skxg.agreement_algorithm, peer);
ring::agreement::agree_ephemeral(self.privkey, &peer_key, (), f)
.map_err(|()| Error::PeerMisbehavedError("key agreement failed".to_string()))
}
}
#[derive(Debug)]
pub struct SupportedKxGroup {
pub name: NamedGroup,
pub agreement_algorithm: &'static ring::agreement::Algorithm,
}
pub static X25519: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::X25519,
agreement_algorithm: &ring::agreement::X25519,
};
pub static SECP256R1: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::secp256r1,
agreement_algorithm: &ring::agreement::ECDH_P256,
};
pub static SECP384R1: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::secp384r1,
agreement_algorithm: &ring::agreement::ECDH_P384,
};
pub static ALL_KX_GROUPS: [&SupportedKxGroup; 3] = [&X25519, &SECP256R1, &SECP384R1];