Skip to main content

rtci_crypto/
conformance.rs

1//! Reusable conformance assertions for built-in and application-provided crypto providers.
2
3use crate::{
4    AeadAlgorithm, BlockCipherAlgorithm, CbcAlgorithm, CryptoAlgorithm, CryptoError, HashAlgorithm,
5    HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, PublicKey, PublicKeyEncoding,
6    RTCCrypto, RTCCryptoProvider, SignatureScheme, StreamCipherAlgorithm, hkdf_expand,
7    hkdf_expand_label, hkdf_extract,
8};
9
10/// Exercises the complete initial RTC crypto contract implemented by the built-in providers.
11///
12/// This helper panics on a contract violation so provider authors can call it directly from a
13/// normal `#[test]` function.
14pub fn assert_provider(provider: &dyn RTCCryptoProvider) {
15    assert_basic_capabilities(provider.crypto());
16    assert_hashes_and_hmac(provider.crypto());
17    assert_block_and_stream_ciphers(provider.crypto());
18    assert_cbc(provider.crypto());
19    assert_aead(provider.crypto());
20    assert_key_exchange(provider.crypto());
21    assert_key_exchange_respond(provider.crypto());
22    assert_signatures(provider.crypto());
23    assert_tls13_key_schedule(provider.crypto());
24    assert_header_masks(provider.crypto());
25    assert_rsa_pss(provider.crypto());
26    assert_random(provider);
27}
28
29fn assert_basic_capabilities(crypto: &dyn RTCCrypto) {
30    let capabilities = [
31        CryptoAlgorithm::Hash(HashAlgorithm::Md5),
32        CryptoAlgorithm::Hash(HashAlgorithm::Sha256),
33        CryptoAlgorithm::Hash(HashAlgorithm::Sha384),
34        CryptoAlgorithm::Hmac(HmacAlgorithm::Sha1),
35        CryptoAlgorithm::Hmac(HmacAlgorithm::Sha256),
36        CryptoAlgorithm::Hmac(HmacAlgorithm::Sha512),
37        CryptoAlgorithm::Hmac(HmacAlgorithm::Sha384),
38        CryptoAlgorithm::HeaderMask(HeaderMaskAlgorithm::Aes128),
39        CryptoAlgorithm::HeaderMask(HeaderMaskAlgorithm::Aes256),
40        CryptoAlgorithm::HeaderMask(HeaderMaskAlgorithm::ChaCha20),
41        CryptoAlgorithm::Signature(SignatureScheme::RsaPssSha256),
42        CryptoAlgorithm::Signature(SignatureScheme::RsaPssSha384),
43        CryptoAlgorithm::Signature(SignatureScheme::RsaPssSha512),
44        CryptoAlgorithm::BlockCipher(BlockCipherAlgorithm::Aes128),
45        CryptoAlgorithm::BlockCipher(BlockCipherAlgorithm::Aes256),
46        CryptoAlgorithm::BlockCipher(BlockCipherAlgorithm::Aes192),
47        CryptoAlgorithm::StreamCipher(StreamCipherAlgorithm::Aes128Ctr),
48        CryptoAlgorithm::StreamCipher(StreamCipherAlgorithm::Aes256Ctr),
49        CryptoAlgorithm::StreamCipher(StreamCipherAlgorithm::Aes192Ctr),
50        CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc),
51        CryptoAlgorithm::Aead(AeadAlgorithm::Aes128Gcm),
52        CryptoAlgorithm::Aead(AeadAlgorithm::Aes256Gcm),
53        CryptoAlgorithm::Aead(AeadAlgorithm::Aes128Ccm),
54        CryptoAlgorithm::Aead(AeadAlgorithm::Aes128Ccm8),
55        CryptoAlgorithm::Aead(AeadAlgorithm::ChaCha20Poly1305),
56        CryptoAlgorithm::KeyExchange(KeyExchangeAlgorithm::P256),
57        CryptoAlgorithm::KeyExchange(KeyExchangeAlgorithm::P384),
58        CryptoAlgorithm::KeyExchange(KeyExchangeAlgorithm::X25519),
59        CryptoAlgorithm::Signature(SignatureScheme::Ed25519),
60        CryptoAlgorithm::Signature(SignatureScheme::EcdsaP256Sha256),
61        CryptoAlgorithm::Signature(SignatureScheme::EcdsaP384Sha256),
62        CryptoAlgorithm::Signature(SignatureScheme::EcdsaP384Sha384),
63        CryptoAlgorithm::Signature(SignatureScheme::RsaPkcs1Sha1),
64        CryptoAlgorithm::Signature(SignatureScheme::RsaPkcs1Sha256),
65        CryptoAlgorithm::Signature(SignatureScheme::RsaPkcs1Sha384),
66        CryptoAlgorithm::Signature(SignatureScheme::RsaPkcs1Sha512),
67        CryptoAlgorithm::SigningKeyGeneration(SignatureScheme::Ed25519),
68        CryptoAlgorithm::SigningKeyGeneration(SignatureScheme::EcdsaP256Sha256),
69        CryptoAlgorithm::SigningKeyImport(SignatureScheme::Ed25519),
70        CryptoAlgorithm::SigningKeyImport(SignatureScheme::EcdsaP256Sha256),
71        CryptoAlgorithm::SigningKeyImport(SignatureScheme::RsaPkcs1Sha256),
72    ];
73    for capability in capabilities {
74        assert!(
75            crypto.supports(capability),
76            "missing capability: {capability:?}"
77        );
78    }
79    // RSA key generation: what the provider says it supports, it does; otherwise an explicit
80    // unsupported-algorithm error (ring has no RSA key generation).
81    if crypto.supports(CryptoAlgorithm::SigningKeyGeneration(
82        SignatureScheme::RsaPkcs1Sha256,
83    )) {
84        assert!(
85            crypto
86                .generate_signing_key(SignatureScheme::RsaPkcs1Sha256)
87                .is_ok()
88        );
89    } else {
90        assert!(matches!(
91            crypto.generate_signing_key(SignatureScheme::RsaPkcs1Sha256),
92            Err(CryptoError::UnsupportedAlgorithm(_))
93        ));
94    }
95    for scheme in [
96        SignatureScheme::Ed25519,
97        SignatureScheme::EcdsaP256Sha256,
98        SignatureScheme::RsaPkcs1Sha256,
99    ] {
100        assert!(matches!(
101            crypto.import_signing_key(scheme, b"not a PKCS#8 key"),
102            Err(CryptoError::InvalidPrivateKey)
103        ));
104    }
105}
106
107/// Checks hash and HMAC known-answer vectors and their error contract.
108pub fn assert_hashes_and_hmac(crypto: &dyn RTCCrypto) {
109    // RFC 1321, FIPS 180-4, RFC 2202, and RFC 4231 known-answer vectors.
110    assert_eq!(
111        crypto.hash(HashAlgorithm::Md5, b"abc").unwrap(),
112        bytes("900150983cd24fb0d6963f7d28e17f72")
113    );
114    assert_eq!(
115        crypto.hash(HashAlgorithm::Sha256, b"abc").unwrap(),
116        bytes("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
117    );
118    // The other certificate fingerprint hashes (RFC 8122 section 5) are optional for a
119    // provider; one that reports them must compute them right (FIPS 180-4 "abc" vectors).
120    for (algorithm, expected) in [
121        (
122            HashAlgorithm::Sha1,
123            "a9993e364706816aba3e25717850c26c9cd0d89d",
124        ),
125        (
126            HashAlgorithm::Sha224,
127            "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7",
128        ),
129        (
130            HashAlgorithm::Sha384,
131            "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
132             8086072ba1e7cc2358baeca134c825a7",
133        ),
134        (
135            HashAlgorithm::Sha512,
136            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
137             2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
138        ),
139    ] {
140        if crypto.supports(CryptoAlgorithm::Hash(algorithm)) {
141            assert_eq!(
142                crypto.hash(algorithm, b"abc").unwrap(),
143                bytes(expected),
144                "{algorithm:?}"
145            );
146        } else {
147            assert_eq!(
148                crypto.hash(algorithm, b"abc"),
149                Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Hash(
150                    algorithm
151                ))),
152                "{algorithm:?}"
153            );
154        }
155    }
156
157    let key = [0x0b; 20];
158    let mut sha1 = [0; 20];
159    let mut sha1_mac = crypto.new_hmac(HmacAlgorithm::Sha1, &key).unwrap();
160    assert_eq!(sha1_mac.output_len(), 20);
161    sha1_mac.sign(&[b"Hi ", b"There"], &mut sha1).unwrap();
162    assert_eq!(
163        sha1.as_slice(),
164        bytes("b617318655057264e28bc0b6fb378c8ef146be00")
165    );
166
167    // A keyed MAC is reusable: the second message must not be affected by the first.
168    let mut repeat = [0; 20];
169    sha1_mac.sign(&[b"Hi ", b"There"], &mut repeat).unwrap();
170    assert_eq!(repeat, sha1, "a Mac must produce the same tag when reused");
171
172    let mut sha256 = [0; 32];
173    let mut sha256_mac = crypto.new_hmac(HmacAlgorithm::Sha256, &key).unwrap();
174    sha256_mac.sign(&[b"Hi ", b"There"], &mut sha256).unwrap();
175    assert_eq!(
176        sha256.as_slice(),
177        bytes("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7")
178    );
179
180    // Splitting the input across slices must not change the tag.
181    let mut joined = [0; 32];
182    sha256_mac.sign(&[b"Hi There"], &mut joined).unwrap();
183    assert_eq!(joined, sha256, "slice boundaries must not affect the tag");
184
185    sha256_mac.verify(&[b"Hi There"], &sha256).unwrap();
186    let mut bad_tag = sha256;
187    bad_tag[0] ^= 1;
188    assert_eq!(
189        sha256_mac.verify(&[b"Hi There"], &bad_tag),
190        Err(CryptoError::AuthenticationFailed)
191    );
192    assert!(matches!(
193        sha256_mac.sign(&[b"x"], &mut [0; 31]),
194        Err(CryptoError::InvalidTagLength { .. })
195    ));
196
197    // RFC 4231 test case 1, HMAC-SHA-512.
198    let mut sha512 = [0; 64];
199    let mut sha512_mac = crypto.new_hmac(HmacAlgorithm::Sha512, &key).unwrap();
200    assert_eq!(sha512_mac.output_len(), 64);
201    sha512_mac.sign(&[b"Hi ", b"There"], &mut sha512).unwrap();
202    assert_eq!(
203        sha512.as_slice(),
204        bytes(concat!(
205            "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde",
206            "daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
207        ))
208    );
209    sha512_mac.verify(&[b"Hi There"], &sha512).unwrap();
210}
211
212/// Checks AES block and stream-cipher known-answer vectors and malformed inputs.
213pub fn assert_block_and_stream_ciphers(crypto: &dyn RTCCrypto) {
214    // FIPS 197 and NIST SP 800-38A known-answer vectors.
215    let mut block = bytes("00112233445566778899aabbccddeeff");
216    crypto
217        .block_encrypt(
218            BlockCipherAlgorithm::Aes128,
219            &bytes("000102030405060708090a0b0c0d0e0f"),
220            &mut block,
221        )
222        .unwrap();
223    assert_eq!(block, bytes("69c4e0d86a7b0430d8cdb78070b4c55a"));
224
225    let mut block = bytes("00112233445566778899aabbccddeeff");
226    crypto
227        .block_encrypt(
228            BlockCipherAlgorithm::Aes256,
229            &bytes("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"),
230            &mut block,
231        )
232        .unwrap();
233    assert_eq!(block, bytes("8ea2b7ca516745bfeafc49904b496089"));
234
235    let key = bytes("2b7e151628aed2a6abf7158809cf4f3c");
236    let iv = bytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
237    let plaintext = bytes("6bc1bee22e409f96e93d7e117393172a");
238    let mut encrypted = plaintext.clone();
239    crypto
240        .new_stream_cipher(StreamCipherAlgorithm::Aes128Ctr, &key)
241        .unwrap()
242        .apply_keystream(&iv, &mut encrypted)
243        .unwrap();
244    assert_eq!(encrypted, bytes("874d6191b620e3261bef6864990db6ce"));
245    crypto
246        .new_stream_cipher(StreamCipherAlgorithm::Aes128Ctr, &key)
247        .unwrap()
248        .apply_keystream(&iv, &mut encrypted)
249        .unwrap();
250    assert_eq!(encrypted, plaintext);
251
252    let key = bytes("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
253    let mut encrypted = plaintext.clone();
254    crypto
255        .new_stream_cipher(StreamCipherAlgorithm::Aes256Ctr, &key)
256        .unwrap()
257        .apply_keystream(&iv, &mut encrypted)
258        .unwrap();
259    assert_eq!(encrypted, bytes("601ec313775789a5b7a7f504bbf3d228"));
260
261    // AES-192 (RFC 6188): FIPS 197 Appendix C.2 and NIST SP 800-38A F.5.3.
262    let mut block = bytes("00112233445566778899aabbccddeeff");
263    crypto
264        .block_encrypt(
265            BlockCipherAlgorithm::Aes192,
266            &bytes("000102030405060708090a0b0c0d0e0f1011121314151617"),
267            &mut block,
268        )
269        .unwrap();
270    assert_eq!(block, bytes("dda97ca4864cdfe06eaf70a0ec0d7191"));
271    let key = bytes("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b");
272    let mut encrypted = plaintext.clone();
273    crypto
274        .new_stream_cipher(StreamCipherAlgorithm::Aes192Ctr, &key)
275        .unwrap()
276        .apply_keystream(&iv, &mut encrypted)
277        .unwrap();
278    assert_eq!(encrypted, bytes("1abc932417521ca24f2b0459fe7e6e0b"));
279    assert!(matches!(
280        crypto.new_stream_cipher(StreamCipherAlgorithm::Aes192Ctr, &[0; 16]),
281        Err(CryptoError::InvalidKeyLength { .. })
282    ));
283
284    assert!(matches!(
285        crypto.block_encrypt(BlockCipherAlgorithm::Aes128, &[0; 15], &mut [0; 16]),
286        Err(CryptoError::InvalidKeyLength { .. })
287    ));
288    assert!(matches!(
289        crypto.block_encrypt(BlockCipherAlgorithm::Aes128, &[0; 16], &mut [0; 15]),
290        Err(CryptoError::OutputTooSmall { .. })
291    ));
292    assert!(matches!(
293        crypto.new_stream_cipher(StreamCipherAlgorithm::Aes128Ctr, &[0; 15]),
294        Err(CryptoError::InvalidKeyLength { .. })
295    ));
296    let mut stream = crypto
297        .new_stream_cipher(StreamCipherAlgorithm::Aes128Ctr, &[0; 16])
298        .unwrap();
299    assert!(matches!(
300        stream.apply_keystream(&[0; 15], &mut [0; 1]),
301        Err(CryptoError::InvalidNonceLength { .. })
302    ));
303}
304
305/// Checks AES-CBC known-answer vectors and malformed inputs.
306pub fn assert_cbc(crypto: &dyn RTCCrypto) {
307    // NIST SP 800-38A F.2.5.
308    let key = bytes("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
309    let iv = bytes("000102030405060708090a0b0c0d0e0f");
310    let plaintext = bytes("6bc1bee22e409f96e93d7e117393172a");
311    let mut blocks = plaintext.clone();
312    let mut cipher = crypto.new_cbc(CbcAlgorithm::Aes256Cbc, &key).unwrap();
313    assert_eq!(cipher.block_len(), 16);
314    cipher.encrypt_blocks(&iv, &mut blocks).unwrap();
315    assert_eq!(blocks, bytes("f58c4c04d6e5f1ba779eabfb5f7bfbd6"));
316    cipher.decrypt_blocks(&iv, &mut blocks).unwrap();
317    assert_eq!(blocks, plaintext);
318
319    assert!(matches!(
320        crypto.new_cbc(CbcAlgorithm::Aes256Cbc, &[0; 31]),
321        Err(CryptoError::InvalidKeyLength { .. })
322    ));
323    assert!(matches!(
324        cipher.encrypt_blocks(&[0; 15], &mut [0; 16]),
325        Err(CryptoError::InvalidNonceLength { .. })
326    ));
327    assert!(matches!(
328        cipher.encrypt_blocks(&[0; 16], &mut []),
329        Err(CryptoError::OutputTooSmall { .. })
330    ));
331    assert!(matches!(
332        cipher.decrypt_blocks(&[0; 16], &mut [0; 15]),
333        Err(CryptoError::OutputTooSmall { .. })
334    ));
335}
336
337/// Checks AEAD known-answer vectors, round trips, authentication failures, and malformed sizes.
338pub fn assert_aead(crypto: &dyn RTCCrypto) {
339    // NIST SP 800-38D, NIST SP 800-38C, and RFC 8439 known-answer vectors.
340    let mut gcm = crypto.new_aead(AeadAlgorithm::Aes128Gcm, &[0; 16]).unwrap();
341    let mut block = vec![0; 16];
342    let mut tag = vec![0; gcm.tag_len()];
343    gcm.seal_in_place(&[0; 12], &[], &mut block, &mut tag)
344        .unwrap();
345    assert_eq!(block, bytes("0388dace60b6a392f328c2b971b2fe78"));
346    assert_eq!(tag, bytes("ab6e47d42cec13bdf53a67b21257bddf"));
347    gcm.open_in_place(&[0; 12], &[], &mut block, &tag).unwrap();
348    assert_eq!(block, vec![0; 16]);
349
350    let mut gcm = crypto.new_aead(AeadAlgorithm::Aes256Gcm, &[0; 32]).unwrap();
351    let mut block = vec![0; 16];
352    let mut tag = vec![0; gcm.tag_len()];
353    gcm.seal_in_place(&[0; 12], &[], &mut block, &mut tag)
354        .unwrap();
355    assert_eq!(block, bytes("cea7403d4d606b6e074ec5d3baf39d18"));
356    assert_eq!(tag, bytes("d0d1c8a799996bf0265b98b5d48ab919"));
357
358    let mut ccm8 = crypto
359        .new_aead(
360            AeadAlgorithm::Aes128Ccm8,
361            &bytes("404142434445464748494a4b4c4d4e4f"),
362        )
363        .unwrap();
364    let mut ccm8_buffer = bytes("202122232425262728292a2b2c2d2e2f3031323334353637");
365    let mut ccm8_tag = vec![0; ccm8.tag_len()];
366    ccm8.seal_in_place(
367        &bytes("101112131415161718191a1b"),
368        &bytes("000102030405060708090a0b0c0d0e0f10111213"),
369        &mut ccm8_buffer,
370        &mut ccm8_tag,
371    )
372    .unwrap();
373    assert_eq!(
374        ccm8_buffer,
375        bytes("e3b201a9f5b71a7a9b1ceaeccd97e70b6176aad9a4428aa5")
376    );
377    assert_eq!(ccm8_tag, bytes("484392fbc1b09951"));
378
379    let mut chacha = crypto
380        .new_aead(
381            AeadAlgorithm::ChaCha20Poly1305,
382            &bytes("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"),
383        )
384        .unwrap();
385    let mut chacha_buffer = bytes(concat!(
386        "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393",
387        "a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074",
388        "6865206675747572652c2073756e73637265656e20776f756c642062652069742e"
389    ));
390    let mut chacha_tag = vec![0; chacha.tag_len()];
391    chacha
392        .seal_in_place(
393            &bytes("070000004041424344454647"),
394            &bytes("50515253c0c1c2c3c4c5c6c7"),
395            &mut chacha_buffer,
396            &mut chacha_tag,
397        )
398        .unwrap();
399    assert_eq!(
400        chacha_buffer,
401        bytes(concat!(
402            "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128",
403            "2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa",
404            "b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116"
405        ))
406    );
407    assert_eq!(chacha_tag, bytes("1ae10b594f09e26a7e902ecbd0600691"));
408    assert!(matches!(
409        crypto.new_aead(AeadAlgorithm::Aes128Gcm, &[0; 15]),
410        Err(CryptoError::InvalidKeyLength { .. })
411    ));
412    assert!(matches!(
413        gcm.seal_in_place(&[0; 11], &[], &mut [], &mut [0; 16]),
414        Err(CryptoError::InvalidNonceLength { .. })
415    ));
416    assert!(matches!(
417        gcm.seal_in_place(&[0; 12], &[], &mut [], &mut [0; 15]),
418        Err(CryptoError::InvalidTagLength { .. })
419    ));
420
421    let cases = [
422        (AeadAlgorithm::Aes256Gcm, 32),
423        (AeadAlgorithm::Aes128Ccm, 16),
424        (AeadAlgorithm::Aes128Ccm8, 16),
425        (AeadAlgorithm::ChaCha20Poly1305, 32),
426    ];
427    for (algorithm, key_len) in cases {
428        let mut cipher = crypto.new_aead(algorithm, &vec![7; key_len]).unwrap();
429        let plaintext = b"provider conformance".to_vec();
430        let mut encrypted = plaintext.clone();
431        let mut tag = vec![0; cipher.tag_len()];
432        cipher
433            .seal_in_place(&[3; 12], b"aad", &mut encrypted, &mut tag)
434            .unwrap();
435        assert_ne!(encrypted, plaintext);
436        cipher
437            .open_in_place(&[3; 12], b"aad", &mut encrypted, &tag)
438            .unwrap();
439        assert_eq!(encrypted, plaintext);
440
441        let mut ciphertext = plaintext.clone();
442        let mut valid_tag = vec![0; cipher.tag_len()];
443        cipher
444            .seal_in_place(&[3; 12], b"aad", &mut ciphertext, &mut valid_tag)
445            .unwrap();
446
447        let mut tampered = ciphertext.clone();
448        tag[0] ^= 1;
449        assert_eq!(
450            cipher.open_in_place(&[3; 12], b"aad", &mut tampered, &tag),
451            Err(CryptoError::AuthenticationFailed)
452        );
453
454        let mut wrong_aad = ciphertext.clone();
455        assert_eq!(
456            cipher.open_in_place(&[3; 12], b"bad", &mut wrong_aad, &valid_tag),
457            Err(CryptoError::AuthenticationFailed)
458        );
459
460        let mut changed_ciphertext = ciphertext.clone();
461        changed_ciphertext[0] ^= 1;
462        assert_eq!(
463            cipher.open_in_place(&[3; 12], b"aad", &mut changed_ciphertext, &valid_tag),
464            Err(CryptoError::AuthenticationFailed)
465        );
466
467        let mut wrong_key_cipher = crypto.new_aead(algorithm, &vec![8; key_len]).unwrap();
468        assert_eq!(
469            wrong_key_cipher.open_in_place(&[3; 12], b"aad", &mut ciphertext, &valid_tag),
470            Err(CryptoError::AuthenticationFailed)
471        );
472    }
473}
474
475/// Checks every supported one-shot key exchange and malformed peer keys.
476pub fn assert_key_exchange(crypto: &dyn RTCCrypto) {
477    for algorithm in [
478        KeyExchangeAlgorithm::P256,
479        KeyExchangeAlgorithm::P384,
480        KeyExchangeAlgorithm::X25519,
481    ] {
482        let left = crypto.start_key_exchange(algorithm).unwrap();
483        let right = crypto.start_key_exchange(algorithm).unwrap();
484        assert_eq!(left.algorithm(), algorithm);
485        let left_public = left.public_key().to_vec();
486        let right_public = right.public_key().to_vec();
487        let left_secret = left.complete(&right_public).unwrap();
488        let right_secret = right.complete(&left_public).unwrap();
489        assert_eq!(left_secret.as_ref(), right_secret.as_ref());
490        assert!(!left_secret.is_empty());
491
492        let invalid = crypto.start_key_exchange(algorithm).unwrap();
493        assert!(matches!(
494            invalid.complete(&[0; 1]),
495            Err(CryptoError::InvalidPublicKey)
496        ));
497    }
498    assert_x25519_rfc7748(crypto);
499}
500
501/// RFC 8446 section 7.4.2 for X25519: the shared secret is computed as RFC 7748 specifies
502/// (32-byte little-endian u-coordinates, a 32-byte output), and with the check of RFC 7748
503/// section 6.1: a peer key of small order, whose output is all zeros, is refused.
504fn assert_x25519_rfc7748(crypto: &dyn RTCCrypto) {
505    let left = crypto
506        .start_key_exchange(KeyExchangeAlgorithm::X25519)
507        .unwrap();
508    let right = crypto
509        .start_key_exchange(KeyExchangeAlgorithm::X25519)
510        .unwrap();
511    assert_eq!(left.public_key().len(), 32);
512    let right_public = right.public_key().to_vec();
513    assert_eq!(left.complete(&right_public).unwrap().len(), 32);
514
515    // Points of small order (RFC 7748 section 6.1; the list of libsodium and of
516    // "Montgomery curves and their arithmetic"): 0, 1, and a point of order 8.
517    let mut one = [0u8; 32];
518    one[0] = 1;
519    let order_eight: [u8; 32] = [
520        0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4,
521        0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49,
522        0xb8, 0x00,
523    ];
524    for small in [[0u8; 32], one, order_eight] {
525        let exchange = crypto
526            .start_key_exchange(KeyExchangeAlgorithm::X25519)
527            .unwrap();
528        assert!(
529            exchange.complete(&small).is_err(),
530            "a small-order X25519 key gives the all-zero secret and is refused: {small:02x?}"
531        );
532    }
533}
534
535/// Checks the responder's side of a key exchange, and X25519MLKEM768
536/// (draft-ietf-tls-ecdhe-mlkem) where the provider has it: the lengths of its shares and
537/// secret, agreement, and that malformed shares are refused. A provider without it says so.
538pub fn assert_key_exchange_respond(crypto: &dyn RTCCrypto) {
539    for algorithm in [
540        KeyExchangeAlgorithm::P256,
541        KeyExchangeAlgorithm::P384,
542        KeyExchangeAlgorithm::X25519,
543    ] {
544        let initiator = crypto.start_key_exchange(algorithm).unwrap();
545        let (share, responder_secret) = crypto
546            .key_exchange_respond(algorithm, initiator.public_key())
547            .unwrap();
548        let initiator_secret = initiator.complete(&share).unwrap();
549        assert_eq!(initiator_secret.as_ref(), responder_secret.as_ref());
550        assert!(crypto.key_exchange_respond(algorithm, &[0; 1]).is_err());
551    }
552
553    let hybrid = KeyExchangeAlgorithm::X25519MlKem768;
554    if !crypto.supports(CryptoAlgorithm::KeyExchange(hybrid)) {
555        assert!(matches!(
556            crypto.start_key_exchange(hybrid).map(|_| ()),
557            Err(CryptoError::UnsupportedAlgorithm(_))
558        ));
559        assert!(crypto.key_exchange_respond(hybrid, &[0; 1216]).is_err());
560        return;
561    }
562    let initiator = crypto.start_key_exchange(hybrid).unwrap();
563    assert_eq!(initiator.algorithm(), hybrid);
564    // An ML-KEM-768 encapsulation key (1184 bytes) and an X25519 key (32).
565    assert_eq!(initiator.public_key().len(), 1216);
566    let initiator_share = initiator.public_key().to_vec();
567    let (share, responder_secret) = crypto
568        .key_exchange_respond(hybrid, &initiator_share)
569        .unwrap();
570    // An ML-KEM-768 ciphertext (1088 bytes) and an X25519 key (32).
571    assert_eq!(share.len(), 1120);
572    let initiator_secret = initiator.complete(&share).unwrap();
573    // The ML-KEM shared secret (32 bytes) followed by the X25519 one (32).
574    assert_eq!(initiator_secret.len(), 64);
575    assert_eq!(initiator_secret.as_ref(), responder_secret.as_ref());
576    assert_ne!(
577        initiator_secret.as_ref()[..32],
578        initiator_secret.as_ref()[32..]
579    );
580
581    // Encapsulation is randomised: a second answer to the same share is another secret.
582    let (_, other_secret) = crypto
583        .key_exchange_respond(hybrid, &initiator_share)
584        .unwrap();
585    assert_ne!(other_secret.as_ref(), responder_secret.as_ref());
586
587    // Shares of the wrong length, either way.
588    for length in [0, 32, 1120, 1215, 1217] {
589        assert!(matches!(
590            crypto.key_exchange_respond(hybrid, &vec![1; length]),
591            Err(CryptoError::InvalidPublicKey)
592        ));
593    }
594    for length in [0, 32, 1119, 1121, 1216] {
595        let initiator = crypto.start_key_exchange(hybrid).unwrap();
596        assert!(matches!(
597            initiator.complete(&vec![1; length]),
598            Err(CryptoError::InvalidPublicKey)
599        ));
600    }
601    // A ciphertext that was altered decapsulates to another secret (ML-KEM rejects
602    // implicitly), so the two ends do not agree.
603    let initiator = crypto.start_key_exchange(hybrid).unwrap();
604    let (mut share, responder_secret) = crypto
605        .key_exchange_respond(hybrid, initiator.public_key())
606        .unwrap();
607    share[0] ^= 1;
608    let initiator_secret = initiator.complete(&share).unwrap();
609    assert_ne!(initiator_secret.as_ref(), responder_secret.as_ref());
610}
611
612/// Checks signing, verification, key import/export, and invalid signatures and encodings.
613pub fn assert_signatures(crypto: &dyn RTCCrypto) {
614    for scheme in [SignatureScheme::Ed25519, SignatureScheme::EcdsaP256Sha256] {
615        let key = crypto.generate_signing_key(scheme).unwrap();
616        let message = b"rtc-crypto provider conformance";
617        let signature = key.sign(scheme, message).unwrap();
618        crypto
619            .verify_signature(scheme, key.public_key(), message, &signature)
620            .unwrap();
621        assert_eq!(
622            crypto.verify_signature(scheme, key.public_key(), b"changed", &signature),
623            Err(CryptoError::InvalidSignature)
624        );
625
626        let exported = key.to_pkcs8_der().unwrap().unwrap();
627        let imported = crypto
628            .import_signing_key(scheme, exported.as_ref())
629            .unwrap();
630        let imported_signature = imported.sign(scheme, message).unwrap();
631        crypto
632            .verify_signature(scheme, imported.public_key(), message, &imported_signature)
633            .unwrap();
634        assert!(matches!(
635            imported.sign(SignatureScheme::RsaPkcs1Sha256, message),
636            Err(CryptoError::UnsupportedAlgorithm(_))
637        ));
638    }
639
640    assert_eq!(
641        crypto.verify_signature(
642            SignatureScheme::Ed25519,
643            PublicKey {
644                encoding: PublicKeyEncoding::SubjectPublicKeyInfoDer,
645                bytes: &[0; 32],
646            },
647            b"message",
648            &[0; 64],
649        ),
650        Err(CryptoError::InvalidPublicKey)
651    );
652
653    assert_verification_only_schemes(crypto);
654}
655
656fn assert_verification_only_schemes(crypto: &dyn RTCCrypto) {
657    let message = b"rtc-crypto verification vector";
658    let p384_public_key = bytes(concat!(
659        "04c298b589fdd33f544610d13c277e0c703b2e3a72c0dfa2a81725e761614bd8c4",
660        "cb80ecf40bba853f37aec2f4e13c7b5d05e7be9231d651bd1dc2848050bcd19858",
661        "e448d27bf2418b350626a1f241c4914795c404aa35afab97e15e202296244a"
662    ));
663    let p384_signature = bytes(concat!(
664        "306502302c6f36a6a01282982213b037f73ec8f935e1fcf4dc63035824c2bcb6",
665        "aaa378f716d15f63df23e85d60f7d5e46c028ad1023100877055a3a8849e179",
666        "ad94da98dc5125f1e78852cf9017795087b90751b99985b989786d2a537f84b08cdf7243820c313"
667    ));
668    crypto
669        .verify_signature(
670            SignatureScheme::EcdsaP384Sha384,
671            PublicKey {
672                encoding: PublicKeyEncoding::EcUncompressedPoint,
673                bytes: &p384_public_key,
674            },
675            message,
676            &p384_signature,
677        )
678        .unwrap();
679
680    let p384_sha256_public_key = bytes(
681        "041e88f40d0a7fc21dc01d89951ea8598ce35f9f37bc163f102a633079ceeaa99a9298aad6e5c46100f37e915132e5df9f9cedf3e140f789934113e0f8b280e4bd0904b6f1ec10479f759b5d5f01ae1e4058ece51a073fe089680b9eee7e4d1f9e",
682    );
683    let p384_sha256_signature = bytes(
684        "3065023100b3ede985a4270f3fe8a0177040f17b417c12d132f2f27dc3290ba14a9fcbe08b82189d4c2f82dc5f649f1d49bcbc726002306825847e994ecd3f2924e7468e285af7647825692a83fd995c749e536eff946451b3e253d706a9b848d7170761d06323",
685    );
686    crypto
687        .verify_signature(
688            SignatureScheme::EcdsaP384Sha256,
689            PublicKey {
690                encoding: PublicKeyEncoding::EcUncompressedPoint,
691                bytes: &p384_sha256_public_key,
692            },
693            message,
694            &p384_sha256_signature,
695        )
696        .unwrap();
697
698    let rsa_public_key = bytes(
699        "3082010a0282010100b0f8c4868ce9bcd4d11632162c0376bb09dce2facadaa27a6d4ad01b217c0a29e036b1bfd0052254ec3d349383019d8fd2d5c895ac6790bcc6c4dfca7c26bbcf570ee3bdff70826f80e8254776d8e73b431e2bece3d7d515edd23ada88e2c7136ac796685df8a40ed38ce59eaefc2509e1b277a0363938eb8e998a3f9fd6f2ed011b969e48d89d76508904961f8d83756466eff0f1fd5e4621e8ff083fd0d6aa87b31e560c185a1862059ba0fa95f8125ac96bfc7e051c3996587dc1271bb3ebf49303314ee888ccc8441de13a59b0646d9375dfbcbd66c1435398e164bc4672fd63a2eef162a7c1ac7ddb3e9cdb68cfeacff01f036a557477b45172593727f50203010001",
700    );
701    let rsa_vectors = [
702        (
703            SignatureScheme::RsaPkcs1Sha1,
704            "967636ce08cc1923f2b6fa792d2a7cd6521f4a793adb4a0f94cfc6543e483d5383a6b36dbcef3a5cfd5cc12c333ebc6a22f2d452cac61a352111247e26f5e13595f0b78a9e94be1ff7eb4ab60ef48fff3a0e8c1a70ea041f63413c7dc4a5219d2ddb8349058ce1b7d2c02eb98f285d589f858a18f6473a1d3af47de653d520ceba6825e1a1bd5a0065ef0e4d9ac5929bc1cc3ffab014081224db7e7787c67f1580913fb98a870c1355c86a33770d17f654f24dccd781f3bf8a7de29e00198a99dd2bf1a1298630da433982ae63cbf71c265abebdd003c1c2ee870f7f8ea96c465dedb158a1e2e5048763d308a69eefc91424ad0795e8320fa0e753673f657a45",
705        ),
706        (
707            SignatureScheme::RsaPkcs1Sha256,
708            "19b21fd70c4dacec4c3cc6f6aac961e4ea0fb9b5d0ee3862cc35b60849388f2f461ab4697c59c25abb251f88b1de312ced6861ed90152c911356dff768cc4eafdadaa2f8d6b5d70c630d2739f1178fe5cbaff62cee343a20bb38404d35c58d247befa486dd5a3c69affdad5bdecaab876799dd297bd9cc4700e099b92d18d8ad78b64f570e4a398b0b8e9baf9a1b01aaa873b23b7c381917f3383482b7780e0e11e734409fc18daacb0428082789f791af2c4a79d5c75cde45c201e46ae347ab7624e0137940945e174dfab59888892c25b8e10abee1a72f2f31fb3f0e8840db490ba752e1df966979f267756767c88ea0d7909145f379811412f68465e08fd2",
709        ),
710        (
711            SignatureScheme::RsaPkcs1Sha384,
712            "0095d1ef58850cbf09dd1219a8678d7fa3f8c490a4a35feb19f50d85991caf659131dc90c52f14466c429a099a53e1d5f321a49065e85f250b85e08158ee46328515acee03bd215d610ec2335e1cbd1525058b950fb8ecb5d073f9fc474613c830c1111868efc3554c2ec62d9efd4694db281a6b3e48ed68d934278f5ba9a6fb19e8d648baa6b5f48d126def83986166ed05d710d5cdccd457092649b08d5e54c5ccfe42786852c98113b78291e3e2ced51ff3ed51ddef8cb81d311a2983cc6c93f0bb583537c067c6afc63e8e4a9d15635882b14d189a217d9588a469ac1899e3adeafdd276150b1023d7b64fea94b50a9ba22cc47c0d8d6ca4faf6b23f76d0",
713        ),
714        (
715            SignatureScheme::RsaPkcs1Sha512,
716            "7373b3eaf66ba56bda1ae85a466c2f0321d15c37ce293642f6b69fddbea0e6f4dfa76dd0ba274afaabf71ba9d85198c0e75af95af6c64cb9bb304ea1ea3c04e653649891af78145b823d3ed1179fdbdc4edbedcf1eb3201b44a9a40930bf005da1bbe138dfac2d272364a991fcadcfba9093e889fa03f153771fdd51525ffae16cb2155eac8f6da49b602ae8fb34a5a131693459cacbc5adbc9b6002473732a7e205c2150bd25afe850c29845054e17d56a028d81f293b1dc634ba11a6790aa478f0f36bcc64787e356384ae90ef83c5226183afca64c9ac28c83ca803e01ff801f1ee12c806005d9f5d3562afae08e358722ca606d46d500d43901256625fc4",
717        ),
718    ];
719    for (scheme, signature) in rsa_vectors {
720        crypto
721            .verify_signature(
722                scheme,
723                PublicKey {
724                    encoding: PublicKeyEncoding::RsaPkcs1Der,
725                    bytes: &rsa_public_key,
726                },
727                message,
728                &bytes(signature),
729            )
730            .unwrap();
731    }
732}
733
734/// Checks SHA-384, HMAC-SHA-384, HKDF and the TLS 1.3 key schedule against FIPS 180-4,
735/// RFC 4231, RFC 5869 and the RFC 8448 section 3 trace.
736pub fn assert_tls13_key_schedule(crypto: &dyn RTCCrypto) {
737    assert_eq!(
738        crypto.hash(HashAlgorithm::Sha384, b"abc").unwrap(),
739        bytes(
740            "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
741             8086072ba1e7cc2358baeca134c825a7"
742        )
743    );
744    assert_eq!(HashAlgorithm::Sha384.output_len(), 48);
745    assert_eq!(HmacAlgorithm::Sha384.output_len(), 48);
746
747    // RFC 4231 test case 1.
748    let mut tag = [0u8; 48];
749    let mut mac = crypto.new_hmac(HmacAlgorithm::Sha384, &[0x0b; 20]).unwrap();
750    assert_eq!(mac.output_len(), 48);
751    mac.sign(&[b"Hi ", b"There"], &mut tag).unwrap();
752    assert_eq!(
753        tag.as_slice(),
754        bytes(
755            "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59c\
756             faea9ea9076ede7f4af152e8b2fa9cb6"
757        )
758    );
759    mac.verify(&[b"Hi There"], &tag).unwrap();
760
761    // RFC 5869 appendix A.1.
762    let pseudorandom_key = hkdf_extract(
763        crypto,
764        HmacAlgorithm::Sha256,
765        &bytes("000102030405060708090a0b0c"),
766        &[0x0b; 22],
767    )
768    .unwrap();
769    assert_eq!(
770        pseudorandom_key.as_ref(),
771        bytes("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5")
772    );
773    // The info in two pieces: where it is cut must not matter.
774    let output = hkdf_expand(
775        crypto,
776        HmacAlgorithm::Sha256,
777        pseudorandom_key.as_ref(),
778        &[&bytes("f0f1f2f3"), &bytes("f4f5f6f7f8f9")],
779        42,
780    )
781    .unwrap();
782    assert_eq!(
783        output.as_ref(),
784        bytes(
785            "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf\
786             34007208d5b887185865"
787        )
788    );
789    // RFC 5869 appendix A.3: no salt and no info.
790    let pseudorandom_key = hkdf_extract(crypto, HmacAlgorithm::Sha256, &[], &[0x0b; 22]).unwrap();
791    assert_eq!(
792        pseudorandom_key.as_ref(),
793        bytes("19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04")
794    );
795    assert_eq!(
796        hkdf_expand(
797            crypto,
798            HmacAlgorithm::Sha256,
799            pseudorandom_key.as_ref(),
800            &[],
801            42
802        )
803        .unwrap()
804        .as_ref(),
805        bytes(
806            "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d\
807             9d201395faa4b61a96c8"
808        )
809    );
810    assert!(matches!(
811        hkdf_expand(
812            crypto,
813            HmacAlgorithm::Sha256,
814            pseudorandom_key.as_ref(),
815            &[],
816            255 * 32 + 1
817        ),
818        Err(CryptoError::OutputTooSmall { .. })
819    ));
820
821    // RFC 8448 section 3, the simple 1-RTT handshake.
822    let sha256 = HmacAlgorithm::Sha256;
823    let empty_hash = crypto.hash(HashAlgorithm::Sha256, b"").unwrap();
824    let early = hkdf_extract(crypto, sha256, &[], &[0; 32]).unwrap();
825    assert_eq!(
826        early.as_ref(),
827        bytes("33ad0a1c607ec03b09e6cd9893680ce210adf300aa1f2660e1b22e10f170f92a")
828    );
829    let derived = hkdf_expand_label(
830        crypto,
831        sha256,
832        early.as_ref(),
833        "tls13 ",
834        "derived",
835        &empty_hash,
836        32,
837    )
838    .unwrap();
839    assert_eq!(
840        derived.as_ref(),
841        bytes("6f2615a108c702c5678f54fc9dbab69716c076189c48250cebeac3576c3611ba")
842    );
843    let handshake = hkdf_extract(
844        crypto,
845        sha256,
846        derived.as_ref(),
847        &bytes("8bd4054fb55b9d63fdfbacf9f04b9f0d35e6d63f537563efd46272900f89492d"),
848    )
849    .unwrap();
850    assert_eq!(
851        handshake.as_ref(),
852        bytes("1dc826e93606aa6fdc0aadc12f741b01046aa6b99f691ed221a9f0ca043fbeac")
853    );
854    let transcript = bytes("860c06edc07858ee8e78f0e7428c58edd6b43f2ca3e6e95f02ed063cf0e1cad8");
855    let client_handshake = hkdf_expand_label(
856        crypto,
857        sha256,
858        handshake.as_ref(),
859        "tls13 ",
860        "c hs traffic",
861        &transcript,
862        32,
863    )
864    .unwrap();
865    assert_eq!(
866        client_handshake.as_ref(),
867        bytes("b3eddb126e067f35a780b3abf45e2d8f3b1a950738f52e9600746a0e27a55a21")
868    );
869    let server_handshake = hkdf_expand_label(
870        crypto,
871        sha256,
872        handshake.as_ref(),
873        "tls13 ",
874        "s hs traffic",
875        &transcript,
876        32,
877    )
878    .unwrap();
879    assert_eq!(
880        server_handshake.as_ref(),
881        bytes("b67b7d690cc16c4e75e54213cb2d37b4e9c912bcded9105d42befd59d391ad38")
882    );
883    let derived = hkdf_expand_label(
884        crypto,
885        sha256,
886        handshake.as_ref(),
887        "tls13 ",
888        "derived",
889        &empty_hash,
890        32,
891    )
892    .unwrap();
893    assert_eq!(
894        derived.as_ref(),
895        bytes("43de77e0c77713859a944db9db2590b53190a65b3ee2e4f12dd7a0bb7ce254b4")
896    );
897    let master = hkdf_extract(crypto, sha256, derived.as_ref(), &[0; 32]).unwrap();
898    assert_eq!(
899        master.as_ref(),
900        bytes("18df06843d13a08bf2a449844c5f8a478001bc4d4c627984d5a41da8d0402919")
901    );
902    let key = hkdf_expand_label(
903        crypto,
904        sha256,
905        server_handshake.as_ref(),
906        "tls13 ",
907        "key",
908        &[],
909        16,
910    )
911    .unwrap();
912    assert_eq!(key.as_ref(), bytes("3fce516009c21727d0f2e4e86ee403bc"));
913    let iv = hkdf_expand_label(
914        crypto,
915        sha256,
916        server_handshake.as_ref(),
917        "tls13 ",
918        "iv",
919        &[],
920        12,
921    )
922    .unwrap();
923    assert_eq!(iv.as_ref(), bytes("5d313eb2671276ee13000b30"));
924
925    // The DTLS 1.3 prefix (RFC 9147 section 5.9) gives different keys from the same secret.
926    let dtls_key = hkdf_expand_label(
927        crypto,
928        sha256,
929        server_handshake.as_ref(),
930        "dtls13",
931        "key",
932        &[],
933        16,
934    )
935    .unwrap();
936    assert_ne!(dtls_key.as_ref(), key.as_ref());
937    assert!(
938        hkdf_expand_label(
939            crypto,
940            sha256,
941            early.as_ref(),
942            "dtls13",
943            "key",
944            &[0; 256],
945            16
946        )
947        .is_err()
948    );
949}
950
951/// Checks the record-number masks against the header-protection samples of RFC 9001
952/// appendix A, which are the computation RFC 9147 section 4.2.3 defines.
953pub fn assert_header_masks(crypto: &dyn RTCCrypto) {
954    // RFC 9001 A.2: AES-128.
955    let mut mask = crypto
956        .new_header_mask(
957            HeaderMaskAlgorithm::Aes128,
958            &bytes("9f50449e04a0e810283a1e9933adedd2"),
959        )
960        .unwrap();
961    let sample: [u8; 16] = bytes("d1b1c98dd7689fb8ec11d242b123dc9b")
962        .try_into()
963        .unwrap();
964    assert_eq!(mask.mask(&sample).unwrap().as_slice(), bytes("437b9aec36"));
965    // A keyed mask is reusable.
966    assert_eq!(mask.mask(&sample).unwrap().as_slice(), bytes("437b9aec36"));
967
968    // RFC 9001 A.5: ChaCha20, the sample's first four bytes the block counter and the rest
969    // the nonce.
970    let mut mask = crypto
971        .new_header_mask(
972            HeaderMaskAlgorithm::ChaCha20,
973            &bytes("25a282b9e82f06f21f488917a4fc8f1b73573685608597d0efcb076b0ab7a7a4"),
974        )
975        .unwrap();
976    let sample: [u8; 16] = bytes("5e5cd55c41f69080575d7999c25a5bfb")
977        .try_into()
978        .unwrap();
979    assert_eq!(mask.mask(&sample).unwrap().as_slice(), bytes("aefefe7d03"));
980
981    // AES-256 is AES-ECB of the sample under a 256-bit key: the block cipher's own answer.
982    let key = [0x42u8; 32];
983    let mut block = sample;
984    crypto
985        .block_encrypt(BlockCipherAlgorithm::Aes256, &key, &mut block)
986        .unwrap();
987    let mut mask = crypto
988        .new_header_mask(HeaderMaskAlgorithm::Aes256, &key)
989        .unwrap();
990    assert_eq!(mask.mask(&sample).unwrap().as_slice(), &block[..5]);
991
992    assert!(matches!(
993        crypto.new_header_mask(HeaderMaskAlgorithm::Aes128, &[0; 32]),
994        Err(CryptoError::InvalidKeyLength { .. })
995    ));
996}
997
998/// Checks RSASSA-PSS verification (the TLS 1.3 `rsa_pss_rsae` schemes: MGF1 with the same
999/// hash, a salt as long as the digest) against signatures made with OpenSSL.
1000pub fn assert_rsa_pss(crypto: &dyn RTCCrypto) {
1001    let message = b"rtc-crypto RSASSA-PSS verification vector";
1002    let rsa_public_key = bytes(
1003        "3082010a0282010100b0f8c4868ce9bcd4d11632162c0376bb09dce2facadaa27a6d4ad01b217c0a29\
1004         e036b1bfd0052254ec3d349383019d8fd2d5c895ac6790bcc6c4dfca7c26bbcf570ee3bdff70826f80\
1005         e8254776d8e73b431e2bece3d7d515edd23ada88e2c7136ac796685df8a40ed38ce59eaefc2509e1b2\
1006         77a0363938eb8e998a3f9fd6f2ed011b969e48d89d76508904961f8d83756466eff0f1fd5e4621e8ff\
1007         083fd0d6aa87b31e560c185a1862059ba0fa95f8125ac96bfc7e051c3996587dc1271bb3ebf4930331\
1008         4ee888ccc8441de13a59b0646d9375dfbcbd66c1435398e164bc4672fd63a2eef162a7c1ac7ddb3e9c\
1009         db68cfeacff01f036a557477b45172593727f50203010001",
1010    );
1011    let vectors = [
1012        (
1013            SignatureScheme::RsaPssSha256,
1014            "a793bca49825413a688eaac91393ae1f80c08853f95bc2754deda4e816d3d4c2fb26090c3cabcad1\
1015             e2af65c7948263e5c2bbf1442cc6c42c95c61dce9b10ceb7114f6bc7390e29cea19d0f439d5dcb27\
1016             56a4669d09da0a27463a65e1ccb25a6c3d320cc337641530352a71ea6db92b9fcabe97e658a645da\
1017             f6f21aeff8581cba9e5c7e66579ab15c6c277585228b20bc531ec9551af3cc11d64d0e836b69d452\
1018             7822fc56b8add10cf786b450a94eeef397276f5731ddec78f5ffa5a1d40f6552060520603e48e310\
1019             38fa9c96952de4dade0723ef7a4947f8cc8916fded1da2215988616433fbb0d2f084173590c23dd9\
1020             a36fa5283c98a4227226b03fb0b211bd",
1021        ),
1022        (
1023            SignatureScheme::RsaPssSha384,
1024            "15d74fcf1000dbfaaf843ad0ab3353d4c6c704e12434bd2e323efa9e59dfd913f70ecb5cf487b1e8\
1025             e1b1980e3d49a01f7f35bacff46c3c361ea22ecf641d1bfee69f63b7bd97d1c7a317a53d9e5eb3ec\
1026             2ed9ef29bb6004457262f34de89c15db3bbe3f1b3da0dfda8c63f4813cf790a0ed92b942440cf05f\
1027             fccff518f3af096cda08c417c98351fe7f15cfbf96d73468ac88e390e3e950846d0e70ac665678b2\
1028             021668e4a3996c498e1f1784c98a9ede2f4b3cbff7fb1fed61266946180248106841acdc3349de98\
1029             4f956df683773f622efbf79c1863559ba40538c7f3a6e36af5d302e8a0275dc37c0acb34587db107\
1030             b4db640fb2a78371e768b16fa790ad1c",
1031        ),
1032        (
1033            SignatureScheme::RsaPssSha512,
1034            "a47446283b0cac22decb44c283fb93d90b50f6a79fe04d83f2484332861d5c9bee21e2b0b16e0d8e\
1035             7630777b06f821cd4504dc2fcc93c4f39b728d7cb0e81470fbd15b5edf3da1f7194e73ff34d08440\
1036             240aeda34b7003d393354e00878e61ae9e6d3473e7d3932b8e05d7dc62932af9d65d8be84600654d\
1037             5be161daac8403e3c2b11a092494e3b9a7ce6a45092b239332443c0baa3e93b01ebb77d0e36f77eb\
1038             951c9ee95ba859997f5bf7865d0fb5ed7af5e447d8c935721eea0b3941dadbc119a6c2b1d2db198e\
1039             11735206b2263c8ce87d22065938b7fdc0e73c7857571a5fd8b289f5133c388427b6042b26f62ba9\
1040             8f70ffb70294b193e079494c1f5674cc",
1041        ),
1042    ];
1043    for (scheme, signature) in vectors {
1044        let public_key = PublicKey {
1045            encoding: PublicKeyEncoding::RsaPkcs1Der,
1046            bytes: &rsa_public_key,
1047        };
1048        let signature = bytes(signature);
1049        crypto
1050            .verify_signature(scheme, public_key, message, &signature)
1051            .unwrap();
1052        assert_eq!(
1053            crypto.verify_signature(scheme, public_key, b"another message", &signature),
1054            Err(CryptoError::InvalidSignature)
1055        );
1056        // A PSS signature is not a PKCS#1 v1.5 one, and the hash is part of the scheme.
1057        assert_eq!(
1058            crypto.verify_signature(
1059                SignatureScheme::RsaPkcs1Sha256,
1060                public_key,
1061                message,
1062                &signature
1063            ),
1064            Err(CryptoError::InvalidSignature)
1065        );
1066        let other = if scheme == SignatureScheme::RsaPssSha256 {
1067            SignatureScheme::RsaPssSha384
1068        } else {
1069            SignatureScheme::RsaPssSha256
1070        };
1071        assert_eq!(
1072            crypto.verify_signature(other, public_key, message, &signature),
1073            Err(CryptoError::InvalidSignature)
1074        );
1075    }
1076}
1077
1078/// Checks that a provider's secure random source returns fresh output.
1079pub fn assert_random(provider: &dyn RTCCryptoProvider) {
1080    let mut first = [0; 32];
1081    let mut second = [0; 32];
1082    provider.random().fill(&mut first).unwrap();
1083    provider.random().fill(&mut second).unwrap();
1084    assert_ne!(first, second);
1085}
1086
1087/// Checks the default unsupported-operation behavior required for partial providers.
1088pub fn assert_unsupported_hash(crypto: &dyn RTCCrypto) {
1089    assert!(!crypto.supports(CryptoAlgorithm::Hash(HashAlgorithm::Sha256)));
1090    assert_eq!(
1091        crypto.hash(HashAlgorithm::Sha256, b"input"),
1092        Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Hash(
1093            HashAlgorithm::Sha256
1094        )))
1095    );
1096}
1097
1098/// Checks the provider-neutral failure returned by a deliberately failing random source.
1099pub fn assert_random_failure(random: &dyn crate::RTCRandom) {
1100    assert_eq!(random.fill(&mut [0; 1]), Err(CryptoError::RandomnessFailed));
1101}
1102
1103fn bytes(hex: &str) -> Vec<u8> {
1104    assert!(hex.len().is_multiple_of(2));
1105    let (pairs, _) = hex.as_bytes().as_chunks::<2>();
1106    pairs
1107        .iter()
1108        .map(|&[hi, lo]| (nibble(hi) << 4) | nibble(lo))
1109        .collect()
1110}
1111
1112fn nibble(byte: u8) -> u8 {
1113    match byte {
1114        b'0'..=b'9' => byte - b'0',
1115        b'a'..=b'f' => byte - b'a' + 10,
1116        _ => panic!("invalid hexadecimal test vector"),
1117    }
1118}