use zeroize::Zeroizing;
use crate::error::{JoseError, Result};
use crate::jwk::Jwk;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AgreementCurve {
P256,
P384,
P521,
X25519,
}
impl AgreementCurve {
#[must_use]
pub fn as_crv_str(self) -> &'static str {
match self {
Self::P256 => "P-256",
Self::P384 => "P-384",
Self::P521 => "P-521",
Self::X25519 => "X25519",
}
}
#[must_use]
pub fn coord_len(self) -> usize {
match self {
Self::P256 => 32,
Self::P384 => 48,
Self::P521 => 66,
Self::X25519 => 32,
}
}
fn kryptering_curve(self) -> Option<kryptering::EcCurve> {
match self {
Self::P256 => Some(kryptering::EcCurve::P256),
Self::P384 => Some(kryptering::EcCurve::P384),
Self::P521 => Some(kryptering::EcCurve::P521),
Self::X25519 => None,
}
}
fn from_jwk(jwk: &Jwk) -> Result<Self> {
match (jwk.kty.as_str(), jwk.crv.as_deref()) {
("EC", Some("P-256")) => Ok(Self::P256),
("EC", Some("P-384")) => Ok(Self::P384),
("EC", Some("P-521")) => Ok(Self::P521),
("OKP", Some("X25519")) => Ok(Self::X25519),
("OKP", Some("X448")) => Err(JoseError::Key(
"X448 is a key-agreement curve but cannot perform key agreement with this \
backend; X25519 and the P-curves can"
.into(),
)),
("OKP", Some(other)) => Err(JoseError::Key(format!(
"OKP curve {other} is a signing curve, not a key-agreement curve"
))),
("EC", Some(other)) => Err(JoseError::Key(format!(
"EC curve {other} is not supported for key agreement by this backend"
))),
("EC", None) => Err(JoseError::Key("missing crv for EC key".into())),
(kty, _) => Err(JoseError::Key(format!(
"kty {kty} cannot perform key agreement; expected EC or OKP"
))),
}
}
}
const AGREEMENT_ALGS: &[&str] = &[
"ECDH-ES",
"ECDH-ES+A128KW",
"ECDH-ES+A192KW",
"ECDH-ES+A256KW",
];
#[derive(Debug, Clone)]
pub struct AgreementKey {
key: kryptering::SoftwareKey,
curve: AgreementCurve,
public: Vec<u8>,
}
impl AgreementKey {
#[must_use]
pub fn curve(&self) -> AgreementCurve {
self.curve
}
#[must_use]
pub fn public_bytes(&self) -> &[u8] {
&self.public
}
pub fn derive_key(
&self,
peer: &PeerKey,
alg_id: &str,
apu: Option<&str>,
apv: Option<&str>,
key_len: usize,
) -> Result<Zeroizing<Vec<u8>>> {
let z = self.agree(peer)?;
crate::jwe::internal::concat_kdf(z.as_slice(), key_len, alg_id, apu, apv)
}
pub fn agree(&self, peer: &PeerKey) -> Result<Zeroizing<Vec<u8>>> {
if self.curve != peer.curve() {
return Err(JoseError::Key(format!(
"key agreement curve mismatch: own key is {:?}, peer is {:?}",
self.curve,
peer.curve()
)));
}
let z = match self.curve.kryptering_curve() {
Some(ec_curve) => {
kryptering::software::keyagreement::agree(ec_curve, &peer.encoded, &self.key)
}
None => kryptering::software::keyagreement::agree_x25519(&peer.encoded, &self.key),
}
.map_err(JoseError::Crypto)?;
if z.len() != self.curve.coord_len() {
return Err(JoseError::Key(format!(
"key agreement returned {} bytes, expected {} for {:?}",
z.len(),
self.curve.coord_len(),
self.curve
)));
}
Ok(Zeroizing::new(z))
}
}
#[derive(Debug, Clone)]
pub struct PeerKey {
curve: AgreementCurve,
encoded: Vec<u8>,
}
impl PeerKey {
#[must_use]
pub fn curve(&self) -> AgreementCurve {
self.curve
}
#[must_use]
pub fn public_bytes(&self) -> &[u8] {
&self.encoded
}
}
pub(crate) fn generate_ephemeral(curve: AgreementCurve) -> Result<Jwk> {
match curve {
AgreementCurve::X25519 => crate::jwk::generate_x25519(),
other => crate::jwk::generate_ec(other.as_crv_str()),
}
}
pub fn agreement_key(jwk: &Jwk) -> Result<AgreementKey> {
let curve = AgreementCurve::from_jwk(jwk)?;
jwk.check_op(crate::jwk::JwkOp::DeriveKey)?;
if let Some(alg) = jwk.alg.as_deref() {
if !AGREEMENT_ALGS.contains(&alg) {
return Err(JoseError::Key(format!(
"JWK alg {alg} is not a key-agreement algorithm; this key cannot be used for \
ECDH-ES (supported: {})",
AGREEMENT_ALGS.join(", ")
)));
}
}
let key = crate::jwk::jwk_to_software_key(jwk)?;
if !key.has_private_key() {
return Err(JoseError::Key(
"key agreement requires the private scalar; a public-only JWK is a peer key, not \
an agreement key"
.into(),
));
}
let public = encode_public(curve, jwk)?;
Ok(AgreementKey { key, curve, public })
}
pub fn peer_key(jwk: &Jwk) -> Result<PeerKey> {
let curve = AgreementCurve::from_jwk(jwk)?;
if jwk.d.is_some() {
return Err(JoseError::Key(
"a peer key must carry public material only; the JWK has a private component `d`"
.into(),
));
}
crate::jwk::jwk_to_software_key(jwk)?;
let encoded = encode_public(curve, jwk)?;
Ok(PeerKey { curve, encoded })
}
fn encode_public(curve: AgreementCurve, jwk: &Jwk) -> Result<Vec<u8>> {
if curve == AgreementCurve::X25519 {
return coordinate(jwk, "x", curve.coord_len());
}
let coord_len = curve.coord_len();
let x = coordinate(jwk, "x", coord_len)?;
let y = coordinate(jwk, "y", coord_len)?;
let mut point = Vec::with_capacity(1 + 2 * coord_len);
point.push(0x04);
point.extend_from_slice(&x);
point.extend_from_slice(&y);
Ok(point)
}
fn coordinate(jwk: &Jwk, name: &str, coord_len: usize) -> Result<Vec<u8>> {
let value = match name {
"x" => jwk.x.as_deref(),
"y" => jwk.y.as_deref(),
_ => None,
}
.ok_or_else(|| JoseError::Key(format!("missing {name} for an agreement key")))?;
let bytes = crate::base64url::decode(value)?;
if bytes.len() > coord_len {
return Err(JoseError::Key(format!(
"{name} is {} octets, longer than the {coord_len}-octet field",
bytes.len()
)));
}
let mut padded = vec![0u8; coord_len - bytes.len()];
padded.extend_from_slice(&bytes);
Ok(padded)
}