rtci-dtls 0.2.1

Sans-I/O DTLS 1.2 and 1.3 (RFC 6347, RFC 9147) with DTLS-SRTP key export, for WebRTC
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
use super::crypto_ccm::*;
use super::*;
use crate::content::ContentType;
use crate::record_layer::record_layer_header::{ProtocolVersion, RECORD_LAYER_HEADER_SIZE};
use crate::signature_hash_algorithm::HashAlgorithm;

#[test]
fn test_generate_key_signature() -> Result<()> {
    let provider = crypto::default_provider().map_err(crypto_error)?;
    let scheme = crypto::SignatureScheme::EcdsaP256Sha256;
    let signing_key = provider
        .crypto()
        .generate_signing_key(scheme)
        .map_err(crypto_error)?;
    let private_key = CryptoPrivateKey::from_signing_key(signing_key.clone());

    let client_random = vec![
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
        0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
        0x1e, 0x1f,
    ];
    let server_random = vec![
        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e,
        0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
        0x8e, 0x8f,
    ];
    let public_key = vec![
        0x20, 0x9f, 0xd7, 0xad, 0x6d, 0xcf, 0xf4, 0x29, 0x8d, 0xd3, 0xf9, 0x6d, 0x5b, 0x1b, 0x2a,
        0xf9, 0x10, 0xa0, 0x53, 0x5b, 0x14, 0x88, 0xd7, 0xf8, 0xfa, 0xbb, 0x34, 0x9a, 0x98, 0x28,
        0x80, 0xb6, 0x15,
    ];
    let signature = generate_key_signature(
        &client_random,
        &server_random,
        &public_key,
        NamedCurve::X25519,
        &SignatureHashAlgorithm {
            hash: HashAlgorithm::Sha256,
            signature: SignatureAlgorithm::Ecdsa,
        },
        &private_key,
    )?;

    provider
        .crypto()
        .verify_signature(
            scheme,
            signing_key.public_key(),
            &value_key_message(
                &client_random,
                &server_random,
                &public_key,
                NamedCurve::X25519,
            ),
            &signature,
        )
        .map_err(crypto_error)?;

    Ok(())
}

#[test]
fn test_exported_signing_key_can_be_imported() -> Result<()> {
    let provider = crypto::default_provider().map_err(crypto_error)?;
    let scheme = crypto::SignatureScheme::EcdsaP256Sha256;
    let generated = provider
        .crypto()
        .generate_signing_key(scheme)
        .map_err(crypto_error)?;
    let pkcs8 = generated
        .to_pkcs8_der()
        .map_err(crypto_error)?
        .expect("built-in generated keys are exportable");
    let imported = provider
        .crypto()
        .import_signing_key(scheme, pkcs8.as_ref())
        .map_err(crypto_error)?;
    let signature = imported
        .sign(scheme, b"imported DTLS key")
        .map_err(crypto_error)?;

    provider
        .crypto()
        .verify_signature(
            scheme,
            imported.public_key(),
            b"imported DTLS key",
            &signature,
        )
        .map_err(crypto_error)
}

#[cfg(all(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
#[test]
fn test_cross_provider_signature_verification() -> Result<()> {
    // The providers are concrete types here, not `dyn RTCCryptoProvider`, so the trait has to
    // be in scope for `.crypto()`. Scoped to this test because it is the only one that needs it
    // and the test only exists when both provider features are on.
    use crypto::RTCCryptoProvider;

    let ring = crypto::providers::RingProvider::new();
    let aws = crypto::providers::AwsLcRsProvider::new();
    let scheme = crypto::SignatureScheme::EcdsaP256Sha256;

    for (signer, verifier) in [
        (
            ring.crypto() as &dyn crypto::RTCCrypto,
            aws.crypto() as &dyn crypto::RTCCrypto,
        ),
        (
            aws.crypto() as &dyn crypto::RTCCrypto,
            ring.crypto() as &dyn crypto::RTCCrypto,
        ),
    ] {
        let key = signer.generate_signing_key(scheme).map_err(crypto_error)?;
        let signature = key
            .sign(scheme, b"cross-provider DTLS signature")
            .map_err(crypto_error)?;
        verifier
            .verify_signature(
                scheme,
                key.public_key(),
                b"cross-provider DTLS signature",
                &signature,
            )
            .map_err(crypto_error)?;
    }

    Ok(())
}

