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
//! Certificate encoding layer.
//!
//! SEC 4 v1.0 treats the certificate encoding as a pluggable component: the
//! scheme is defined over an opaque certificate byte string, and Appendix C
//! lists several encodings. The known-answer vectors validate the protocol
//! core, and validate nothing about encoding ambiguity; that gap is exactly
//! what the adversarial tests in this module exist to close.
//!
//! The encoding here is deliberately unambiguous: every variable-length field
//! carries an explicit big-endian length prefix. Without the prefixes, two
//! different (identity, attributes) tuples could serialize to the same bytes
//! and hash to the same `e`, which would let one certificate impersonate
//! another (certificate substitution). With the prefixes, the split is
//! recoverable, so that class of collision cannot occur.

use alloc::vec::Vec;
use elliptic_curve::sec1::{FromSec1Point, Sec1Point, ToSec1Point};
use p256::{AffinePoint, NistP256};

/// Length of the compressed SEC1 encoding of a P-256 point (0x02/0x03 + x).
pub const COMPRESSED_POINT_LEN: usize = 33;

/// The user-controlled fields that, together with the reconstruction point,
/// form the certificate that is hashed by `Hn`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CertificateFields {
    pub identity: Vec<u8>,
    pub attributes: Vec<u8>,
}

impl CertificateFields {
    pub fn new(identity: Vec<u8>, attributes: Vec<u8>) -> Self {
        Self {
            identity,
            attributes,
        }
    }
}

/// A parsed certificate: the identity/attribute fields and the reconstruction
/// point, exactly as they were encoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DecodedCertificate {
    pub fields: CertificateFields,
    pub reconstruction_point: AffinePoint,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeError {
    Truncated,
    InvalidPoint,
}

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

/// Encode identity and attributes with the reconstruction point into the
/// opaque certificate bytes that are passed to `Hn`.
pub fn encode(fields: &CertificateFields, reconstruction_point: &AffinePoint) -> Vec<u8> {
    let mut out = Vec::new();
    push_len_prefixed(&mut out, &fields.identity);
    push_len_prefixed(&mut out, &fields.attributes);
    out.extend_from_slice(reconstruction_point.to_sec1_point(true).as_bytes());
    out
}

/// Parse a certificate produced by [`encode`].
pub fn decode(cert: &[u8]) -> Result<DecodedCertificate, DecodeError> {
    let mut rest = cert;

    let (identity, r) = take_len_prefixed(rest).ok_or(DecodeError::Truncated)?;
    rest = r;
    let (attributes, r) = take_len_prefixed(rest).ok_or(DecodeError::Truncated)?;
    rest = r;

    if rest.len() != COMPRESSED_POINT_LEN {
        return Err(DecodeError::Truncated);
    }
    let ep = Sec1Point::<NistP256>::from_bytes(rest).map_err(|_| DecodeError::InvalidPoint)?;
    let reconstruction_point =
        AffinePoint::from_sec1_point(&ep).ok_or(DecodeError::InvalidPoint)?;

    Ok(DecodedCertificate {
        fields: CertificateFields::new(identity.to_vec(), attributes.to_vec()),
        reconstruction_point,
    })
}

fn take_len_prefixed(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
    let len_bytes: [u8; 2] = bytes.get(..2)?.try_into().ok()?;
    let len = u16::from_be_bytes(len_bytes) as usize;
    let field = bytes.get(2..2 + len)?;
    Some((field, &bytes[2 + len..]))
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::ProjectivePoint;

    /// A fixed, valid P-256 point for encoding tests: the generator.
    fn test_point() -> AffinePoint {
        AffinePoint::from(ProjectivePoint::GENERATOR)
    }

    /// The adversarial case the vectors cannot cover: shifting a byte across
    /// the identity/attributes boundary must change the encoded bytes. With
    /// length prefixes the split is unambiguous, so two distinct tuples can
    /// never serialize to the same certificate.
    #[test]
    fn boundary_shift_cannot_collide() {
        let pt = test_point();
        let a = CertificateFields::new(b"ab".to_vec(), b"c".to_vec());
        let b = CertificateFields::new(b"a".to_vec(), b"bc".to_vec());
        let ea = encode(&a, &pt);
        let eb = encode(&b, &pt);
        assert_ne!(ea, eb, "distinct (identity, attributes) collided");
    }

    #[test]
    fn boundary_shift_is_distinguishable_after_decode() {
        let pt = test_point();
        let a = decode(&encode(
            &CertificateFields::new(b"ab".to_vec(), b"c".to_vec()),
            &pt,
        ))
        .unwrap();
        let b = decode(&encode(
            &CertificateFields::new(b"a".to_vec(), b"bc".to_vec()),
            &pt,
        ))
        .unwrap();
        assert_ne!(a.fields.identity, b.fields.identity);
        assert_ne!(a.fields.attributes, b.fields.attributes);
    }

    #[test]
    fn empty_fields_round_trip() {
        let pt = test_point();
        let fields = CertificateFields::new(Vec::new(), Vec::new());
        let cert = encode(&fields, &pt);
        let dec = decode(&cert).unwrap();
        assert_eq!(dec.fields, fields);
        assert_eq!(dec.reconstruction_point, pt);
    }

    #[test]
    fn truncated_input_is_rejected() {
        let pt = test_point();
        let cert = encode(
            &CertificateFields::new(b"id".to_vec(), b"attrs".to_vec()),
            &pt,
        );
        for cut in 0..cert.len() {
            assert_eq!(decode(&cert[..cut]), Err(DecodeError::Truncated));
        }
    }

    /// Corruption of the reconstruction point must be rejected rather than
    /// accepted silently: a structurally bad point is the entry point for a
    /// forged certificate. An x coordinate above the field modulus is not a
    /// valid P-256 point, so decode must fail.
    #[test]
    fn corrupted_point_is_rejected() {
        let pt = test_point();
        let fields = CertificateFields::new(b"id".to_vec(), b"attrs".to_vec());
        let mut cert = encode(&fields, &pt);
        let point_start = 2 + fields.identity.len() + 2 + fields.attributes.len();
        cert[point_start] = 0x02;
        cert[point_start + 1..point_start + 33].fill(0xFF);
        assert!(decode(&cert).is_err());
    }
}