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 certificate authority: the long-lived issuing key.

use core::fmt;

use elliptic_curve::Generate;
use p256::Scalar;

use crate::certificate::{Certificate, CertificateIssue, PrivateReconstructionValue};
use crate::encoding;
use crate::error::Error;
use crate::nonce::derive_nonce;
use crate::protocol;
use crate::request::CertificateRequest;

/// A certificate authority: the long-lived P-256 key pair that issues implicit
/// certificates.
///
/// The issuing secret `d_CA` is zeroized when the authority is dropped and is
/// redacted from `Debug`. The public key is the trust anchor: every requester
/// and every relying party must hold it.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use ecqv::{CertificateAuthority, CertificateRequest};
/// use rand::rng;
///
/// let mut rng = rng();
///
/// // One-time setup. In production this key comes from secure storage or an
/// // HSM; random() exists for tests and development.
/// let ca = CertificateAuthority::random(&mut rng);
///
/// // The trust anchor. Every requester and relying party must hold it.
/// let ca_public = ca.public_key();
///
/// // Per request. No RNG is passed: the per-certificate nonce is derived
/// // deterministically from (d_CA, request), so the same request cannot be
/// // issued twice with two different nonces and d_CA cannot leak via reuse.
/// let request = CertificateRequest::random(b"device-42", b"", &mut rng);
/// let issued = ca.issue_certificate(&request)?;
///
/// // Deliver over a channel that is both secret and authentic:
/// //   certificate                         -> requester (public)
/// //   private_reconstruction_value (`r`)  -> requester (SECRET: `r` plus the
/// //                                          requester's k_U derives the
/// //                                          requester's private key)
/// # let _ = (ca_public, issued.certificate, issued.private_reconstruction_value);
/// # Ok(())
/// # }
/// ```
pub struct CertificateAuthority {
    secret: p256::SecretKey,
    public: p256::PublicKey,
}

impl CertificateAuthority {
    /// Generate a fresh CA key pair.
    pub fn random<R: rand_core::CryptoRng + ?Sized>(rng: &mut R) -> Self {
        let secret = p256::SecretKey::generate_from_rng(rng);
        let public = secret.public_key();
        Self { secret, public }
    }

    /// Build a CA from an existing P-256 secret key, for example one loaded
    /// from secure storage or an HSM.
    pub fn from_secret_key(secret: &p256::SecretKey) -> Self {
        let public = secret.public_key();
        Self {
            secret: secret.clone(),
            public,
        }
    }

    /// The CA public key `Q_CA`: the trust anchor.
    pub fn public_key(&self) -> p256::PublicKey {
        self.public
    }

    /// Issue an implicit certificate for a request.
    ///
    /// The per-certificate nonce `k` is derived deterministically from
    /// `(d_CA, request)` (see `nonce`); the caller supplies no randomness and
    /// cannot influence or repeat `k`.
    pub fn issue_certificate(
        &self,
        request: &CertificateRequest,
    ) -> Result<CertificateIssue, Error> {
        let d_ca: Scalar = *self.secret.to_nonzero_scalar();
        let k = derive_nonce(&d_ca, &request.request_bytes());
        self.issue_with_nonce(request, &k)
    }

    /// Issue with a caller-supplied nonce, for the known-answer harness.
    ///
    /// Available only with the `test-vectors` feature, which is never enabled
    /// for a production dependency. In normal use the CA nonce must never be
    /// chosen or repeated by the caller: reuse leaks `d_CA`.
    #[cfg(feature = "test-vectors")]
    pub fn issue_certificate_with_nonce(
        &self,
        request: &CertificateRequest,
        k: &Scalar,
    ) -> Result<CertificateIssue, Error> {
        self.issue_with_nonce(request, k)
    }

    fn issue_with_nonce(
        &self,
        request: &CertificateRequest,
        k: &Scalar,
    ) -> Result<CertificateIssue, Error> {
        let d_ca: Scalar = *self.secret.to_nonzero_scalar();
        let p_u = protocol::reconstruction_point(&request.public_affine(), k);
        let cert_bytes = encoding::encode(&request.fields(), &p_u);
        let r = protocol::issue_private_value(&cert_bytes, k, &d_ca);
        Ok(CertificateIssue {
            certificate: Certificate(cert_bytes),
            private_reconstruction_value: PrivateReconstructionValue::from_scalar(r)?,
        })
    }
}

impl fmt::Debug for CertificateAuthority {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CertificateAuthority")
            .field("public_key", &self.public)
            .finish()
    }
}