Expand description
Rust implementation of DIDComm v2 spec
§License
§Examples of usage
§1. Prepare raw message for send and receive
§GoTo: full test
// Message construction
let m = Message::new()
// setting `from` header (sender) - Optional
.from("did:xyz:ulapcuhsatnpuhza930hpu34n_")
// setting `to` header (recipients) - Optional
.to(&[
"did::xyz:34r3cu403hnth03r49g03",
"did:xyz:30489jnutnjqhiu0uh540u8hunoe",
])
// populating body with some data - `Vec<bytes>`
.body(TEST_DID).unwrap();
// Serialize message into JWM json (SENDER action)
let ready_to_send = m.clone().as_raw_json().unwrap();
// ... transport is happening here ...
// On receival deserialize from json into Message (RECEIVER action)
// Error handling recommended here
let received = Message::receive(&ready_to_send, None, None, None);§2. Prepare JWE message for direct send
§GoTo: full test
// sender key as bytes
let ek = [130, 110, 93, 113, 105, 127, 4, 210, 65, 234, 112, 90, 150, 120, 189, 252, 212, 165, 30, 209, 194, 213, 81, 38, 250, 187, 216, 14, 246, 250, 166, 92];
// Message construction
let message = Message::new()
.from("did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp")
.to(&[
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
])
// packing in some payload (can be anything really)
.body(TEST_DID).unwrap()
// decide which [Algorithm](crypto::encryptor::CryptoAlgorithm) is used (based on key)
.as_jwe(
&CryptoAlgorithm::XC20P,
Some(bobs_public.to_vec()),
)
// add some custom app/protocol related headers to didcomm header portion
// these are not included into JOSE header
.add_header_field("my_custom_key".into(), "my_custom_value".into())
.add_header_field("another_key".into(), "another_value".into())
// set `kid` property
.kid(r#"#z6LShs9GGnqk85isEBzzshkuVWrVKsRp24GnDuHk8QWkARMW"#);
// recipient public key is automatically resolved
let ready_to_send = message.seal(
&ek,
Some(vec![Some(bobs_public.to_vec()), Some(carol_public.to_vec())]),
).unwrap();
//... transport is happening here ...§3. Prepare JWS message -> send -> receive
- Here
Messageis signed but not encrypted. - In such scenarios explicit use of
.sign(...)andMessage::verify(...)required.
// Message construction an JWS wrapping
let message = Message::new() // creating message
.from("did:xyz:ulapcuhsatnpuhza930hpu34n_") // setting from
.to(&["did::xyz:34r3cu403hnth03r49g03", "did:xyz:30489jnutnjqhiu0uh540u8hunoe"]) // setting to
.body(TEST_DID).unwrap() // packing in some payload
.as_jws(&SignatureAlgorithm::EdDsa)
.sign(SignatureAlgorithm::EdDsa.signer(), &sign_keypair.to_bytes()).unwrap();
//... transport is happening here ...
// Receiving JWS
let received = Message::verify(&message.as_bytes(), &sign_keypair.verifying_key().to_bytes());§4. Prepare JWE message to be mediated -> mediate -> receive
- Message should be encrypted by destination key first in
.routed_by()method call using key for the recipient. - Next it should be encrypted by mediator key in
.seal()method call - this can be done multiple times - once for each mediator in chain but should be strictly sequential to match mediators sequence in the chain. - Method call
.seal()MUST be preceded by.as_jwe(CryptoAlgorithm)as mediators may use different algorithms and key types than destination and this is not automatically predicted or populated. - Keys used for encryption should be used in reverse order - final destination - last mediator - second to last mediator - etc. Onion style.
§GoTo: full test
let mediated = Message::new()
// setting from
.from("did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp")
// setting to
.to(&["did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG"])
// packing in some payload
.body(r#"{"foo":"bar"}"#).unwrap()
// set JOSE header for XC20P algorithm
.as_jwe(&CryptoAlgorithm::XC20P, Some(bobs_public.to_vec()))
// custom header
.add_header_field("my_custom_key".into(), "my_custom_value".into())
// another custom header
.add_header_field("another_key".into(), "another_value".into())
// set kid header
.kid(&"Ef1sFuyOozYm3CEY4iCdwqxiSyXZ5Br-eUDdQXk6jaQ")
// here we use destination key to bob and `to` header of mediator -
//**THIS MUST BE LAST IN THE CHAIN** - after this call you'll get new instance of envelope `Message` destined to the mediator.
.routed_by(
&alice_private,
Some(vec![Some(bobs_public.to_vec())]),
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
Some(mediators_public.to_vec()),
);
assert!(mediated.is_ok());
//... transport to mediator is happening here ...
// Received by mediator
let mediator_received = Message::receive(
&mediated.unwrap(),
Some(&mediators_private),
Some(alice_public.to_vec()),
None,
);
assert!(mediator_received.is_ok());
// Get inner JWE as string from message
let mediator_received_unwrapped = mediator_received.unwrap().get_body().unwrap();
let pl_string = String::from_utf8_lossy(mediator_received_unwrapped.as_ref());
let message_to_forward: Mediated = serde_json::from_str(&pl_string).unwrap();
let attached_jwe = serde_json::from_slice::<Jwe>(&message_to_forward.payload);
assert!(attached_jwe.is_ok());
let str_jwe = serde_json::to_string(&attached_jwe.unwrap());
assert!(str_jwe.is_ok());
//... transport to destination is happening here ...
// Received by Bob
let bob_received = Message::receive(
&String::from_utf8_lossy(&message_to_forward.payload),
Some(&bobs_private),
Some(alice_public.to_vec()),
None,
);
assert!(bob_received.is_ok());§5. Prepare JWS envelope wrapped into JWE -> sign -> pack -> receive
- JWS header is set automatically based on signing algorithm type.
- Message forming and encryption happens in same way as in other JWE examples.
- ED25519-dalek signature is used in this example with keypair for signing and public key for verification.
§GoTo: full test
let KeyPairSet {
alice_public,
alice_private,
bobs_private,
bobs_public,
..
} = get_keypair_set();
// Message construction
let message = Message::new() // creating message
.from("did:xyz:ulapcuhsatnpuhza930hpu34n_") // setting from
.to(&["did::xyz:34r3cu403hnth03r49g03"]) // setting to
.body(TEST_DID).unwrap() // packing in some payload
.as_jwe(&CryptoAlgorithm::XC20P, Some(bobs_public.to_vec())) // set JOSE header for XC20P algorithm
.add_header_field("my_custom_key".into(), "my_custom_value".into()) // custom header
.add_header_field("another_key".into(), "another_value".into()) // another custom header
.kid(r#"Ef1sFuyOozYm3CEY4iCdwqxiSyXZ5Br-eUDdQXk6jaQ"#); // set kid header
// Send as signed and encrypted JWS wrapped into JWE
let ready_to_send = message.seal_signed(
&alice_private,
Some(vec![Some(bobs_public.to_vec())]),
SignatureAlgorithm::EdDsa,
&sign_keypair.to_bytes(),
).unwrap();
//... transport to destination is happening here ...
//Receive - same method to receive for JWE or JWS wrapped into JWE but with pub verifying key
let received = Message::receive(
&ready_to_send,
Some(&bobs_private),
Some(alice_public.to_vec()),
None,
); // and now we parse received§6. Multiple recipients static key wrap per recipient with shared secret
- ! Works with
resolvefeature only - requires resolution of public keys for each recipient for shared secret generation. - Static key generated randomly in the background (
tofield has >1 recipient).
§GoTo: full test
§Pluggable cryptography
In order to use your own implementation(s) of message crypto and/or signature algorithms implement these trait(s):
Don’t use default feature - might change in future.
When implemented - use them instead of CryptoAlgorithm and SignatureAlgorithm from examples above.
§Strongly typed Message payload (body)
§GoTo: full test
In most cases application implementation would prefer to have strongly typed body of the message instead of raw Vec<u8>.
For this scenario Shape trait should be implemented for target type.
- First, let’s define our target type. JSON in this example.
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct DesiredShape {
num_field: usize,
string_field: String,
}- Next, implement
Shapetrait for it
impl Shape for DesiredShape {
type Err = Error;
fn shape(m: &Message) -> Result<DesiredShape, Error> {
serde_json::from_str(&m.get_body().unwrap())
.map_err(|e| Error::SerdeError(e))
}
}- Now we can call
shape()on ourMessageand shape in in. - In this example we expect JSON payload and use it’s Deserializer to get our data, but your implementation can work with any serialization.
let body = r#"{"num_field":123,"string_field":"foobar"}"#.to_string();
let message = Message::new() // creating message
.from("did:xyz:ulapcuhsatnpuhza930hpu34n_") // setting from
.to(&["did::xyz:34r3cu403hnth03r49g03"]) // setting to
.body(&body).unwrap(); // packing in some payload
let received_typed_body = DesiredShape::shape(&message).unwrap(); // Where m = Message§Disclaimer
This is a sample implementation of the DIDComm V2 spec. The DIDComm V2 spec is still actively being developed by the DIDComm WG in the DIF and therefore subject to change.
Modules§
- crypto
- Collection of utilities for cryptography related components.
- decorators
- Decorator Types.
- out_
of_ band
Structs§
- Attachment
- Attachment holding structure
- Attachment
Builder - Builder of attachment metadata and payload.
Used to construct and inject Attachment into
Message - Attachment
Data - Attachment Data holding structure
- Attachment
Data Builder - Builder for
AttachmentData - DidComm
Header - Collection of DIDComm message specific headers, will be flattened into DIDComm plain message according to spec.
- Epk
- Encryption public key
- Jwe
- JWE representation of
Messagewith public header. Can be serialized to JSON or Compact representations and from same. - Jwk
- Json Web Keys structure defined by RFC
- JwmHeader
- JWM Header as specified in RFC With single deviation - allows raw text JWM to support DIDComm spec
- Jws
- A struct to generate and serialize JWS envelopes for DIDComm messages.
- Mediated
- Mediated Message value
- Message
- DIDComm message structure.
- Prior
Claims - header used for DID rotation
- Problem
- Recipient
- This struct presents single recipient of JWE
recipientscollection. Each recipient should have same body cypher key encrypted with shared secret. Spec - Signature
- Signature data for JWS envelopes.
They can be used per recipient in General JWS JSON,
triggered by using
.as_jwsor as a single signature for the entire JWS in Flattened JWS JSON, triggered by.as_flat_jws. - Thread
- A
~threadmessage decorator that provides request/reply and threading semantics according to Aries RFC 0008.
Enums§
- Content
Type - Enum that represents DIDComm message payload type
- Error
Errortype used througout crate- KeyAlgorithm
algfield values provided by RFC- KeyOps
- Known
Problems - Values defined in spec: https://identity.foundation/didcomm-messaging/spec/#problem-codes
Except
KnownProblems::Unknow, which is default and should be used as little as possible - Message
Type - Enum that represents DIDComm envelope type
Traits§
Type Aliases§
- Result
Resulttype. See module level documentation.