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, its transport types, and the private key reconstruction
//! value.

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

use elliptic_curve::ff::PrimeField;
use p256::Scalar;

use crate::encoding;
use crate::error::Error;
use crate::protocol;
use crate::unvalidated::UnvalidatedPublicKey;

/// An encoded implicit certificate (`CertU`): the opaque bytes that are hashed
/// by `Hn`.
///
/// `Certificate` bytes are produced by a [`CertificateAuthority`](crate::CertificateAuthority)
/// and travel in the clear. The secret half of the issue response is
/// [`PrivateReconstructionValue`], which is NOT part of the certificate.
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Certificate(pub(crate) Vec<u8>);

impl Certificate {
    /// The encoded certificate bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Parse certificate bytes as received over the wire.
    ///
    /// Fails fast if the bytes are not a structurally valid certificate of
    /// this crate's encoding, so a malformed certificate is caught at load
    /// time rather than at first use.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, Error> {
        encoding::decode(&bytes)?;
        Ok(Self(bytes))
    }

    /// Reconstruct the public key this certificate claims.
    ///
    /// This ALWAYS succeeds for any structurally valid certificate, including
    /// a forged one. The result is an [`UnvalidatedPublicKey`]: nothing has
    /// been proven, and the key is worthless until it is used successfully
    /// (for example, by verifying a signature the certificate holder produced).
    pub fn reconstruct(&self, ca_public: &p256::PublicKey) -> Result<UnvalidatedPublicKey, Error> {
        let decoded = encoding::decode(self.as_bytes())?;
        let point = protocol::user_public_key(
            self.as_bytes(),
            &decoded.reconstruction_point,
            ca_public.as_affine(),
        );
        Ok(UnvalidatedPublicKey { point })
    }
}

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

/// The private key reconstruction value `r`, produced by the CA and delivered
/// to the requester.
///
/// SECRET. Anyone holding `r` and the requester's request secret `k_U` can
/// derive the requester's private key. `r` must travel to the requester over a
/// channel that is both secret and authentic, and must never be logged.
///
/// Debug is redacted and the value is zeroized on drop.
#[derive(Clone)]
pub struct PrivateReconstructionValue(pub(crate) p256::SecretKey);

impl PrivateReconstructionValue {
    pub(crate) fn from_scalar(r: Scalar) -> Result<Self, Error> {
        let secret = p256::SecretKey::from_bytes(&r.to_repr()).map_err(|_| Error::InvalidScalar)?;
        Ok(Self(secret))
    }

    /// The value as a P-256 scalar (internal).
    pub(crate) fn scalar(&self) -> Scalar {
        *self.0.to_nonzero_scalar()
    }

    /// Serialize for transport to the requester. Treat the bytes as secret.
    pub fn to_bytes(&self) -> [u8; 32] {
        let mut out = [0u8; 32];
        out.copy_from_slice(self.0.to_bytes().as_slice());
        out
    }

    /// Parse `r` as received from the CA.
    ///
    /// # Errors
    /// Returns [`Error::InvalidScalar`] if the bytes are not a valid nonzero
    /// P-256 scalar.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let arr: [u8; 32] = bytes.try_into().map_err(|_| Error::InvalidScalar)?;
        let secret = p256::SecretKey::from_bytes(&arr.into()).map_err(|_| Error::InvalidScalar)?;
        Ok(Self(secret))
    }
}

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

/// The CA's response to a certificate request: the certificate itself and the
/// secret reconstruction value `r`.
///
/// The two fields have opposite confidentiality requirements. The
/// [`certificate`](Self::certificate) is public. The
/// [`private_reconstruction_value`](Self::private_reconstruction_value) is
/// secret and must reach the requester over a channel that is both secret and
/// authentic; a caller who logs or transmits it in the clear hands over the
/// requester's private key.
#[derive(Clone, Debug)]
pub struct CertificateIssue {
    pub certificate: Certificate,
    pub private_reconstruction_value: PrivateReconstructionValue,
}