Skip to main content

Crate cose2

Crate cose2 

Source
Expand description

cose2 — CBOR Object Signing and Encryption (COSE, RFC 9052) and CBOR Web Token (CWT, RFC 8392) for Rust, built on cbor2.

This crate models COSE structures (messages, headers, keys) and CWT claims, and delegates cryptography to caller-supplied implementations of the Signer, Verifier, Macer and Encryptor traits — so it ships no cryptographic dependencies in its default feature set. Top-level COSE messages use named Rust structs with #[cbor(array)] to keep the COSE array wire shape, and encode with their registered CBOR tags through #[derive(cbor2::Cbor)]. CWT claims likewise encode with their registered CBOR tag. Decode helpers still accept untagged messages and claim maps for compatibility; use to_untagged_vec when a peer expects an untagged wire body. Headers reject malformed crit parameters and protected/unprotected bucket label collisions. Critical header parameters (crit) that an application must understand are validated structurally on decode; applications that process untrusted input should additionally call Header::ensure_crit_understood on each protected header to enforce the RFC 9052 §3.1 rule that an unrecognised critical parameter is a fatal error. Header accessors and the message layer read attributes from the protected bucket first and then the unprotected bucket (RFC 9052 §3). Keys enforce required kty values and non-empty COSE_KeySets. Recipient structures validate the RFC 9052 shape for known recipient algorithm classes. Content-key distribution itself (key wrap, key transport, ECDH key agreement, and the Enc_Recipient / Mac_Recipient / Rec_Recipient recipient-layer cryptography of RFC 9053) is left to application code: this crate models and validates the recipient structures but does not encrypt or decrypt the content-encryption key. Content encryption follows the AEAD construction of RFC 9052 §5.3; the Encryptor trait always authenticates the Enc_structure, so the AE-only construction of §5.4 (zero-length protected header, no external AAD) is not directly modelled. Encryption accepts either a full IV, or a Partial IV combined with Encryptor::base_iv, and never generates nonces internally. Optional crypto backends are available behind feature flags; enable crypto-ring (or the aggregate crypto feature) for a ring-based backend, or crypto-aws-lc-rs for an aws-lc-rs-based one. The two backends expose the same providers; when both are enabled, crypto-ring takes precedence. The crypto-ed25519-dalek feature adds a standalone Ed25519 Signer/Verifier backed by ed25519-dalek (module ed25519), and crypto-aes-gcm adds an AES-GCM Encryptor backed by aes-gcm (module aes_gcm).

§Example: COSE_Sign1 round trip

use cose2::{iana, Sign1Message, Signer, Verifier, Error};

// A trivial (insecure) signer/verifier for illustration.
struct Demo;
impl Signer for Demo {
    fn alg(&self) -> Option<cose2::Label> { Some(iana::AlgorithmEdDSA.into()) }
    fn kid(&self) -> Option<&[u8]> { Some(b"key-1") }
    fn sign(&self, data: &[u8]) -> Result<Vec<u8>, Error> { Ok(data.to_vec()) }
}
impl Verifier for Demo {
    fn alg(&self) -> Option<cose2::Label> { Some(iana::AlgorithmEdDSA.into()) }
    fn verify(&self, data: &[u8], sig: &[u8]) -> Result<(), Error> {
        if sig == data { Ok(()) } else { Err(Error::verify("bad signature")) }
    }
}

let mut msg = Sign1Message::new(Some(b"This is the content".to_vec()));
let encoded = msg.sign_and_encode(&Demo, None).unwrap();

let verified = Sign1Message::verify_and_decode(&Demo, &encoded, None).unwrap();
assert_eq!(verified.payload.as_deref(), Some(&b"This is the content"[..]));

Modules§

aes_gcm
Optional built-in AES-GCM content encryptor backed by aes-gcm.
crypto
Optional built-in cryptographic providers.
cwt
CBOR Web Token (CWT) claims and validation (RFC 8392).
ed25519
Optional built-in Ed25519 providers backed by ed25519-dalek.
iana
Constants for the COSE, CWT and CBOR-tags IANA registries.
tag
CBOR tag prefixes for COSE structures and helpers to add/strip them.

Structs§

CoseMap
A map from Label to Value, the common representation of COSE header, key and CWT-claim maps (RFC 9052 / RFC 8392).
Encrypt0Message
A COSE_Encrypt0 message.
EncryptMessage
A COSE_Encrypt message (encryption with one or more recipients).
EncryptionContext
AEAD inputs prepared by a COSE_Encrypt or COSE_Encrypt0 message.
Header
A COSE Headers / Generic_Headers map (RFC 9052 §3).
KdfContext
A COSE_KDF_Context structure (RFC 9053 §5.2): [AlgorithmID, PartyUInfo, PartyVInfo, SuppPubInfo, ?SuppPrivInfo].
Key
A COSE_Key object: a CoseMap with key-specific accessors.
KeySet
A set of Key objects (a COSE_KeySet, encoded as a CBOR array).
Mac0Message
A COSE_Mac0 message.
MacMessage
A COSE_Mac message (MAC with one or more recipients).
PartyInfo
A PartyInfo array [identity, nonce, other] (RFC 9053 §5.2).
Recipient
A COSE_recipient structure.
Sign1Message
A COSE_Sign1 message.
SignMessage
A COSE_Sign message (one or more signers).
Signature
A COSE_Signature inside a SignMessage.
SuppPubInfo
A SuppPubInfo structure: [keyDataLength, protected, ?other].

Enums§

Error
Errors returned by COSE/CWT operations in this crate.
Label
A COSE label, used as the key of header, key and claim maps.
RecipientAlgorithmClass
The recipient algorithm class implied by a registered COSE algorithm.
Value
The CBOR value type used for header, key and claim values.

Traits§

Encryptor
Encrypts and decrypts content for COSE_Encrypt and COSE_Encrypt0.
Macer
Computes and verifies message authentication codes for COSE_Mac and COSE_Mac0.
Signer
Produces digital signatures for COSE_Sign and COSE_Sign1.
Verifier
Verifies digital signatures for COSE_Sign and COSE_Sign1.

Functions§

is_understood_header
Returns true when label is a common header parameter this crate models natively and therefore always understands (RFC 9052 §3.1: “Header parameters defined in [RFC 9052] do not need to be included [in crit]”).