use alloc::vec::Vec;
use elliptic_curve::sec1::{FromSec1Point, Sec1Point, ToSec1Point};
use p256::{AffinePoint, NistP256};
pub const COMPRESSED_POINT_LEN: usize = 33;
#[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,
}
}
}
#[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);
}
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
}
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;
fn test_point() -> AffinePoint {
AffinePoint::from(ProjectivePoint::GENERATOR)
}
#[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));
}
}
#[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());
}
}