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
//! Deterministic CA nonce derivation.
//!
//! SEC 4 hazard: reusing the CA nonce `k` across two certificates leaks the CA
//! private key by simple algebra. Rather than trust an RNG at issue time, `k`
//! is derived deterministically from `(d_CA, request)` the way RFC 6979 derives
//! a nonce from a key and message: `k` is a rejection-sampled HMAC-SHA256
//! output, keyed by `d_CA`, over the request bytes plus a counter.
//!
//! Consequences that are exactly what we want:
//!
//! - the same request issued twice yields the same `k` and the same
//!   certificate (idempotent, not a leak);
//! - two different requests yield different `k` with overwhelming probability;
//! - there is no RNG to fail, so an RNG that is broken, cloned, or reset can
//!   never reproduce a nonce;
//! - the CA issuing API therefore never accepts a caller-supplied nonce.
//!   Known-answer testing injects `k` through the feature-gated
//!   `issue_certificate_with_nonce` only.

use elliptic_curve::ff::{Field, PrimeField};
use hmac::{Hmac, KeyInit, Mac};
use p256::Scalar;
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

/// Derive the CA nonce `k` for a request, bound to the CA secret `d_ca`.
pub(crate) fn derive_nonce(d_ca: &Scalar, request_bytes: &[u8]) -> Scalar {
    let mut counter = 0u64;
    loop {
        let mut mac = <HmacSha256 as KeyInit>::new_from_slice(d_ca.to_repr().as_slice())
            .expect("HMAC accepts any key length");
        mac.update(request_bytes);
        mac.update(&counter.to_be_bytes());
        let out = mac.finalize().into_bytes();

        // Rejection sample into [1, n-1]. The number of rejections is the only
        // side channel, and it carries nothing usable.
        if let Some(candidate) = Scalar::from_repr(out).into_option() {
            if !bool::from(candidate.is_zero()) {
                return candidate;
            }
        }
        counter = counter.wrapping_add(1);
    }
}