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 requester side: generating a certificate request and finalizing the
//! response.

use alloc::vec::Vec;
use core::fmt;

use elliptic_curve::Generate;
#[cfg(feature = "test-vectors")]
use elliptic_curve::ff::Field;
use elliptic_curve::ff::PrimeField;
use elliptic_curve::sec1::ToSec1Point;
use p256::{AffinePoint, Scalar};

use crate::certificate::{Certificate, PrivateReconstructionValue};
use crate::encoding;
use crate::error::Error;
use crate::protocol;

/// A certificate request: the requester's request secret `k_U`, the public
/// request key `R_U = k_U*G`, and the identity and attributes to be certified.
///
/// The request holds `k_U`, which is secret and is zeroized when the request
/// is dropped. Only [`public_point`](Self::public_point) and the identity and
/// attributes should leave the device.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use ecqv::{CertificateAuthority, CertificateRequest};
/// use rand::rng;
///
/// let mut rng = rng();
///
/// // Identity and attributes are opaque bytes; the library length-prefixes
/// // them so no two distinct sets can encode to the same certificate.
/// let request = CertificateRequest::random(b"device-42", b"firmware=2.1", &mut rng);
///
/// // Only the public part ever leaves this device:
/// let request_public = request.public_point();
///
/// // ... request_public goes to the CA ...
/// let ca = CertificateAuthority::random(&mut rng);
/// let ca_public = ca.public_key();
/// let issued = ca.issue_certificate(&request)?;
///
/// // finalize CONSUMES the request, so k_U is used exactly once. It derives
/// // d_U and runs the SEC 4 3.6 self-check before anything is returned: a
/// // certificate not issued by ca_public, or altered, yields Err instead of
/// // a key. There is no "remember to verify" step to forget, because there is
/// // no key in hand until the check has passed.
/// let secret_key = request.finalize(
///     &issued.certificate,
///     &issued.private_reconstruction_value,
///     &ca_public,
/// )?;
/// # let _ = request_public;
/// # let _ = secret_key;
/// # Ok(())
/// # }
/// ```
pub struct CertificateRequest {
    k_u: p256::SecretKey,
    r_u: AffinePoint,
    identity: Vec<u8>,
    attributes: Vec<u8>,
}

impl CertificateRequest {
    /// Generate a new certificate request with a fresh random `k_U`.
    pub fn random<R: rand_core::CryptoRng + ?Sized>(
        identity: &[u8],
        attributes: &[u8],
        rng: &mut R,
    ) -> Self {
        let k_u = p256::SecretKey::generate_from_rng(rng);
        let r_u = *k_u.public_key().as_affine();
        Self {
            k_u,
            r_u,
            identity: identity.to_vec(),
            attributes: attributes.to_vec(),
        }
    }

    /// Build a request from a caller-supplied request secret.
    ///
    /// Available only with the `test-vectors` feature, which is never enabled
    /// for a production dependency. Used by the known-answer harness to pin
    /// `k_U` to the published vector inputs.
    #[cfg(feature = "test-vectors")]
    pub fn from_secret(identity: &[u8], attributes: &[u8], k_u: &Scalar) -> Result<Self, Error> {
        if bool::from(k_u.is_zero()) {
            return Err(Error::InvalidScalar);
        }
        let secret =
            p256::SecretKey::from_bytes(&k_u.to_repr()).map_err(|_| Error::InvalidScalar)?;
        let r_u = *secret.public_key().as_affine();
        Ok(Self {
            k_u: secret,
            r_u,
            identity: identity.to_vec(),
            attributes: attributes.to_vec(),
        })
    }

    /// The public request key `R_U`, sent to the CA over the wire.
    pub fn public_point(&self) -> p256::PublicKey {
        p256::PublicKey::from_affine(self.r_u).expect("request point is on the curve")
    }

    /// Derive the requester's private key from the CA's response.
    ///
    /// Consumes the request so `k_U` is used exactly once. Per SEC 4 section
    /// 3.6, this computes `d_U = e*k_U + r`, reconstructs `Q_U = e*P_U + Q_CA`
    /// and verifies `d_U*G == Q_U` before returning anything. A certificate
    /// not issued by `ca_public`, or altered in transit, fails the self-check
    /// and yields [`Error::SelfCheckFailed`] instead of a key.
    pub fn finalize(
        self,
        certificate: &Certificate,
        r: &PrivateReconstructionValue,
        ca_public: &p256::PublicKey,
    ) -> Result<p256::SecretKey, Error> {
        let cert_bytes = certificate.as_bytes();
        let decoded = encoding::decode(cert_bytes)?;

        let k_u: Scalar = *self.k_u.to_nonzero_scalar();
        let r_scalar = r.scalar();
        let d_u = protocol::requester_private_key(cert_bytes, &k_u, &r_scalar);

        // SEC 4 3.6: the requester verifies d_U*G == Q_U before trusting the
        // key. This is what makes the implicit validation explicit on the
        // holder's side.
        let q_u = protocol::user_public_key(
            cert_bytes,
            &decoded.reconstruction_point,
            ca_public.as_affine(),
        );
        if protocol::public_from_private(&d_u) != q_u {
            return Err(Error::SelfCheckFailed);
        }

        p256::SecretKey::from_bytes(&d_u.to_repr()).map_err(|_| Error::InvalidScalar)
    }

    /// The identity and attributes as the encoding layer sees them (internal).
    pub(crate) fn fields(&self) -> encoding::CertificateFields {
        encoding::CertificateFields::new(self.identity.clone(), self.attributes.clone())
    }

    /// The request's public point (internal).
    pub(crate) fn public_affine(&self) -> AffinePoint {
        self.r_u
    }

    /// An unambiguous serialization of the request, used to bind the CA nonce
    /// (internal).
    pub(crate) fn request_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        push_len(&mut out, &self.identity);
        push_len(&mut out, &self.attributes);
        out.extend_from_slice(self.r_u.to_sec1_point(true).as_bytes());
        out
    }
}

fn push_len(out: &mut Vec<u8>, field: &[u8]) {
    let len = u16::try_from(field.len()).expect("identity or attributes longer than 65535 bytes");
    out.extend_from_slice(&len.to_be_bytes());
    out.extend_from_slice(field);
}

impl fmt::Debug for CertificateRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CertificateRequest")
            .field("k_u", &"<redacted>")
            .field("r_u", &self.r_u)
            .finish()
    }
}