#[test]
fn test_ccm_encryption_and_decryption() -> Result<()> {
    let key = vec![
        0x18, 0x78, 0xac, 0xc2, 0x2a, 0xd8, 0xbd, 0xd8, 0xc6, 0x01, 0xa6, 0x17, 0x12, 0x6f, 0x63,
        0x54,
    ];
    let iv = vec![0x0e, 0xb2, 0x09, 0x06];

    let mut ccm = CryptoCcm::new(
        crypto::default_provider().map_err(crypto_error)?,
        &CryptoCcmTagLen::CryptoCcmTagLength,
        &key,
        &iv,
        &key,
        &iv,
    )?;

    let rlh = RecordLayerHeader {
        content_type: ContentType::ApplicationData,
        protocol_version: ProtocolVersion {
            major: 0xfe,
            minor: 0xff,
        },
        epoch: 0,
        sequence_number: 18,
        content_len: 3,
    };

    let raw = vec![
        0x17, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x03, 0xff, 0xaa,
        0xbb,
    ];

    let cipher_text = ccm.encrypt(&rlh, &raw)?;

    assert_eq!(
        &cipher_text[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE],
        [0, 27],
        "RecordLayer size updating failed \nexp: {:?} \nactual {:?} ",
        [0, 27],
        &cipher_text[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE]
    );

    let plain_text = ccm.decrypt(&cipher_text)?;

    assert_eq!(
        raw[RECORD_LAYER_HEADER_SIZE..],
        plain_text[RECORD_LAYER_HEADER_SIZE..],
        "Decryption failed \nexp: {:?} \nactual {:?} ",
        &raw[RECORD_LAYER_HEADER_SIZE..],
        &plain_text[RECORD_LAYER_HEADER_SIZE..]
    );

    Ok(())
}

