didcomm 0.4.1

DIDComm for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use askar_crypto::sign::KeySign;
use std::borrow::Cow;

use crate::{
    error::{ErrorKind, Result, ResultExt},
    jws::envelope::{Algorithm, CompactHeader, Header, ProtectedHeader, Signature, JWS},
};

pub(crate) fn sign<Key: KeySign>(
    payload: &[u8],
    signer: (&str, &Key),
    alg: Algorithm,
) -> Result<String> {
    let (kid, key) = signer;

    let sig_type = alg.sig_type()?;

    let protected = {
        let protected = ProtectedHeader {
            typ: Cow::Borrowed("application/didcomm-signed+json"),
            alg,
        };

        let protected = serde_json::to_string(&protected)
            .kind(ErrorKind::InvalidState, "Unable serialize protected header")?;

        base64::encode_config(protected, base64::URL_SAFE_NO_PAD)
    };

    let payload = base64::encode_config(payload, base64::URL_SAFE_NO_PAD);

    let signature = {
        // JWS Signing Input
        // The input to the digital signature or MAC computation.  Its value
        // is ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload)).
        let sign_input = format!("{}.{}", protected, payload);

        let signature = key
            .create_signature(sign_input.as_bytes(), Some(sig_type))
            .kind(ErrorKind::InvalidState, "Unable create signature")?;

        base64::encode_config(&signature, base64::URL_SAFE_NO_PAD)
    };

    let signature = Signature {
        header: Header { kid },
        protected: &protected,
        signature: &signature,
    };

    let jws = JWS {
        signatures: vec![signature],
        payload: &payload,
    };

    let jws = serde_json::to_string(&jws).kind(ErrorKind::InvalidState, "Unable serialize jws")?;

    Ok(jws)
}

pub(crate) fn sign_compact<Key: KeySign>(
    payload: &[u8],
    signer: (&str, &Key),
    typ: &str,
    alg: Algorithm,
) -> Result<String> {
    let (kid, key) = signer;

    let sig_type = alg.sig_type()?;

    let header = {
        let header = CompactHeader { typ, alg, kid };

        let header = serde_json::to_string(&header)
            .kind(ErrorKind::InvalidState, "Unable serialize header")?;

        base64::encode_config(header, base64::URL_SAFE_NO_PAD)
    };

    let payload = base64::encode_config(payload, base64::URL_SAFE_NO_PAD);

    let signature = {
        // JWS Signing Input
        // The input to the digital signature or MAC computation.  Its value
        // is ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload)).
        let sign_input = format!("{}.{}", header, payload);

        let signature = key
            .create_signature(sign_input.as_bytes(), Some(sig_type))
            .kind(ErrorKind::InvalidState, "Unable create signature")?;

        base64::encode_config(&signature, base64::URL_SAFE_NO_PAD)
    };

    let compact_jws = format!("{}.{}.{}", header, payload, signature);

    Ok(compact_jws)
}

#[cfg(test)]
mod tests {
    use askar_crypto::{
        alg::{ed25519::Ed25519KeyPair, k256::K256KeyPair, p256::P256KeyPair},
        jwk::FromJwk,
        sign::{KeySigVerify, KeySign},
    };

    use crate::{
        error::{ErrorKind, Result},
        jws::{self, envelope::Algorithm},
    };

    #[test]
    fn sign_works() {
        _sign_works::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            ALICE_PKEY_ED25519,
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_works::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            ALICE_PKEY_P256,
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_works::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            ALICE_PKEY_K256,
            Algorithm::Es256K,
            PAYLOAD,
        );

        fn _sign_works<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            pkey: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign::<K>(kid, key, alg.clone(), payload);

            let msg = res.expect("Unable _sign");

            let mut buf = vec![];
            let msg = jws::parse(&msg, &mut buf).expect("Unable parse");

            assert_eq!(
                msg.jws.payload,
                base64::encode_config(payload, base64::URL_SAFE_NO_PAD)
            );

            assert_eq!(msg.jws.signatures.len(), 1);
            assert_eq!(msg.jws.signatures[0].header.kid, kid);

            assert_eq!(msg.protected.len(), 1);
            assert_eq!(msg.protected[0].alg, alg);
            assert_eq!(msg.protected[0].typ, "application/didcomm-signed+json");

