wolfcose 0.1.0

Safe Rust API for wolfSSL wolfCOSE.
#![allow(missing_docs)]

use wolfcose::{
    mac0_into, mac0_to_vec, verify_mac0, Algorithm, CoseKey, CoseKeyBuilder, CoseMac0Message,
    Error, Mac0Builder, PayloadMode,
};

const PAYLOAD: &[u8] = b"secured drone payload";
const AAD: &[u8] = b"drone-protocol/v1:test";

fn mac_key() -> CoseKey {
    CoseKeyBuilder::symmetric([0x22; 32])
        .algorithm(Algorithm::HMAC256)
        .kid(b"mac")
        .build()
        .unwrap()
}

#[test]
fn mac0_attached_detached_and_builder_paths_round_trip() {
    let key = mac_key();
    let mut scratch = [0; 1024];
    let mut out = [0; 512];
    let message = mac0_into(
        &key,
        Algorithm::HMAC256,
        Some(b"mac"),
        PayloadMode::Attached(PAYLOAD),
        AAD,
        &mut scratch,
        &mut out,
    )
    .unwrap()
    .to_vec();
    assert_eq!(
        mac0_to_vec(
            &key,
            Algorithm::HMAC256,
            Some(b"mac"),
            PayloadMode::Attached(PAYLOAD),
            AAD,
            &mut scratch
        )
        .unwrap(),
        message
    );

    let parsed = CoseMac0Message::parse(&message).unwrap();
    assert!(parsed.payload_attached());
    assert_eq!(parsed.unprotected().kid(), Some(&b"mac"[..]));

    let verified = verify_mac0(&key, &message, None, AAD, &mut scratch).unwrap();
    assert_eq!(verified.payload, Some(PAYLOAD));
    assert_eq!(
        verify_mac0(&key, &message, None, b"wrong-aad", &mut scratch),
        Err(Error::MacFailed)
    );

    let mut builder_out = [0; 512];
    let mut builder = Mac0Builder::new()
        .key(&key)
        .algorithm(Algorithm::HMAC256)
        .kid(b"mac")
        .external_aad(AAD)
        .payload(PayloadMode::Attached(PAYLOAD))
        .scratch_len(1024);
    let builder_message = builder.mac_into(&mut builder_out).unwrap().to_vec();
    let builder_vec = builder.mac_to_vec().unwrap();
    assert_eq!(builder_message, builder_vec);
    assert_eq!(
        builder.verify(&builder_vec, None).unwrap().payload,
        Some(PAYLOAD)
    );

    let detached = mac0_to_vec(
        &key,
        Algorithm::HMAC256,
        None,
        PayloadMode::Detached(PAYLOAD),
        AAD,
        &mut scratch,
    )
    .unwrap();
    let parsed = CoseMac0Message::parse(&detached).unwrap();
    assert!(!parsed.payload_attached());
    assert_eq!(
        verify_mac0(&key, &detached, Some(PAYLOAD), AAD, &mut scratch)
            .unwrap()
            .payload,
        None
    );
    assert_eq!(
        verify_mac0(&key, &detached, None, AAD, &mut scratch),
        Err(Error::DetachedPayload)
    );
}