#[test]
fn test_certificate_verify() -> Result<()> {
    let provider = crypto::default_provider().map_err(crypto_error)?;
    let plain_text: Vec<u8> = vec![
        0x6f, 0x47, 0x97, 0x85, 0xcc, 0x76, 0x50, 0x93, 0xbd, 0xe2, 0x6a, 0x69, 0x0b, 0xc3, 0x03,
        0xd1, 0xb7, 0xe4, 0xab, 0x88, 0x7b, 0xa6, 0x52, 0x80, 0xdf, 0xaa, 0x25, 0x7a, 0xdb, 0x29,
        0x32, 0xe4, 0xd8, 0x28, 0x28, 0xb3, 0xe8, 0x04, 0x3c, 0x38, 0x16, 0xfc, 0x78, 0xe9, 0x15,
        0x7b, 0xc5, 0xbd, 0x7d, 0xfc, 0xcd, 0x83, 0x00, 0x57, 0x4a, 0x3c, 0x23, 0x85, 0x75, 0x6b,
        0x37, 0xd5, 0x89, 0x72, 0x73, 0xf0, 0x44, 0x8c, 0x00, 0x70, 0x1f, 0x6e, 0xa2, 0x81, 0xd0,
        0x09, 0xc5, 0x20, 0x36, 0xab, 0x23, 0x09, 0x40, 0x1f, 0x4d, 0x45, 0x96, 0x62, 0xbb, 0x81,
        0xb0, 0x30, 0x72, 0xad, 0x3a, 0x0a, 0xac, 0x31, 0x63, 0x40, 0x52, 0x0a, 0x27, 0xf3, 0x34,
        0xde, 0x27, 0x7d, 0xb7, 0x54, 0xff, 0x0f, 0x9f, 0x5a, 0xfe, 0x07, 0x0f, 0x4e, 0x9f, 0x53,
        0x04, 0x34, 0x62, 0xf4, 0x30, 0x74, 0x83, 0x35, 0xfc, 0xe4, 0x7e, 0xbf, 0x5a, 0xc4, 0x52,
        0xd0, 0xea, 0xf9, 0x61, 0x4e, 0xf5, 0x1c, 0x0e, 0x58, 0x02, 0x71, 0xfb, 0x1f, 0x34, 0x55,
        0xe8, 0x36, 0x70, 0x3c, 0xc1, 0xcb, 0xc9, 0xb7, 0xbb, 0xb5, 0x1c, 0x44, 0x9a, 0x6d, 0x88,
        0x78, 0x98, 0xd4, 0x91, 0x2e, 0xeb, 0x98, 0x81, 0x23, 0x30, 0x73, 0x39, 0x43, 0xd5, 0xbb,
        0x70, 0x39, 0xba, 0x1f, 0xdb, 0x70, 0x9f, 0x91, 0x83, 0x56, 0xc2, 0xde, 0xed, 0x17, 0x6d,
        0x2c, 0x3e, 0x21, 0xea, 0x36, 0xb4, 0x91, 0xd8, 0x31, 0x05, 0x60, 0x90, 0xfd, 0xc6, 0x74,
        0xa9, 0x7b, 0x18, 0xfc, 0x1c, 0x6a, 0x1c, 0x6e, 0xec, 0xd3, 0xc1, 0xc0, 0x0d, 0x11, 0x25,
        0x48, 0x37, 0x3d, 0x45, 0x11, 0xa2, 0x31, 0x14, 0x0a, 0x66, 0x9f, 0xd8, 0xac, 0x74, 0xa2,
        0xcd, 0xc8, 0x79, 0xb3, 0x9e, 0xc6, 0x66, 0x25, 0xcf, 0x2c, 0x87, 0x5e, 0x5c, 0x36, 0x75,
        0x86,
    ];

    //test ECDSA256
    let certificate_ecdsa256 = Certificate::generate_self_signed(
        vec!["localhost".to_owned()],
        crypto::default_provider().map_err(crypto_error)?.crypto(),
    )?;
    let ecdsa_algorithm = SignatureHashAlgorithm {
        hash: HashAlgorithm::Sha256,
        signature: SignatureAlgorithm::Ecdsa,
    };
    let cert_verify_ecdsa256 = generate_certificate_verify(
        &plain_text,
        &ecdsa_algorithm,
        &certificate_ecdsa256.private_key,
    )?;
    verify_certificate_verify(
        provider.crypto(),
        &plain_text,
        &ecdsa_algorithm,
        &cert_verify_ecdsa256,
        &certificate_ecdsa256
            .certificate
            .iter()
            .map(|x| x.as_ref().to_owned())
            .collect::<Vec<Vec<u8>>>(),
        false,
    )?;

    //test ED25519
    let certificate_ed25519 = Certificate::generate_self_signed_with_alg(
        vec!["localhost".to_owned()],
        &rcgen::PKCS_ED25519,
        crypto::default_provider().map_err(crypto_error)?.crypto(),
    )?;
    let ed25519_algorithm = SignatureHashAlgorithm {
        hash: HashAlgorithm::Sha256,
        signature: SignatureAlgorithm::Ed25519,
    };
    let cert_verify_ed25519 = generate_certificate_verify(
        &plain_text,
        &ed25519_algorithm,
        &certificate_ed25519.private_key,
    )?;
    verify_certificate_verify(
        provider.crypto(),
        &plain_text,
        &ed25519_algorithm,
        &cert_verify_ed25519,
        &certificate_ed25519
            .certificate
            .iter()
            .map(|x| x.as_ref().to_owned())
            .collect::<Vec<Vec<u8>>>(),
        false,
    )?;

    Ok(())
}