            let pkey = K::from_jwk(pkey).expect("Unable from_jwk");
            let valid = msg.verify::<K>((kid, &pkey)).expect("Unable verify");

            assert!(valid);
        }
    }

    #[test]
    fn sign_works_incompatible_alg() {
        _sign_works_incompatible_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            Algorithm::Es256,
            PAYLOAD,
        );

        fn _sign_works_incompatible_alg<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign::<K>(kid, key, alg.clone(), payload);

            let err = res.expect_err("res is ok");
            assert_eq!(err.kind(), ErrorKind::InvalidState);

            assert_eq!(
                format!("{}", err),
                "Invalid state: Unable create signature: Unsupported signature type"
            );
        }
    }

    #[test]
    fn sign_works_unknown_alg() {
        _sign_works_unknown_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        _sign_works_unknown_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        _sign_works_unknown_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        fn _sign_works_unknown_alg<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign::<K>(kid, key, alg.clone(), payload);

            let err = res.expect_err("res is ok");
            assert_eq!(err.kind(), ErrorKind::Unsupported);

            assert_eq!(
                format!("{}", err),
                "Unsupported crypto or method: Unsupported signature type"
            );
        }
    }

    #[test]
    fn sign_compact_works() {
        _sign_compact_works::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            ALICE_PKEY_ED25519,
            "example-typ-1",
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_compact_works::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            ALICE_PKEY_P256,
            "example-typ-2",
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_compact_works::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            ALICE_PKEY_K256,
            "example-typ-3",
            Algorithm::Es256K,
            PAYLOAD,
        );

        fn _sign_compact_works<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            pkey: &str,
            typ: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign_compact::<K>(kid, key, typ, alg.clone(), payload);

            let msg = res.expect("Unable _sign_compact");

            let mut buf = vec![];
            let msg = jws::parse_compact(&msg, &mut buf).expect("Unable parse_compact");

            assert_eq!(
                msg.payload,
                base64::encode_config(payload, base64::URL_SAFE_NO_PAD)
            );

            assert_eq!(msg.parsed_header.typ, typ);
            assert_eq!(msg.parsed_header.alg, alg);
            assert_eq!(msg.parsed_header.kid, kid);

            let pkey = K::from_jwk(pkey).expect("Unable from_jwk");
            let valid = msg.verify::<K>(&pkey).expect("Unable verify");

            assert!(valid);
        }
    }

    #[test]
    fn sign_compact_works_incompatible_alg() {
        _sign_compact_works_incompatible_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            "example-typ-1",
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            "example-typ-1",
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            "example-typ-1",
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            "example-typ-1",
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            "example-typ-1",
            Algorithm::Es256K,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            "example-typ-1",
            Algorithm::Es256,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            "example-typ-1",
            Algorithm::EdDSA,
            PAYLOAD,
        );

        _sign_compact_works_incompatible_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            "example-typ-1",
            Algorithm::Es256,
            PAYLOAD,
        );

        fn _sign_compact_works_incompatible_alg<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            typ: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign_compact::<K>(kid, key, typ, alg.clone(), payload);

            let err = res.expect_err("res is ok");
            assert_eq!(err.kind(), ErrorKind::InvalidState);

            assert_eq!(
                format!("{}", err),
                "Invalid state: Unable create signature: Unsupported signature type"
            );
        }
    }

    #[test]
    fn sign_compact_works_unknown_alg() {
        _sign_compact_works_unknown_alg::<Ed25519KeyPair>(
            ALICE_KID_ED25519,
            ALICE_KEY_ED25519,
            "example-typ-1",
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        _sign_compact_works_unknown_alg::<P256KeyPair>(
            ALICE_KID_P256,
            ALICE_KEY_P256,
            "example-typ-1",
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        _sign_compact_works_unknown_alg::<K256KeyPair>(
            ALICE_KID_K256,
            ALICE_KEY_K256,
            "example-typ-1",
            Algorithm::Other("bls".to_owned()),
            PAYLOAD,
        );

        fn _sign_compact_works_unknown_alg<K: FromJwk + KeySign + KeySigVerify>(
            kid: &str,
            key: &str,
            typ: &str,
            alg: Algorithm,
            payload: &str,
        ) {
            let res = _sign_compact::<K>(kid, key, typ, alg.clone(), payload);

            let err = res.expect_err("res is ok");
            assert_eq!(err.kind(), ErrorKind::Unsupported);

            assert_eq!(
                format!("{}", err),
                "Unsupported crypto or method: Unsupported signature type"
            );
        }
    }

    fn _sign<K: FromJwk + KeySign>(
        kid: &str,
        key: &str,
        alg: Algorithm,
        payload: &str,
    ) -> Result<String> {
        let key = K::from_jwk(key).expect("Unable from_jwk");
        jws::sign(payload.as_bytes(), (&kid, &key), alg.clone())
    }

    fn _sign_compact<K: FromJwk + KeySign>(
        kid: &str,
        key: &str,
        typ: &str,
        alg: Algorithm,
        payload: &str,
    ) -> Result<String> {
        let key = K::from_jwk(key).expect("Unable from_jwk");
        jws::sign_compact(payload.as_bytes(), (&kid, &key), typ, alg.clone())
    }

    const ALICE_KID_ED25519: &str = "did:example:alice#key-1";

    const ALICE_KEY_ED25519: &str = r#"
    {
        "kty":"OKP",
        "d":"pFRUKkyzx4kHdJtFSnlPA9WzqkDT1HWV0xZ5OYZd2SY",
        "crv":"Ed25519",
        "x":"G-boxFB6vOZBu-wXkm-9Lh79I8nf9Z50cILaOgKKGww"
    }
    "#;

    const ALICE_PKEY_ED25519: &str = r#"
    {
        "kty":"OKP",
        "crv":"Ed25519",
        "x":"G-boxFB6vOZBu-wXkm-9Lh79I8nf9Z50cILaOgKKGww"
    }
    "#;

    const ALICE_KID_P256: &str = "did:example:alice#key-2";

    const ALICE_KEY_P256: &str = r#"
    {
        "kty":"EC",
        "d":"7TCIdt1rhThFtWcEiLnk_COEjh1ZfQhM4bW2wz-dp4A",
        "crv":"P-256",
        "x":"2syLh57B-dGpa0F8p1JrO6JU7UUSF6j7qL-vfk1eOoY",
        "y":"BgsGtI7UPsObMRjdElxLOrgAO9JggNMjOcfzEPox18w"
    }
    "#;

    const ALICE_PKEY_P256: &str = r#"
    {
        "kty":"EC",
        "crv":"P-256",
        "x":"2syLh57B-dGpa0F8p1JrO6JU7UUSF6j7qL-vfk1eOoY",
        "y":"BgsGtI7UPsObMRjdElxLOrgAO9JggNMjOcfzEPox18w"
    }
    "#;

    const ALICE_KID_K256: &str = "did:example:alice#key-3";

    const ALICE_KEY_K256: &str = r#"
    {
        "kty":"EC",
        "d":"N3Hm1LXA210YVGGsXw_GklMwcLu_bMgnzDese6YQIyA",
        "crv":"secp256k1",
        "x":"aToW5EaTq5mlAf8C5ECYDSkqsJycrW-e1SQ6_GJcAOk",
        "y":"JAGX94caA21WKreXwYUaOCYTBMrqaX4KWIlsQZTHWCk"
    }
    "#;

    const ALICE_PKEY_K256: &str = r#"
    {
        "kty":"EC",
        "d":"N3Hm1LXA210YVGGsXw_GklMwcLu_bMgnzDese6YQIyA",
        "x":"aToW5EaTq5mlAf8C5ECYDSkqsJycrW-e1SQ6_GJcAOk",
        "y":"JAGX94caA21WKreXwYUaOCYTBMrqaX4KWIlsQZTHWCk"
    }
    "#;

    const PAYLOAD: &str = r#"{"id":"1234567890","typ":"application/didcomm-plain+json","type":"http://example.com/protocols/lets_do_lunch/1.0/proposal","from":"did:example:alice","to":["did:example:bob"],"created_time":1516269022,"expires_time":1516385931,"body":{"messagespecificattribute":"and its value"}}"#;
}