ecqv 0.1.0

SEC 4 ECQV implicit certificates on P-256: reconstruct a public key from a certificate and the issuer's key, with no signature to carry
Documentation
//! The unvalidated public key and the hazard that makes it a type.

#[cfg(feature = "ecdsa")]
use crate::error::Error;

/// A public key reconstructed from a certificate, before anything has proven
/// the certificate is real.
///
/// Reconstruction always succeeds, even for a forged certificate. The name is
/// the warning: this key is unvalidated, and there is no way to validate it
/// except by using it.
///
/// The only operations that succeed on this type are ones that prove the key
/// works:
///
/// - [`verify_signature`](Self::verify_signature) verifies a signature that the
///   certificate holder claims to have produced. If it returns `Ok`, the
///   certificate was really issued by the CA public key you reconstructed
///   against, and the message is authentic. This is the only operation that
///   proves the certificate locally and immediately.
/// - [`into_public_key_unchecked`](Self::into_public_key_unchecked) hands back
///   the bare key. READ THIS BEFORE CALLING IT: using the key for key agreement
///   (e.g. ECDH) does NOT validate the certificate. A forged certificate
///   yields the wrong point, ECDH against it produces a shared secret the peer
///   does not share, and nothing fails at the ECDH call. Validation is deferred
///   to whatever authenticates the resulting channel, and if nothing does, the
///   certificate is never validated at all.
///
/// The `_unchecked` suffix is deliberate and greppable: an auditor can find
/// every place a bare key is taken out.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "ecdsa")] {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use ecqv::{CertificateAuthority, CertificateRequest, UnvalidatedPublicKey};
/// use p256::ecdsa::{Signature, SigningKey, signature::Signer};
/// use rand::rng;
///
/// # let mut rng = rng();
/// # let ca = CertificateAuthority::random(&mut rng);
/// # let ca_public = ca.public_key();
/// # let request = CertificateRequest::random(b"device-7", b"", &mut rng);
/// # let issued = ca.issue_certificate(&request)?;
/// # let holder = request.finalize(&issued.certificate, &issued.private_reconstruction_value, &ca_public)?;
/// # let signing_key = SigningKey::from(&holder);
/// # let message = b"hello, road";
/// # let signature: Signature = signing_key.sign(message);
/// // A certificate arrived over the wire, and we hold the CA public key.
/// // Reconstruction ALWAYS succeeds, even for a forged certificate:
/// let unvalidated: UnvalidatedPublicKey = issued.certificate.reconstruct(&ca_public)?;
///
/// // Nothing has been proven yet. The certificate is validated exactly once,
/// // by using the key it claims: if the holder's signature verifies, the
/// // certificate was really issued by ca_public and the message is authentic.
/// unvalidated.verify_signature(message, &signature)?;
///
/// // For a non-signature use of the bare key (for example ECDH), say so
/// // explicitly. Note: using the key for key agreement does NOT validate the
/// // certificate; a forged certificate yields the wrong point, and the failure
/// // surfaces only when the channel built from the shared secret is checked.
/// let _bare_public_key = unvalidated.into_public_key_unchecked();
/// # Ok(())
/// # }
/// # }
/// ```
pub struct UnvalidatedPublicKey {
    pub(crate) point: p256::AffinePoint,
}

impl UnvalidatedPublicKey {
    /// Prove the certificate by verifying a signature the holder produced.
    ///
    /// The reconstructed key is used to verify `signature` over `message`
    /// (ECDSA P-256). If this succeeds, the certificate was issued by the CA
    /// public key used in reconstruction and the message is authentic.
    ///
    /// This is the load-bearing validation step for the relying party. It is
    /// the ONLY operation that proves the certificate locally and immediately;
    /// everything else that uses the key defers validation somewhere else.
    #[cfg(feature = "ecdsa")]
    pub fn verify_signature(
        &self,
        message: &[u8],
        signature: &p256::ecdsa::Signature,
    ) -> Result<(), Error> {
        use p256::ecdsa::signature::Verifier;
        let verifying_key = p256::ecdsa::VerifyingKey::from_affine(self.point)
            .map_err(|_| Error::InvalidReconstructionPoint)?;
        verifying_key
            .verify(message, signature)
            .map_err(|_| Error::SignatureVerification)
    }

    /// Take out the bare public key.
    ///
    /// Use this only when you cannot use [`verify_signature`](Self::verify_signature),
    /// for example to do ECDH. It does NOT validate the certificate: with a
    /// forged certificate it returns the wrong point, and the failure surfaces
    /// only if and when whatever you build with the key is later checked.
    /// Validation is deferred to the layer that authenticates the resulting
    /// channel; if no such layer exists, the certificate is never validated.
    pub fn into_public_key_unchecked(self) -> p256::PublicKey {
        p256::PublicKey::from_affine(self.point)
            .expect("reconstructed point is on the curve by construction")
    }
}

impl core::fmt::Debug for UnvalidatedPublicKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("UnvalidatedPublicKey(<reconstructed point>)")
    }
}