#[test]
fn test_verify_key_signature_ecdsa_p384_sha256() -> Result<()> {
    let provider = crypto::default_provider().map_err(crypto_error)?;

    const CERT_DER: &[u8] = &[
        0x30, 0x82, 0x01, 0x51, 0x30, 0x81, 0xd8, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x01,
        0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03, 0x30, 0x14, 0x31,
        0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c,
        0x68, 0x6f, 0x73, 0x74, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x35, 0x30, 0x31, 0x30, 0x31, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x17, 0x0d, 0x33, 0x35, 0x30, 0x31, 0x30, 0x31, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x30, 0x14, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55,
        0x04, 0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x76,
        0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81,
        0x04, 0x00, 0x22, 0x03, 0x62, 0x00, 0x04, 0xd9, 0xf9, 0xfe, 0x7a, 0xe3, 0xc8, 0x03, 0x88,
        0x78, 0xd1, 0x2b, 0x44, 0xab, 0xa2, 0x6a, 0xfd, 0x54, 0x0a, 0x7b, 0xe7, 0x94, 0x29, 0xf3,
        0x82, 0x7a, 0xb9, 0x78, 0x02, 0xbc, 0x11, 0x6a, 0xc0, 0xa8, 0x34, 0x47, 0xf3, 0xa6, 0x79,
        0x7f, 0xca, 0x37, 0xea, 0x6a, 0x80, 0x3f, 0xcc, 0xb4, 0x2b, 0xd5, 0x02, 0x9f, 0x1f, 0x9d,
        0x10, 0xe7, 0x6b, 0x6a, 0x4c, 0x26, 0x0d, 0xa1, 0x53, 0x56, 0x62, 0x49, 0x93, 0xc1, 0x46,
        0xa6, 0x83, 0x1d, 0x17, 0xcb, 0xbb, 0xe9, 0x6e, 0xaf, 0xe2, 0xa3, 0x77, 0x59, 0x88, 0x2d,
        0x03, 0x41, 0xa8, 0x45, 0xd7, 0xd7, 0x7d, 0xbd, 0x64, 0x1d, 0x79, 0x0e, 0x61, 0x30, 0x0a,
        0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03, 0x03, 0x68, 0x00, 0x30, 0x65,
        0x02, 0x31, 0x00, 0xf6, 0xdc, 0xe5, 0x18, 0x22, 0x6b, 0xd4, 0xcc, 0x23, 0x58, 0x2c, 0x9c,
        0xe9, 0x19, 0xed, 0x53, 0x96, 0xec, 0xe3, 0x08, 0xf2, 0xcf, 0xc3, 0xac, 0x92, 0x66, 0x9d,
        0x87, 0x45, 0xe8, 0xc3, 0x69, 0x5a, 0xa1, 0x38, 0xbe, 0xc6, 0xbe, 0xfa, 0xb7, 0xc4, 0xe4,
        0xa7, 0xdb, 0xe2, 0xef, 0x2d, 0x8b, 0x02, 0x30, 0x4c, 0x45, 0x5d, 0xaa, 0x5e, 0x44, 0x07,
        0x28, 0xd3, 0x49, 0x3b, 0xcd, 0xff, 0x3a, 0x2e, 0x99, 0xf6, 0x07, 0x0a, 0x47, 0x30, 0xef,
        0xb8, 0x53, 0x62, 0xbe, 0xe6, 0x0b, 0xab, 0xc6, 0xd5, 0x24, 0x46, 0x5b, 0x85, 0x6e, 0x54,
        0x2f, 0xa6, 0xfd, 0x1d, 0xbd, 0x98, 0x1f, 0x32, 0x93, 0xf2, 0x86,
    ];
    const SIGNATURE: &[u8] = &[
        0x30, 0x65, 0x02, 0x30, 0x47, 0x16, 0xc1, 0xe8, 0xbf, 0x6b, 0x46, 0x4d, 0x13, 0x15, 0xf1,
        0x70, 0xe0, 0xf6, 0xb9, 0xba, 0x20, 0x92, 0x15, 0xa9, 0x0b, 0x69, 0xb0, 0xad, 0xe6, 0x38,
        0x7a, 0x58, 0x81, 0x5b, 0x2a, 0xa6, 0xd0, 0x8f, 0x96, 0x6f, 0x49, 0x5e, 0x80, 0xbd, 0x2e,
        0xb7, 0x7e, 0x6b, 0x5d, 0x83, 0x21, 0x8f, 0x02, 0x31, 0x00, 0x95, 0x05, 0xe1, 0x74, 0x3d,
        0x4b, 0xd0, 0x7f, 0x55, 0x0b, 0x83, 0x86, 0x1a, 0x34, 0x85, 0xc1, 0x54, 0x68, 0xfb, 0x08,
        0x7a, 0x59, 0x71, 0x9d, 0xb3, 0xdd, 0x23, 0x7e, 0xd6, 0x1e, 0x12, 0x43, 0x66, 0xf5, 0xc2,
        0xea, 0x4a, 0x6e, 0x80, 0x1d, 0xab, 0x4e, 0xb7, 0xaa, 0xe6, 0x6d, 0x26, 0xfe,
    ];

    let message = b"dtls-verify-key-signature-p384-sha256";
    let algorithm = SignatureHashAlgorithm {
        hash: HashAlgorithm::Sha256,
        signature: SignatureAlgorithm::Ecdsa,
    };

    let raw_certs = vec![CERT_DER.to_vec()];

    verify_key_signature(
        provider.crypto(),
        message,
        &algorithm,
        SIGNATURE,
        &raw_certs,
        false,
    )?;

    Ok(())
}

