use std::fmt;
use crate::error::{Error, PeerMisbehaved};
use crate::msgs::enums::NamedGroup;
pub(crate) struct KeyExchange {
skxg: &'static SupportedKxGroup,
privkey: ring::agreement::EphemeralPrivateKey,
pub(crate) pubkey: ring::agreement::PublicKey,
}
impl KeyExchange {
pub(crate) fn choose(
name: NamedGroup,
supported: &[&'static SupportedKxGroup],
) -> Option<&'static SupportedKxGroup> {
supported
.iter()
.find(|skxg| skxg.name == name)
.cloned()
}
pub(crate) 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(crate) fn group(&self) -> NamedGroup {
self.skxg.name
}
pub(crate) fn complete<T>(self, peer: &[u8], f: impl FnOnce(&[u8]) -> 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(|_| PeerMisbehaved::InvalidKeyShare.into())
}
}
pub struct SupportedKxGroup {
pub name: NamedGroup,
agreement_algorithm: &'static ring::agreement::Algorithm,
}
impl fmt::Debug for SupportedKxGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.name.fmt(f)
}
}
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];