#[derive(Debug)]
struct MockSigner {
    call_count: std::sync::Arc<std::sync::Mutex<usize>>,
    last_message: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
    signature: Vec<u8>,
}

impl SigningKey for MockSigner {
    fn supports(&self, _scheme: CryptoSignatureScheme) -> bool {
        true
    }

    fn public_key(&self) -> PublicKey<'_> {
        PublicKey {
            encoding: PublicKeyEncoding::SubjectPublicKeyInfoDer,
            bytes: &[],
        }
    }

    fn sign(
        &self,
        _scheme: CryptoSignatureScheme,
        message: &[u8],
    ) -> std::result::Result<Vec<u8>, crypto::CryptoError> {
        *self.call_count.lock().unwrap() += 1;
        *self.last_message.lock().unwrap() = message.to_vec();
        Ok(self.signature.clone())
    }
}

#[test]
fn test_external_signing_key_is_invoked_for_signing() -> Result<()> {
    let expected_signature = vec![0xca, 0xfe, 0xba, 0xbe];
    let call_count = std::sync::Arc::new(std::sync::Mutex::new(0usize));
    let last_message = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

    let private_key = CryptoPrivateKey::from_signing_key(std::sync::Arc::new(MockSigner {
        call_count: std::sync::Arc::clone(&call_count),
        last_message: std::sync::Arc::clone(&last_message),
        signature: expected_signature.clone(),
    }));
    assert!(
        private_key
            .signing_key
            .to_pkcs8_der()
            .map_err(crypto_error)?
            .is_none()
    );

    let client_random = [0x01u8, 0x02, 0x03, 0x04];
    let server_random = [0x05u8, 0x06, 0x07, 0x08];
    let public_key = [0x09u8, 0x0a, 0x0b];
    let named_curve = NamedCurve::X25519;
    let expected_key_message =
        value_key_message(&client_random, &server_random, &public_key, named_curve);
    let algorithm = SignatureHashAlgorithm {
        hash: HashAlgorithm::Sha256,
        signature: SignatureAlgorithm::Ecdsa,
    };

    let key_signature = generate_key_signature(
        &client_random,
        &server_random,
        &public_key,
        named_curve,
        &algorithm,
        &private_key,
    )?;

    assert_eq!(*call_count.lock().unwrap(), 1);
    assert_eq!(&*last_message.lock().unwrap(), &expected_key_message);
    assert_eq!(key_signature, expected_signature);

    let handshake_bodies = b"certificate-verify-handshake-bodies";
    let cert_verify = generate_certificate_verify(handshake_bodies, &algorithm, &private_key)?;

    assert_eq!(*call_count.lock().unwrap(), 2);
    assert_eq!(&*last_message.lock().unwrap(), handshake_bodies);
    assert_eq!(cert_verify, expected_signature);

    Ok(())
}

/// An RSA-2048 certificate (its key `dtls13/testdata/rsa-2048.pkcs8.pem`) and an
/// RSASSA-PKCS1-v1_5 SHA-256 signature over `message` made with the raw private operation
/// over the EMSA-PKCS1-v1_5 encoding whose DigestInfo starts `digest_info_prefix` (RFC 8017
/// section 9.2), so that the test chooses the DigestInfo form the providers' signers do not.
fn rsa_certificate_and_raw_signature(
    message: &[u8],
    digest_info_prefix: &[u8],
) -> Result<(Vec<u8>, Vec<u8>)> {
    use der_parser::num_bigint::BigUint;
    let key_pair = rcgen::KeyPair::from_pem(include_str!("../dtls13/testdata/rsa-2048.pkcs8.pem"))
        .map_err(|e| Error::Other(e.to_string()))?;
    let certificate = rcgen::CertificateParams::new(vec!["rsa-digest-info".to_owned()])
        .map_err(|e| Error::Other(e.to_string()))?
        .self_signed(&key_pair)
        .map_err(|e| Error::Other(e.to_string()))?;
    // PKCS#8 PrivateKeyInfo { version, algorithm, OCTET STRING RSAPrivateKey { version, n, e,
    // d, ... } } (RFC 5208, RFC 8017 appendix A.1.2).
    let pkcs8 = key_pair.serialize_der();
    let bad = |e: der_parser::error::BerError| Error::Other(e.to_string());
    let (_, info) = der_parser::parse_der(&pkcs8).map_err(|e| Error::Other(e.to_string()))?;
    let private_key = info.as_sequence().map_err(bad)?[2]
        .as_slice()
        .map_err(bad)?;
    let (_, rsa) = der_parser::parse_der(private_key).map_err(|e| Error::Other(e.to_string()))?;
    let rsa = rsa.as_sequence().map_err(bad)?;
    let n = rsa[1].as_biguint().map_err(bad)?;
    let d = rsa[3].as_biguint().map_err(bad)?;
    let k = n.bits().div_ceil(8) as usize;
    let provider = crypto::default_provider().map_err(crypto_error)?;
    let digest = provider
        .crypto()
        .hash(crypto::HashAlgorithm::Sha256, message)
        .map_err(crypto_error)?;
    let t_len = digest_info_prefix.len() + digest.len();
    let mut em = vec![0x00, 0x01];
    em.resize(k - t_len - 1, 0xff);
    em.push(0x00);
    em.extend_from_slice(digest_info_prefix);
    em.extend_from_slice(&digest);
    let s = BigUint::from_bytes_be(&em).modpow(&d, &n).to_bytes_be();
    let mut signature = vec![0u8; k - s.len()];
    signature.extend_from_slice(&s);
    Ok((certificate.der().to_vec(), signature))
}

/// The SHA-256 DigestInfo prefixes: with NULL parameters (what every signer writes), and
/// without parameters.
const SHA256_DIGEST_INFO_NULL: &[u8] = &[
    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
    0x00, 0x04, 0x20,
];
const SHA256_DIGEST_INFO_ABSENT: &[u8] = &[
    0x30, 0x2f, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x04,
    0x20,
];

/// RFC 5246 section 4.7: "the DigestInfo.AlgorithmIdentifier.parameters field MUST be NULL,
/// but implementations MUST accept both without parameters and with NULL parameters." A
/// ServerKeyExchange signature in either form verifies; a changed signature or message, and a
/// DigestInfo of another hash, does not.
#[test]
fn rsa_pkcs1_signatures_with_and_without_null_digest_parameters_are_accepted() -> Result<()> {
    let provider = crypto::default_provider().map_err(crypto_error)?;
    let algorithm = SignatureHashAlgorithm {
        hash: HashAlgorithm::Sha256,
        signature: SignatureAlgorithm::Rsa,
    };
    let message = b"server key exchange params";
    for (form, prefix) in [
        ("NULL parameters", SHA256_DIGEST_INFO_NULL),
        ("no parameters", SHA256_DIGEST_INFO_ABSENT),
    ] {
        let (certificate, signature) = rsa_certificate_and_raw_signature(message, prefix)?;
        let raw_certificates = vec![certificate];
        verify_key_signature(
            provider.crypto(),
            message,
            &algorithm,
            &signature,
            &raw_certificates,
            false,
        )
        .unwrap_or_else(|e| panic!("{form}: {e}"));
        assert!(
            verify_key_signature(
                provider.crypto(),
                b"another message",
                &algorithm,
                &signature,
                &raw_certificates,
                false,
            )
            .is_err(),
            "{form}: another message"
        );
        let mut changed = signature.clone();
        changed[100] ^= 1;
        assert!(
            verify_key_signature(
                provider.crypto(),
                message,
                &algorithm,
                &changed,
                &raw_certificates,
                false,
            )
            .is_err(),
            "{form}: a changed signature"
        );
    }
    // The DigestInfo names SHA-256: as a SHA-384 signature it is refused in both forms.
    let (certificate, signature) =
        rsa_certificate_and_raw_signature(message, SHA256_DIGEST_INFO_ABSENT)?;
    assert!(
        verify_key_signature(
            provider.crypto(),
            message,
            &SignatureHashAlgorithm {
                hash: HashAlgorithm::Sha384,
                signature: SignatureAlgorithm::Rsa,
            },
            &signature,
            &[certificate],
            false,
        )
        .is_err()
    );
    Ok(())
}