Skip to main content

rs_matter_crypto/
lib.rs

1/*
2 *
3 *    Copyright (c) 2022-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18//! Cryptographic abstractions and backends, the canonical representations of
19//! cryptographic material, and the group key derivation.
20
21#![cfg_attr(not(feature = "std"), no_std)]
22#![allow(async_fn_in_trait)]
23#![allow(unknown_lints)]
24#![allow(clippy::uninlined_format_args)]
25// `cargo llvm-cov` sets `coverage_nightly` when it runs on a nightly toolchain;
26// the test modules are then excluded from the coverage report
27#![cfg_attr(all(coverage_nightly, test), feature(coverage_attribute))]
28
29use crate::error::Error;
30
31// The dependencies, under the names the code uses for them
32use rs_matter_tlv as tlv;
33use rs_matter_utils as utils;
34use rs_matter_utils::error;
35
36#[cfg(feature = "alloc")]
37extern crate alloc;
38
39// This mod MUST go first, so that the others see its macros.
40pub(crate) mod fmt;
41use crate::utils::sync::{MaybeSend, MaybeSendSync};
42
43pub use rand_core::{CryptoRng, Rng, TryCryptoRng, TryRng};
44
45pub use canon::*;
46pub use csr::CSR_MAX_LEN;
47pub use rand::*;
48
49pub mod backend;
50mod canon;
51mod csr;
52pub mod group_keys;
53mod rand;
54
55/// Trait representing a cryptographic backend.
56///
57/// The backend should provide all the cryptographic primitives required by the Matter spec.
58///
59/// The trait is designed in a way where it allows customizing a concrete implementation by
60/// swapping out its out of the box algorithms with custom (potentially HW-accelerated) ones,
61/// by decorating the original implementation and replacing only the required types and methods.
62pub trait Crypto: MaybeSendSync {
63    type Rand<'a>: CryptoRng + Copy + MaybeSend
64    where
65        Self: 'a;
66
67    type WeakRand<'a>: Rng + Copy + MaybeSend
68    where
69        Self: 'a;
70
71    /// Hasher type returned by `Crypto::hash`.
72    ///
73    /// As per the Matter spec, the hasher should be SHA-256.
74    type Hash<'a>: Digest<HASH_LEN> + MaybeSend
75    where
76        Self: 'a;
77
78    /// SHA-1 hasher type returned by `Crypto::hash1`.
79    type Hash1<'a>: Digest<SHA1_HASH_LEN> + MaybeSend
80    where
81        Self: 'a;
82
83    /// HMAC hasher type returned by `Crypto::hmac`.
84    ///
85    /// As per the Matter spec, the HMAC hasher should be HMAC-SHA-256.
86    type Hmac<'a>: Digest<HASH_LEN> + MaybeSend
87    where
88        Self: 'a;
89
90    /// KDF type returned by `Crypto::kdf`.
91    ///
92    /// As per the Matter spec, the KDF should be HKDF-SHA256.
93    type Kdf<'a>: Kdf + MaybeSend
94    where
95        Self: 'a;
96
97    /// PBKDF type returned by `Crypto::pbkdf`.
98    ///
99    /// As per the Matter spec, the PBKDF should be PBKDF2-HMAC-SHA256.
100    type PbKdf<'a>: PbKdf + MaybeSend
101    where
102        Self: 'a;
103
104    /// AEAD type returned by `Crypto::aead`.
105    ///
106    /// As per the Matter spec, the AEAD algorithm used is AES-CCM with 128-bit keys, 13-byte nonces
107    /// and 16-byte tags.
108    type Aead<'a>: Aead<AEAD_CANON_KEY_LEN, AEAD_NONCE_LEN> + MaybeSend
109    where
110        Self: 'a;
111
112    /// Public key type returned by `Crypto::pub_key`.
113    ///
114    /// As per the Matter spec, the used Public Key Cryptograqphy should be
115    /// Elliptic-Curve based, and specifically secp256r1 (NIST P-256).
116    ///
117    /// In other words, the public key is a point on the secp256r1 curve.
118    ///
119    /// With that said, the implementation is free to choose a different internal
120    /// representation of the public key type as compared to the `EcPoint` type.
121    /// The only requirement is that both should be possible to convert from/to
122    /// the same canonical representation.
123    type PublicKey<'a>: PublicKey<'a, PKC_CANON_PUBLIC_KEY_LEN, PKC_SIGNATURE_LEN> + MaybeSend
124    where
125        Self: 'a;
126
127    /// Signing secret key type returned by `Crypto::singleton_singing_secret_key`.
128    ///
129    /// As per the Matter spec, the used Public Key Cryptograqphy should be
130    /// Elliptic-Curve based, and specifically secp256r1 (NIST P-256).
131    ///
132    /// In other words, the signing secret key is a scalar on the secp256r1 curve.
133    ///
134    /// With that said, the implementation is free to choose a different internal
135    /// representation of the signing secret key type as compared to the `EcScalar` type.
136    /// The only requirement is that both should be possible to convert from/to
137    /// the same canonical representation.
138    type SigningSecretKey<'a>: SigningSecretKey<
139            'a,
140            PKC_CANON_PUBLIC_KEY_LEN,
141            PKC_SIGNATURE_LEN,
142            PublicKey<'a> = Self::PublicKey<'a>,
143        > + MaybeSend
144    where
145        Self: 'a;
146
147    /// Secret key type returned by `Crypto::secret_key` and `Crypto::generate_secret_key`.
148    ///
149    /// As per the Matter spec, the used Public Key Cryptograqphy should be
150    /// Elliptic-Curve based, and specifically secp256r1 (NIST P-256).
151    ///
152    /// In other words, the secret key is a scalar on the secp256r1 curve.
153    ///
154    /// With that said, the implementation is free to choose a different internal
155    /// representation of the secret key type as compared to the `EcScalar` type.
156    /// The only requirement is that both should be possible to convert from/to
157    /// the same canonical representation.
158    type SecretKey<'a>: SecretKey<
159            'a,
160            PKC_CANON_SECRET_KEY_LEN,
161            PKC_CANON_PUBLIC_KEY_LEN,
162            PKC_SIGNATURE_LEN,
163            PKC_SHARED_SECRET_LEN,
164            PublicKey<'a> = Self::PublicKey<'a>,
165        > + MaybeSend
166    where
167        Self: 'a;
168
169    /// EC scalar type returned by `Crypto::ec_scalar` and `Crypto::generate_ec_scalar`.
170    ///
171    /// As per the Matter spec, the curve used is secp256r1 (NIST P-256).
172    ///
173    /// In other words, the EC scalar is a scalar on the secp256r1 curve.
174    type EcScalar<'a>: EcScalar<'a, EC_CANON_SCALAR_LEN> + MaybeSend
175    where
176        Self: 'a;
177
178    /// EC point type returned by `Crypto::ec_point` and `Crypto::ec_generator_point`.
179    ///
180    /// As per the Matter spec, the curve used is secp256r1 (NIST P-256).
181    ///
182    /// In other words, the EC point is a point on the secp256r1 curve.
183    type EcPoint<'a>: EcPoint<'a, EC_CANON_POINT_LEN, EC_CANON_SCALAR_LEN, Scalar<'a> = Self::EcScalar<'a>>
184        + MaybeSend
185    where
186        Self: 'a;
187
188    /// Create a new, cryptographically secure, random number generator instance.
189    fn rand(&self) -> Result<Self::Rand<'_>, Error>;
190
191    /// Create a new NON-cryptographically secure (but potentially faster), random number generator instance.
192    fn weak_rand(&self) -> Result<Self::WeakRand<'_>, Error>;
193
194    /// Create a new hasher instance.
195    fn hash(&self) -> Result<Self::Hash<'_>, Error>;
196
197    /// Create a new SHA-1 hasher instance.
198    fn hash1(&self) -> Result<Self::Hash1<'_>, Error>;
199
200    /// Create a new HMAC hasher instance with the given key.
201    fn hmac<const KEY_LEN: usize>(
202        &self,
203        key: CryptoSensitiveRef<'_, KEY_LEN>,
204    ) -> Result<Self::Hmac<'_>, Error>;
205
206    /// Create a new KDF instance.
207    fn kdf(&self) -> Result<Self::Kdf<'_>, Error>;
208
209    /// Create a new PBKDF instance.
210    fn pbkdf(&self) -> Result<Self::PbKdf<'_>, Error>;
211
212    /// Create a new AEAD instance.
213    fn aead(&self) -> Result<Self::Aead<'_>, Error>;
214
215    /// Create a public key instance from its canonical representation.
216    fn pub_key(&self, key: CanonPkcPublicKeyRef<'_>) -> Result<Self::PublicKey<'_>, Error>;
217
218    /// Create a secret key instance from its canonical representation.
219    fn secret_key(&self, key: CanonPkcSecretKeyRef<'_>) -> Result<Self::SecretKey<'_>, Error>;
220
221    /// Generate a new secret key instance.
222    fn generate_secret_key(&self) -> Result<Self::SecretKey<'_>, Error>;
223
224    /// Get the singleton signing secret key instance.
225    ///
226    /// This is used for device attestation.
227    fn singleton_singing_secret_key(&self) -> Result<Self::SigningSecretKey<'_>, Error>;
228
229    /// Create an EC scalar instance from its canonical representation.
230    fn ec_scalar(&self, scalar: CanonEcScalarRef<'_>) -> Result<Self::EcScalar<'_>, Error>;
231
232    /// Create an EC scalar instance from a 320-bit unsigned integer modulo the EC prime modulus.
233    fn ec_scalar_mod_p(&self, uint: CanonUint320Ref<'_>) -> Result<Self::EcScalar<'_>, Error>;
234
235    /// Generate a new random EC scalar instance.
236    fn generate_ec_scalar(&self) -> Result<Self::EcScalar<'_>, Error>;
237
238    /// Create an EC point instance from its canonical representation.
239    fn ec_point(&self, point: CanonEcPointRef<'_>) -> Result<Self::EcPoint<'_>, Error>;
240
241    /// Get the EC Generator point.
242    fn ec_generator_point(&self) -> Result<Self::EcPoint<'_>, Error>;
243}
244
245impl<T> Crypto for &T
246where
247    T: Crypto,
248{
249    type Rand<'a>
250        = T::Rand<'a>
251    where
252        Self: 'a;
253
254    type WeakRand<'a>
255        = T::WeakRand<'a>
256    where
257        Self: 'a;
258
259    type Hash<'a>
260        = T::Hash<'a>
261    where
262        Self: 'a;
263
264    type Hash1<'a>
265        = T::Hash1<'a>
266    where
267        Self: 'a;
268
269    type Hmac<'a>
270        = T::Hmac<'a>
271    where
272        Self: 'a;
273
274    type Kdf<'a>
275        = T::Kdf<'a>
276    where
277        Self: 'a;
278
279    type PbKdf<'a>
280        = T::PbKdf<'a>
281    where
282        Self: 'a;
283
284    type Aead<'a>
285        = T::Aead<'a>
286    where
287        Self: 'a;
288
289    type PublicKey<'a>
290        = T::PublicKey<'a>
291    where
292        Self: 'a;
293
294    type SecretKey<'a>
295        = T::SecretKey<'a>
296    where
297        Self: 'a;
298
299    type SigningSecretKey<'a>
300        = T::SigningSecretKey<'a>
301    where
302        Self: 'a;
303
304    type EcScalar<'a>
305        = T::EcScalar<'a>
306    where
307        Self: 'a;
308
309    type EcPoint<'a>
310        = T::EcPoint<'a>
311    where
312        Self: 'a;
313
314    fn rand(&self) -> Result<Self::Rand<'_>, Error> {
315        (*self).rand()
316    }
317
318    fn weak_rand(&self) -> Result<Self::WeakRand<'_>, Error> {
319        (*self).weak_rand()
320    }
321
322    fn hash(&self) -> Result<Self::Hash<'_>, Error> {
323        (*self).hash()
324    }
325
326    fn hash1(&self) -> Result<Self::Hash1<'_>, Error> {
327        (*self).hash1()
328    }
329
330    fn hmac<const KEY_LEN: usize>(
331        &self,
332        key: CryptoSensitiveRef<'_, KEY_LEN>,
333    ) -> Result<Self::Hmac<'_>, Error> {
334        (*self).hmac(key)
335    }
336
337    fn kdf(&self) -> Result<Self::Kdf<'_>, Error> {
338        (*self).kdf()
339    }
340
341    fn pbkdf(&self) -> Result<Self::PbKdf<'_>, Error> {
342        (*self).pbkdf()
343    }
344
345    fn aead(&self) -> Result<Self::Aead<'_>, Error> {
346        (*self).aead()
347    }
348
349    fn pub_key(&self, key: CanonPkcPublicKeyRef<'_>) -> Result<Self::PublicKey<'_>, Error> {
350        (*self).pub_key(key)
351    }
352
353    fn generate_secret_key(&self) -> Result<Self::SecretKey<'_>, Error> {
354        (*self).generate_secret_key()
355    }
356
357    fn secret_key(&self, key: CanonPkcSecretKeyRef<'_>) -> Result<Self::SecretKey<'_>, Error> {
358        (*self).secret_key(key)
359    }
360
361    fn singleton_singing_secret_key(&self) -> Result<Self::SigningSecretKey<'_>, Error> {
362        (*self).singleton_singing_secret_key()
363    }
364
365    fn ec_scalar(&self, scalar: CanonEcScalarRef<'_>) -> Result<Self::EcScalar<'_>, Error> {
366        (*self).ec_scalar(scalar)
367    }
368
369    fn ec_scalar_mod_p(&self, uint: CanonUint320Ref<'_>) -> Result<Self::EcScalar<'_>, Error> {
370        (*self).ec_scalar_mod_p(uint)
371    }
372
373    fn generate_ec_scalar(&self) -> Result<Self::EcScalar<'_>, Error> {
374        (*self).generate_ec_scalar()
375    }
376
377    fn ec_point(&self, point: CanonEcPointRef<'_>) -> Result<Self::EcPoint<'_>, Error> {
378        (*self).ec_point(point)
379    }
380
381    fn ec_generator_point(&self) -> Result<Self::EcPoint<'_>, Error> {
382        (*self).ec_generator_point()
383    }
384}
385
386/// Trait representing a generic digest (hash) algorithm.
387///
388/// The digest algorithm should support incremental updates and finalization.
389///
390/// Used for both hashing and HMAC.
391pub trait Digest<const HASH_LEN: usize> {
392    /// Update the digest with the given data.
393    fn update(&mut self, data: &[u8]) -> Result<(), Error>;
394
395    /// Finish the digest and write the result into the given buffer,
396    /// without consuming the hasher instance, allowing for further updates and finalizations.
397    fn finish_current(&mut self, hash: &mut CryptoSensitive<HASH_LEN>) -> Result<(), Error>;
398
399    /// Finish the digest and write the result into the given buffer.
400    fn finish(self, hash: &mut CryptoSensitive<HASH_LEN>) -> Result<(), Error>;
401}
402
403/// Trait representing a Key Derivation Function (KDF).
404pub trait Kdf {
405    /// Expand the given input keying material (IKM) with the given salt and info
406    /// to produce the output keying material (OKM) written into `key`.
407    fn expand<const IKM_LEN: usize, const KEY_LEN: usize>(
408        self,
409        salt: &[u8],
410        ikm: CryptoSensitiveRef<'_, IKM_LEN>,
411        info: &[u8],
412        key: &mut CryptoSensitive<KEY_LEN>,
413    ) -> Result<(), Error>;
414}
415
416/// Trait representing a Password-Based Key Derivation Function (PBKDF).
417pub trait PbKdf {
418    /// Derive a key from the given password, salt and iteration count,
419    /// writing the result into `key`.
420    fn derive<const PASS_LEN: usize, const KEY_LEN: usize>(
421        self,
422        pass: CryptoSensitiveRef<'_, PASS_LEN>,
423        iter: usize,
424        salt: &[u8],
425        key: &mut CryptoSensitive<KEY_LEN>,
426    ) -> Result<(), Error>;
427}
428
429/// Trait representing an Authenticated Encryption with Associated Data (AEAD) algorithm.
430pub trait Aead<const KEY_LEN: usize, const NONCE_LEN: usize> {
431    /// Encrypt the given data in place, using the given key, nonce and additional authenticated data (AAD).
432    ///
433    /// # Arguments
434    /// - `key`: The AEAD key.
435    /// - `nonce`: The AEAD nonce.
436    /// - `aad`: The additional authenticated data.
437    /// - `data`: The data to encrypt, which will be modified in place to contain the ciphertext and tag.
438    /// - `data_len`: The length of the plaintext data in `data`.
439    ///
440    /// # Returns
441    /// - On success, returns a slice containing the ciphertext and tag.
442    /// - On failure, returns an `Error`.
443    fn encrypt_in_place<'a>(
444        &mut self,
445        key: CryptoSensitiveRef<'_, KEY_LEN>,
446        nonce: CryptoSensitiveRef<'_, NONCE_LEN>,
447        aad: &[u8],
448        data: &'a mut [u8],
449        data_len: usize,
450    ) -> Result<&'a [u8], Error>;
451
452    /// Decrypt the given data in place, using the given key, nonce and additional authenticated data (AAD).
453    ///
454    /// # Arguments
455    /// - `key`: The AEAD key.
456    /// - `nonce`: The AEAD nonce.
457    /// - `aad`: The additional authenticated data.
458    /// - `data`: The data to decrypt, which will be modified in place to contain the plaintext.
459    ///
460    /// # Returns
461    /// - On success, returns a slice containing the plaintext.
462    /// - On failure, returns an `Error`.
463    fn decrypt_in_place<'a>(
464        &mut self,
465        key: CryptoSensitiveRef<'_, KEY_LEN>,
466        nonce: CryptoSensitiveRef<'_, NONCE_LEN>,
467        aad: &[u8],
468        data: &'a mut [u8],
469    ) -> Result<&'a [u8], Error>;
470}
471
472impl<const KEY_LEN: usize, const NONCE_LEN: usize, T> Aead<KEY_LEN, NONCE_LEN> for &mut T
473where
474    T: Aead<KEY_LEN, NONCE_LEN>,
475{
476    fn encrypt_in_place<'a>(
477        &mut self,
478        key: CryptoSensitiveRef<'_, KEY_LEN>,
479        nonce: CryptoSensitiveRef<'_, NONCE_LEN>,
480        aad: &[u8],
481        data: &'a mut [u8],
482        data_len: usize,
483    ) -> Result<&'a [u8], Error> {
484        (*self).encrypt_in_place(key, nonce, aad, data, data_len)
485    }
486
487    fn decrypt_in_place<'a>(
488        &mut self,
489        key: CryptoSensitiveRef<'_, KEY_LEN>,
490        nonce: CryptoSensitiveRef<'_, NONCE_LEN>,
491        aad: &[u8],
492        data: &'a mut [u8],
493    ) -> Result<&'a [u8], Error> {
494        (*self).decrypt_in_place(key, nonce, aad, data)
495    }
496}
497
498/// Trait representing a signing secret key.
499///
500/// A signing secret key is a weaker variant of a secret key. Namely:
501/// - It can only be used for signing operations.
502/// - It cannot be used for deriving shared secrets.
503/// - It cannot be written to its canonical representation (exported).
504///
505/// Suitable in use-cases requiring static yet strongly protected secret key (i.e. device attestation),
506/// where the secret key of the device might be offloaded to a special storage and crypto-engine
507/// and thus might not be directly accessible.
508pub trait SigningSecretKey<'a, const PUB_KEY_LEN: usize, const SIGNATURE_LEN: usize> {
509    /// Public key type associated with this secret key.
510    type PublicKey<'s>: PublicKey<'s, PUB_KEY_LEN, SIGNATURE_LEN>
511    where
512        Self: 's;
513
514    /// Get the public key corresponding to this secret key.
515    fn pub_key(&self) -> Result<Self::PublicKey<'a>, Error>;
516
517    /// Generate a Certificate Signing Request (CSR) using this secret key.
518    ///
519    /// # Arguments
520    /// - `buf`: Buffer to write the CSR into. Must be at least `CSR_MAX_LEN` bytes long.
521    ///
522    /// # Returns
523    /// - On success, returns a slice containing the CSR, in DER format.
524    /// - On failure, returns an `Error`.
525    ///
526    /// The default writes the CSR from a template, with `pub_key` and `sign`.
527    fn csr<'s>(&self, buf: &'s mut [u8]) -> Result<&'s [u8], Error>
528    where
529        Self: 'a,
530    {
531        csr::write(self, buf)
532    }
533
534    /// Sign the given data using this secret key,
535    ///
536    /// # Arguments
537    /// - `data`: Data to sign.
538    /// - `signature`: Buffer to write the signature into.
539    fn sign(
540        &self,
541        data: &[u8],
542        signature: &mut CryptoSensitive<SIGNATURE_LEN>,
543    ) -> Result<(), Error>;
544}
545
546/// Trait representing a secret key.
547///
548/// A secret key can be used for signing operations, deriving shared secrets,
549/// and can be written to its canonical representation (exported).
550pub trait SecretKey<
551    'a,
552    const KEY_LEN: usize,
553    const PUB_KEY_LEN: usize,
554    const SIGNATURE_LEN: usize,
555    const SHARED_SECRET_LEN: usize,
556>: SigningSecretKey<'a, PUB_KEY_LEN, SIGNATURE_LEN>
557{
558    /// Derive a shared secret with the given peer public key,
559    ///
560    /// # Arguments
561    /// - `peer_pub_key`: Peer public key to derive the shared secret with.
562    /// - `shared_secret`: Buffer to write the shared secret into.
563    fn derive_shared_secret(
564        &self,
565        peer_pub_key: &Self::PublicKey<'a>,
566        shared_secret: &mut CryptoSensitive<SHARED_SECRET_LEN>,
567    ) -> Result<(), Error>;
568
569    /// Write the canonical representation of this secret key into the given buffer.
570    fn write_canon(&self, key: &mut CryptoSensitive<KEY_LEN>) -> Result<(), Error>;
571}
572
573/// Trait representing a public key.
574pub trait PublicKey<'a, const KEY_LEN: usize, const SIGNATURE_LEN: usize> {
575    /// Verify the given signature over the given data using this public key.
576    ///
577    /// # Arguments
578    /// - `data`: Data to verify the signature over.
579    /// - `signature`: Signature to verify.
580    ///
581    /// # Returns
582    /// - `true` if the signature is valid.
583    fn verify(
584        &self,
585        data: &[u8],
586        signature: CryptoSensitiveRef<SIGNATURE_LEN>,
587    ) -> Result<bool, Error>;
588
589    /// Write the canonical representation of this public key into the given buffer.
590    fn write_canon(&self, key: &mut CryptoSensitive<KEY_LEN>) -> Result<(), Error>;
591}
592
593impl<'a, const KEY_LEN: usize, const SIGNATURE_LEN: usize, T> PublicKey<'a, KEY_LEN, SIGNATURE_LEN>
594    for &T
595where
596    T: PublicKey<'a, KEY_LEN, SIGNATURE_LEN>,
597{
598    fn verify(
599        &self,
600        data: &[u8],
601        signature: CryptoSensitiveRef<SIGNATURE_LEN>,
602    ) -> Result<bool, Error> {
603        (*self).verify(data, signature)
604    }
605
606    fn write_canon(&self, key: &mut CryptoSensitive<KEY_LEN>) -> Result<(), Error> {
607        (*self).write_canon(key)
608    }
609}
610
611/// Trait representing an Elliptic Curve (EC) scalar value.
612pub trait EcScalar<'a, const LEN: usize> {
613    /// Multiply this scalar by another scalar.
614    ///
615    /// # Arguments
616    /// - `other`: The other scalar to multiply with.
617    ///
618    /// # Returns
619    /// - The result of the multiplication.
620    fn mul(&self, other: &Self) -> Result<Self, Error>
621    where
622        Self: Sized;
623
624    /// Write the canonical representation of this scalar into the given buffer.
625    fn write_canon(&self, scalar: &mut CryptoSensitive<LEN>) -> Result<(), Error>;
626}
627
628/// Trait representing an Elliptic Curve (EC) point.
629pub trait EcPoint<'a, const LEN: usize, const SCALAR_LEN: usize> {
630    /// Scalar type associated with this EC point.
631    type Scalar<'s>: EcScalar<'s, SCALAR_LEN>
632    where
633        Self: 'a + 's;
634
635    /// Return `true` if this point is a valid public key on the curve, i.e. it
636    /// is on the curve, its coordinates are in range, and it is **not** the
637    /// identity (point at infinity) — equivalently, per RFC 9383 §4, that the
638    /// cofactor multiple `h*P` is not the identity element.
639    ///
640    /// SPAKE2+ requires this validation on the peer's public share (`X` on the
641    /// verifier side, `Y` on the prover side); an unchecked identity/invalid
642    /// point lets a peer force the shared secret and break the protocol's
643    /// guarantees.
644    fn is_valid_pubkey(&self) -> Result<bool, Error>;
645
646    /// Negate this EC point.
647    fn neg(&self) -> Result<Self, Error>
648    where
649        Self: Sized;
650
651    /// Multiply this EC point by the given scalar.
652    fn mul(&self, scalar: &Self::Scalar<'a>) -> Result<Self, Error>
653    where
654        Self: Sized;
655
656    /// Perform an addition-multiplication operation,
657    /// i.e. compute P1 * s1 + P2 * s2, where P1 is `self`.
658    ///
659    /// # Arguments
660    /// - `s1`: Scalar to multiply `self` with.
661    /// - `p2`: Second EC point to multiply with `s2`.
662    /// - `s2`: Scalar to multiply `p2` with.
663    ///
664    /// # Returns
665    /// - The result of the addition-multiplication.
666    fn add_mul(
667        &self,
668        s1: &Self::Scalar<'a>,
669        p2: &Self,
670        s2: &Self::Scalar<'a>,
671    ) -> Result<Self, Error>
672    where
673        Self: Sized;
674
675    /// Write the canonical representation of this EC point into the given buffer.
676    fn write_canon(&self, point: &mut CryptoSensitive<LEN>) -> Result<(), Error>;
677}
678
679#[allow(unused)]
680pub fn default_crypto<'s, R>(
681    rand: R,
682    singleton_secret_key: CanonPkcSecretKeyRef<'s>,
683) -> impl Crypto + 's
684where
685    R: CryptoRng + MaybeSend + 's,
686{
687    #[cfg(feature = "openssl")]
688    let crypto = backend::openssl::OpenSslCrypto::new(singleton_secret_key);
689
690    #[cfg(all(feature = "mbedtls", not(feature = "openssl")))]
691    let crypto = backend::mbedtls::MbedtlsCrypto::new(rand, singleton_secret_key);
692
693    #[cfg(all(
694        feature = "rustcrypto",
695        not(any(feature = "openssl", feature = "mbedtls"))
696    ))]
697    let crypto = backend::rustcrypto::RustCrypto::new(rand, singleton_secret_key);
698
699    #[cfg(not(any(feature = "openssl", feature = "mbedtls", feature = "rustcrypto")))]
700    let crypto = backend::dummy::DummyCrypto;
701
702    crypto
703}
704
705/// The private key of the test Device Attestation Certificate, for [`test_only_crypto`].
706pub const TEST_DAC_PRIVKEY: CanonPkcSecretKeyRef = CanonPkcSecretKeyRef::new(&[
707    0xaa, 0xb6, 0x00, 0xae, 0x8a, 0xe8, 0xaa, 0xb7, 0xd7, 0x36, 0x27, 0xc2, 0x17, 0xb7, 0xc2, 0x04,
708    0x70, 0x9c, 0xa6, 0x94, 0x6a, 0xf5, 0xf2, 0xf7, 0x53, 0x08, 0x33, 0xa5, 0x2b, 0x44, 0xfb, 0xff,
709]);
710
711pub fn test_only_crypto() -> impl Crypto {
712    default_crypto(WeakTestOnlyRand::new_default(), TEST_DAC_PRIVKEY)
713}
714
715#[cfg(test)]
716#[cfg_attr(coverage_nightly, coverage(off))]
717mod tests {
718    use crate::error::ErrorCode;
719    use crate::{
720        test_only_crypto, Aead, CanonPkcPublicKey, CanonPkcPublicKeyRef, CanonPkcSecretKey,
721        CanonPkcSecretKeyRef, CanonPkcSharedSecret, CanonPkcSignature, CanonPkcSignatureRef,
722        Crypto, CryptoSensitive, CryptoSensitiveRef, Digest, Kdf, PbKdf, PublicKey, Rng, SecretKey,
723        SigningSecretKey, AEAD_TAG_LEN, CSR_MAX_LEN, HASH_LEN, PKC_CANON_PUBLIC_KEY_LEN,
724        SHA1_HASH_LEN,
725    };
726
727    /// One-shot SHA-256 over `data` via the `Crypto` trait.
728    fn sha256(data: &[u8]) -> [u8; HASH_LEN] {
729        let crypto = test_only_crypto();
730
731        let mut hasher = unwrap!(crypto.hash());
732        unwrap!(hasher.update(data));
733
734        let mut out = CryptoSensitive::new();
735        unwrap!(hasher.finish(&mut out));
736
737        *out.access()
738    }
739
740    /// HMAC-SHA-256 of `msg` under `key` via the `Crypto` trait.
741    fn hmac_sha256<const KEY_LEN: usize>(key: &[u8; KEY_LEN], msg: &[u8]) -> [u8; HASH_LEN] {
742        let crypto = test_only_crypto();
743
744        let mut hmac = unwrap!(crypto.hmac(CryptoSensitiveRef::new(key)));
745        unwrap!(hmac.update(msg));
746
747        let mut out = CryptoSensitive::new();
748        unwrap!(hmac.finish(&mut out));
749
750        *out.access()
751    }
752
753    /// HKDF-SHA-256 extract+expand via the `Crypto` trait.
754    fn hkdf_sha256<const IKM_LEN: usize, const KEY_LEN: usize>(
755        salt: &[u8],
756        ikm: &[u8; IKM_LEN],
757        info: &[u8],
758    ) -> [u8; KEY_LEN] {
759        let crypto = test_only_crypto();
760
761        let mut out = CryptoSensitive::new();
762        unwrap!(unwrap!(crypto.kdf()).expand(salt, CryptoSensitiveRef::new(ikm), info, &mut out));
763
764        *out.access()
765    }
766
767    /// PBKDF2-HMAC-SHA-256 via the `Crypto` trait.
768    fn pbkdf2_sha256<const PASS_LEN: usize, const KEY_LEN: usize>(
769        pass: &[u8; PASS_LEN],
770        iter: usize,
771        salt: &[u8],
772    ) -> [u8; KEY_LEN] {
773        let crypto = test_only_crypto();
774
775        let mut out = CryptoSensitive::new();
776        unwrap!(unwrap!(crypto.pbkdf()).derive(
777            CryptoSensitiveRef::new(pass),
778            iter,
779            salt,
780            &mut out
781        ));
782
783        *out.access()
784    }
785
786    /// AES-128-CCM encrypt: returns `ciphertext || tag`.
787    fn ccm_encrypt(key: &[u8; 16], nonce: &[u8; 13], aad: &[u8], pt: &[u8]) -> Vec<u8> {
788        let crypto = test_only_crypto();
789        let mut aead = unwrap!(crypto.aead());
790
791        let mut buf = vec![0u8; pt.len() + AEAD_TAG_LEN];
792        buf[..pt.len()].copy_from_slice(pt);
793
794        let out = unwrap!(aead.encrypt_in_place(
795            CryptoSensitiveRef::new(key),
796            CryptoSensitiveRef::new(nonce),
797            aad,
798            &mut buf,
799            pt.len(),
800        ));
801
802        out.to_vec()
803    }
804
805    /// AES-128-CCM decrypt of `ciphertext || tag`: returns the plaintext, or `None`
806    /// if authentication failed.
807    fn ccm_decrypt(key: &[u8; 16], nonce: &[u8; 13], aad: &[u8], ct_tag: &[u8]) -> Option<Vec<u8>> {
808        let crypto = test_only_crypto();
809        let mut aead = unwrap!(crypto.aead());
810
811        let mut buf = ct_tag.to_vec();
812
813        aead.decrypt_in_place(
814            CryptoSensitiveRef::new(key),
815            CryptoSensitiveRef::new(nonce),
816            aad,
817            &mut buf,
818        )
819        .ok()
820        .map(|pt| pt.to_vec())
821    }
822
823    // Vectors from connectedhomeip src/crypto/tests/Hash_SHA256_test_vectors.h (v01, v02, v07, v08)
824    #[test]
825    fn sha256_kat() {
826        assert_eq!(
827            sha256(&[]),
828            [
829                0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f,
830                0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
831                0x78, 0x52, 0xb8, 0x55
832            ]
833        );
834
835        assert_eq!(
836            sha256(&[0xd3]),
837            [
838                0x28, 0x96, 0x9c, 0xdf, 0xa7, 0x4a, 0x12, 0xc8, 0x2f, 0x3b, 0xad, 0x96, 0x0b, 0x0b,
839                0x00, 0x0a, 0xca, 0x2a, 0xc3, 0x29, 0xde, 0xea, 0x5c, 0x23, 0x28, 0xeb, 0xc6, 0xf2,
840                0xba, 0x98, 0x02, 0xc1
841            ]
842        );
843
844        assert_eq!(
845            sha256(&[
846                0x1b, 0x50, 0x3f, 0xb9, 0xa7, 0x3b, 0x16, 0xad, 0xa3, 0xfc, 0xf1, 0x04, 0x26, 0x23,
847                0xae, 0x76, 0x10
848            ]),
849            [
850                0xd5, 0xc3, 0x03, 0x15, 0xf7, 0x2e, 0xd0, 0x5f, 0xe5, 0x19, 0xa1, 0xbf, 0x75, 0xab,
851                0x5f, 0xd0, 0xff, 0xec, 0x5a, 0xc1, 0xac, 0xb0, 0xda, 0xf6, 0x6b, 0x6b, 0x76, 0x95,
852                0x98, 0x59, 0x45, 0x09
853            ]
854        );
855
856        assert_eq!(sha256(SHA256_DATA08), SHA256_HASH08);
857    }
858
859    /// Feeding the input in chunks gives the same digest as one shot, and
860    /// `finish_current` is a non-consuming snapshot of the data seen so far.
861    #[test]
862    fn sha256_incremental() {
863        let crypto = test_only_crypto();
864
865        let mut hasher = unwrap!(crypto.hash());
866        unwrap!(hasher.update(&SHA256_DATA08[..7]));
867        unwrap!(hasher.update(&SHA256_DATA08[7..20]));
868
869        let mut mid = CryptoSensitive::new();
870        unwrap!(hasher.finish_current(&mut mid));
871        assert_eq!(*mid.access(), sha256(&SHA256_DATA08[..20]));
872
873        unwrap!(hasher.update(&SHA256_DATA08[20..]));
874        unwrap!(hasher.update(&[]));
875
876        let mut full = CryptoSensitive::new();
877        unwrap!(hasher.finish(&mut full));
878        assert_eq!(*full.access(), SHA256_HASH08);
879    }
880
881    // FIPS 180-4 example: SHA-1("abc")
882    #[test]
883    fn sha1_kat() {
884        let crypto = test_only_crypto();
885
886        let mut hasher = unwrap!(crypto.hash1());
887        unwrap!(hasher.update(b"abc"));
888
889        let mut out = CryptoSensitive::<SHA1_HASH_LEN>::new();
890        unwrap!(hasher.finish(&mut out));
891
892        assert_eq!(
893            *out.access(),
894            [
895                0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e, 0x25, 0x71, 0x78, 0x50,
896                0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d
897            ]
898        );
899    }
900
901    // Vectors from connectedhomeip src/crypto/tests/HMAC_SHA256_test_vectors.h
902    // (kHmacSha256TestCase1 with a 131-byte key, kHmacKeyHandleSha256TestCase1 with a 16-byte key)
903    #[test]
904    fn hmac_sha256_kat() {
905        let msg = b"Test Using Larger Than Block-Size Key - Hash Key First";
906
907        assert_eq!(
908            hmac_sha256(&[0xaa; 131], msg),
909            [
910                0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5,
911                0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f,
912                0x0e, 0xe3, 0x7f, 0x54
913            ]
914        );
915
916        assert_eq!(
917            hmac_sha256(&[0xba; 16], msg),
918            [
919                0xc0, 0xcd, 0x77, 0x23, 0xdc, 0xf1, 0x57, 0xa5, 0xfe, 0x53, 0xc5, 0x6b, 0x2d, 0x86,
920                0xd4, 0x1c, 0x78, 0x61, 0xb4, 0x20, 0x67, 0xca, 0x7c, 0xae, 0x44, 0x13, 0x57, 0x4d,
921                0x25, 0xda, 0x84, 0x1e
922            ]
923        );
924
925        // A different key must give a different MAC
926        assert_ne!(hmac_sha256(&[0xbb; 16], msg), hmac_sha256(&[0xba; 16], msg));
927    }
928
929    // Vectors from connectedhomeip src/crypto/tests/HKDF_SHA256_test_vectors.h (v1, v2, v3)
930    #[test]
931    fn hkdf_sha256_kat() {
932        // v1: 22-byte IKM, 13-byte salt, 10-byte info, 42-byte OKM
933        let okm: [u8; 42] = hkdf_sha256(
934            &[
935                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
936            ],
937            &[0x0b; 22],
938            &[0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9],
939        );
940        assert_eq!(
941            okm,
942            [
943                0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36,
944                0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56,
945                0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
946            ]
947        );
948
949        // v2: 80-byte IKM/salt/info, 82-byte OKM (spans multiple HMAC blocks)
950        let mut ikm = [0u8; 80];
951        let mut salt = [0u8; 80];
952        let mut info = [0u8; 80];
953        for i in 0..80 {
954            ikm[i] = i as u8;
955            salt[i] = 0x60 + i as u8;
956            info[i] = 0xb0 + i as u8;
957        }
958        let okm: [u8; 82] = hkdf_sha256(&salt, &ikm, &info);
959        assert_eq!(
960            okm,
961            [
962                0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a,
963                0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c,
964                0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb,
965                0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8,
966                0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec,
967                0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87
968            ]
969        );
970
971        // v3: empty salt, 80-byte info, 42-byte OKM
972        let okm: [u8; 42] = hkdf_sha256(&[], &[0x0b; 22], &info);
973        assert_eq!(
974            okm,
975            [
976                0x7a, 0xc3, 0xc1, 0xb4, 0x18, 0xd0, 0xc3, 0xad, 0x19, 0x7a, 0x8f, 0x6d, 0x69, 0x29,
977                0x8a, 0x04, 0x0b, 0x51, 0x23, 0x82, 0x32, 0xd1, 0xf6, 0xbd, 0xa9, 0xe7, 0x69, 0x90,
978                0x5a, 0x09, 0xb6, 0xba, 0x79, 0x81, 0x1d, 0xbe, 0xb3, 0x3a, 0x46, 0xfb, 0x1b, 0x8b
979            ]
980        );
981    }
982
983    // Vectors from connectedhomeip src/crypto/tests/PBKDF2_SHA256_test_vectors.h (tcId 1, 2, 5)
984    #[test]
985    fn pbkdf2_sha256_kat() {
986        let key: [u8; 20] = pbkdf2_sha256(b"password", 1, b"saltSALTsaltSALT");
987        assert_eq!(
988            key,
989            [
990                0xf2, 0xe3, 0x4b, 0xd9, 0x50, 0xe9, 0x1c, 0xf3, 0x7d, 0x22, 0xe1, 0x13, 0x5a, 0x39,
991                0x9b, 0x02, 0xa1, 0x7c, 0xb1, 0x93
992            ]
993        );
994
995        let key: [u8; 20] = pbkdf2_sha256(b"password", 2, b"saltSALTsaltSALT");
996        assert_eq!(
997            key,
998            [
999                0x2b, 0x77, 0x27, 0x5c, 0xc3, 0x12, 0x0b, 0x15, 0x13, 0xf6, 0xf3, 0xe0, 0x36, 0x49,
1000                0xfd, 0x49, 0x33, 0x76, 0x52, 0x60
1001            ]
1002        );
1003
1004        let key: [u8; 25] = pbkdf2_sha256(
1005            b"passwordPASSWORDpassword",
1006            10,
1007            b"saltSALTsaltSALTsaltSALTsaltSALT",
1008        );
1009        assert_eq!(
1010            key,
1011            [
1012                0x0d, 0xbf, 0x87, 0x38, 0xd2, 0x30, 0xbf, 0x28, 0xba, 0xe0, 0xfb, 0x4d, 0x8f, 0x07,
1013                0x34, 0x98, 0x24, 0xb5, 0xe0, 0xb1, 0xa7, 0x0b, 0xa2, 0x19, 0x3b
1014            ]
1015        );
1016    }
1017
1018    // Vectors from connectedhomeip src/crypto/tests/AES_CCM_128_test_vectors.h
1019    // (aesccm128_matter_*_test_vector_0, _10 and _11: 13-byte nonce, 16-byte tag)
1020    struct CcmVector {
1021        key: [u8; 16],
1022        nonce: [u8; 13],
1023        aad: &'static [u8],
1024        pt: &'static [u8],
1025        ct: &'static [u8],
1026        tag: [u8; 16],
1027    }
1028
1029    const CCM_VECTORS: &[CcmVector] = &[
1030        // tcId 0: 13-byte plaintext, no AAD
1031        CcmVector {
1032            key: [
1033                0x09, 0x53, 0xfa, 0x93, 0xe7, 0xca, 0xac, 0x96, 0x38, 0xf5, 0x88, 0x20, 0x22, 0x0a,
1034                0x39, 0x8e,
1035            ],
1036            nonce: [
1037                0x00, 0x80, 0x00, 0x00, 0x01, 0x12, 0x01, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78,
1038            ],
1039            aad: &[],
1040            pt: &[
1041                0xff, 0xfd, 0x03, 0x4b, 0x50, 0x05, 0x7e, 0x40, 0x00, 0x00, 0x01, 0x00, 0x00,
1042            ],
1043            ct: &[
1044                0xb5, 0xe5, 0xbf, 0xda, 0xcb, 0xaf, 0x6c, 0xb7, 0xfb, 0x6b, 0xff, 0x87, 0x1f,
1045            ],
1046            tag: [
1047                0xb0, 0xd6, 0xdd, 0x82, 0x7d, 0x35, 0xbf, 0x37, 0x2f, 0xa6, 0x42, 0x5d, 0xcd, 0x17,
1048                0xd3, 0x56,
1049            ],
1050        },
1051        // tcId 10: 8-byte plaintext, 16-byte AAD
1052        CcmVector {
1053            key: [
1054                0x63, 0x96, 0x47, 0x71, 0x73, 0x4f, 0xbd, 0x76, 0xe3, 0xb4, 0x05, 0x19, 0xd1, 0xd9,
1055                0x4a, 0x48,
1056            ],
1057            nonce: [
1058                0x01, 0x00, 0x07, 0x08, 0x0d, 0x12, 0x34, 0x97, 0x36, 0x12, 0x34, 0x56, 0x77,
1059            ],
1060            aad: &[
1061                0xf4, 0xa0, 0x02, 0xc7, 0xfb, 0x1e, 0x4c, 0xa0, 0xa4, 0x69, 0xa0, 0x21, 0xde, 0x0d,
1062                0xb8, 0x75,
1063            ],
1064            pt: &[0xea, 0x0a, 0x00, 0x57, 0x6f, 0x72, 0x6c, 0x64],
1065            ct: &[0xde, 0x15, 0x47, 0x11, 0x84, 0x63, 0x12, 0x3e],
1066            tag: [
1067                0x14, 0x60, 0x4c, 0x1d, 0xdb, 0x4f, 0x59, 0x87, 0x06, 0x4b, 0x17, 0x36, 0xf3, 0x92,
1068                0x39, 0x62,
1069            ],
1070        },
1071        // tcId 11: empty plaintext, 1-byte AAD
1072        CcmVector {
1073            key: [
1074                0x08, 0xb0, 0xda, 0x25, 0x5d, 0x20, 0x83, 0x80, 0x8a, 0x1b, 0x4d, 0x36, 0x70, 0x90,
1075                0xba, 0xcc,
1076            ],
1077            nonce: [
1078                0x77, 0x78, 0x28, 0xb1, 0x36, 0x79, 0xa9, 0xe2, 0xca, 0x89, 0x56, 0x82, 0x33,
1079            ],
1080            aad: &[0xc5],
1081            pt: &[],
1082            ct: &[],
1083            tag: [
1084                0x0a, 0x93, 0xec, 0x4a, 0x8f, 0xf3, 0x39, 0x64, 0xf5, 0x80, 0x05, 0x86, 0x8a, 0x86,
1085                0x88, 0x56,
1086            ],
1087        },
1088    ];
1089
1090    #[test]
1091    fn aes_ccm_encrypt_kat() {
1092        for v in CCM_VECTORS {
1093            let out = ccm_encrypt(&v.key, &v.nonce, v.aad, v.pt);
1094
1095            assert_eq!(out.len(), v.ct.len() + AEAD_TAG_LEN);
1096            assert_eq!(&out[..v.ct.len()], v.ct);
1097            assert_eq!(&out[v.ct.len()..], &v.tag);
1098        }
1099    }
1100
1101    #[test]
1102    fn aes_ccm_decrypt_kat() {
1103        for v in CCM_VECTORS {
1104            let mut ct_tag = v.ct.to_vec();
1105            ct_tag.extend_from_slice(&v.tag);
1106
1107            assert_eq!(
1108                ccm_decrypt(&v.key, &v.nonce, v.aad, &ct_tag).as_deref(),
1109                Some(v.pt)
1110            );
1111        }
1112    }
1113
1114    #[test]
1115    fn aes_ccm_decrypt_tampered_tag_fails() {
1116        let v = &CCM_VECTORS[1];
1117
1118        let mut ct_tag = v.ct.to_vec();
1119        ct_tag.extend_from_slice(&v.tag);
1120        let last = ct_tag.len() - 1;
1121        ct_tag[last] ^= 0x01;
1122
1123        assert!(ccm_decrypt(&v.key, &v.nonce, v.aad, &ct_tag).is_none());
1124    }
1125
1126    #[test]
1127    fn aes_ccm_decrypt_tampered_ciphertext_fails() {
1128        let v = &CCM_VECTORS[1];
1129
1130        let mut ct_tag = v.ct.to_vec();
1131        ct_tag.extend_from_slice(&v.tag);
1132        ct_tag[0] ^= 0x80;
1133
1134        assert!(ccm_decrypt(&v.key, &v.nonce, v.aad, &ct_tag).is_none());
1135    }
1136
1137    #[test]
1138    fn aes_ccm_decrypt_wrong_aad_or_nonce_fails() {
1139        let v = &CCM_VECTORS[1];
1140
1141        let mut ct_tag = v.ct.to_vec();
1142        ct_tag.extend_from_slice(&v.tag);
1143
1144        let mut aad = v.aad.to_vec();
1145        aad[3] ^= 0x01;
1146        assert!(ccm_decrypt(&v.key, &v.nonce, &aad, &ct_tag).is_none());
1147
1148        // Dropping the AAD entirely must also fail
1149        assert!(ccm_decrypt(&v.key, &v.nonce, &[], &ct_tag).is_none());
1150
1151        let mut nonce = v.nonce;
1152        nonce[12] ^= 0x01;
1153        assert!(ccm_decrypt(&v.key, &nonce, v.aad, &ct_tag).is_none());
1154
1155        // Sanity: the untouched inputs still decrypt
1156        assert!(ccm_decrypt(&v.key, &v.nonce, v.aad, &ct_tag).is_some());
1157    }
1158
1159    /// A ciphertext shorter than the tag cannot be authenticated.
1160    #[test]
1161    fn aes_ccm_decrypt_too_short_fails() {
1162        let v = &CCM_VECTORS[0];
1163
1164        assert!(ccm_decrypt(&v.key, &v.nonce, v.aad, &v.tag[..AEAD_TAG_LEN - 1]).is_none());
1165    }
1166
1167    /// The RFC 6979 P-256 key shared by all vectors in
1168    /// connectedhomeip src/crypto/tests/ECDSA_det_test_vectors.h
1169    const ECDSA_DET_PRIV_KEY: CanonPkcSecretKeyRef = CanonPkcSecretKeyRef::new(&[
1170        0xC9, 0xAF, 0xA9, 0xD8, 0x45, 0xBA, 0x75, 0x16, 0x6B, 0x5C, 0x21, 0x57, 0x67, 0xB1, 0xD6,
1171        0x93, 0x4E, 0x50, 0xC3, 0xDB, 0x36, 0xE8, 0x9B, 0x12, 0x7B, 0x8A, 0x62, 0x2B, 0x12, 0x0F,
1172        0x67, 0x21,
1173    ]);
1174
1175    /// The uncompressed SEC1 encoding (`0x04 || X || Y`) of the public key above.
1176    const ECDSA_DET_PUB_KEY: CanonPkcPublicKeyRef = CanonPkcPublicKeyRef::new(&[
1177        0x04, 0x60, 0xFE, 0xD4, 0xBA, 0x25, 0x5A, 0x9D, 0x31, 0xC9, 0x61, 0xEB, 0x74, 0xC6, 0x35,
1178        0x6D, 0x68, 0xC0, 0x49, 0xB8, 0x92, 0x3B, 0x61, 0xFA, 0x6C, 0xE6, 0x69, 0x62, 0x2E, 0x60,
1179        0xF2, 0x9F, 0xB6, 0x79, 0x03, 0xFE, 0x10, 0x08, 0xB8, 0xBC, 0x99, 0xA4, 0x1A, 0xE9, 0xE9,
1180        0x56, 0x28, 0xBC, 0x64, 0xF2, 0xF1, 0xB2, 0x0C, 0x2D, 0x7E, 0x9F, 0x51, 0x77, 0xA3, 0xC2,
1181        0x94, 0xD4, 0x46, 0x22, 0x99,
1182    ]);
1183
1184    /// (message, r || s) pairs from connectedhomeip src/crypto/tests/ECDSA_det_test_vectors.h
1185    const ECDSA_DET_VECTORS: &[(&[u8], [u8; 64])] = &[
1186        (
1187            b"sample",
1188            [
1189                0xEF, 0xD4, 0x8B, 0x2A, 0xAC, 0xB6, 0xA8, 0xFD, 0x11, 0x40, 0xDD, 0x9C, 0xD4, 0x5E,
1190                0x81, 0xD6, 0x9D, 0x2C, 0x87, 0x7B, 0x56, 0xAA, 0xF9, 0x91, 0xC3, 0x4D, 0x0E, 0xA8,
1191                0x4E, 0xAF, 0x37, 0x16, 0xF7, 0xCB, 0x1C, 0x94, 0x2D, 0x65, 0x7C, 0x41, 0xD4, 0x36,
1192                0xC7, 0xA1, 0xB6, 0xE2, 0x9F, 0x65, 0xF3, 0xE9, 0x00, 0xDB, 0xB9, 0xAF, 0xF4, 0x06,
1193                0x4D, 0xC4, 0xAB, 0x2F, 0x84, 0x3A, 0xCD, 0xA8,
1194            ],
1195        ),
1196        (
1197            b"test",
1198            [
1199                0xF1, 0xAB, 0xB0, 0x23, 0x51, 0x83, 0x51, 0xCD, 0x71, 0xD8, 0x81, 0x56, 0x7B, 0x1E,
1200                0xA6, 0x63, 0xED, 0x3E, 0xFC, 0xF6, 0xC5, 0x13, 0x2B, 0x35, 0x4F, 0x28, 0xD3, 0xB0,
1201                0xB7, 0xD3, 0x83, 0x67, 0x01, 0x9F, 0x41, 0x13, 0x74, 0x2A, 0x2B, 0x14, 0xBD, 0x25,
1202                0x92, 0x6B, 0x49, 0xC6, 0x49, 0x15, 0x5F, 0x26, 0x7E, 0x60, 0xD3, 0x81, 0x4B, 0x4C,
1203                0x0C, 0xC8, 0x42, 0x50, 0xE4, 0x6F, 0x00, 0x83,
1204            ],
1205        ),
1206        // SHA-256(message) >= curve order
1207        (
1208            b"\xca\xb5\x89\x7a\x2d\xa7\x3c\x33",
1209            [
1210                0x24, 0x9E, 0x5A, 0x94, 0xCE, 0x56, 0x7B, 0x42, 0xC0, 0xCB, 0xFC, 0xF5, 0x59, 0xCE,
1211                0x5F, 0x95, 0x1D, 0x5A, 0xA1, 0xF5, 0xC5, 0x4A, 0x10, 0x0C, 0x17, 0x00, 0xA9, 0x91,
1212                0x39, 0xDB, 0x93, 0x59, 0x33, 0x71, 0xC6, 0x28, 0x79, 0x75, 0x54, 0x9A, 0x34, 0x81,
1213                0xD9, 0xFB, 0x5E, 0x10, 0xDB, 0x17, 0xFF, 0x7C, 0x90, 0xE1, 0xA6, 0x73, 0xB7, 0x9A,
1214                0xC0, 0x58, 0x9A, 0x53, 0x78, 0x7B, 0x1E, 0x38,
1215            ],
1216        ),
1217        // First deterministic k candidate >= curve order
1218        (
1219            b"\x0a\x1c\x40\xa8\xcd\x85\x44\x01",
1220            [
1221                0xAD, 0xC7, 0xBE, 0x41, 0x40, 0x8E, 0x47, 0x17, 0x6C, 0x47, 0x0D, 0x95, 0x78, 0xCE,
1222                0x5D, 0x1A, 0xF7, 0x78, 0xA2, 0x7F, 0x4B, 0x63, 0x7D, 0x1A, 0x7C, 0x3F, 0xA6, 0x7B,
1223                0xD6, 0xDD, 0xDE, 0x74, 0xB3, 0x42, 0x50, 0x59, 0xB4, 0xD0, 0x6F, 0xF8, 0x0B, 0x4B,
1224                0xE8, 0x75, 0x49, 0x07, 0xE4, 0x9D, 0x17, 0x12, 0x14, 0x74, 0xCE, 0xE3, 0x8D, 0x1F,
1225                0xFB, 0x30, 0x75, 0x6C, 0x39, 0xD6, 0x4C, 0xD3,
1226            ],
1227        ),
1228    ];
1229
1230    /// Verification of the RFC 6979 deterministic signatures. Only verification
1231    /// is exercised, since signing is randomized on some backends.
1232    #[test]
1233    fn ecdsa_det_vectors_verify() {
1234        let crypto = test_only_crypto();
1235        let key = unwrap!(crypto.pub_key(ECDSA_DET_PUB_KEY));
1236
1237        for (msg, sig) in ECDSA_DET_VECTORS {
1238            assert!(unwrap!(key.verify(msg, CryptoSensitiveRef::new(sig))));
1239        }
1240
1241        // A signature over one message does not verify over another
1242        assert!(!unwrap!(key.verify(
1243            ECDSA_DET_VECTORS[1].0,
1244            CryptoSensitiveRef::new(&ECDSA_DET_VECTORS[0].1)
1245        )));
1246    }
1247
1248    /// The public key derived from a canonical secret key matches the known point,
1249    /// and the secret key exports back to the same canonical bytes.
1250    #[test]
1251    fn ecdsa_secret_key_canon_roundtrip() {
1252        let crypto = test_only_crypto();
1253        let key = unwrap!(crypto.secret_key(ECDSA_DET_PRIV_KEY));
1254
1255        let mut canon_priv = CanonPkcSecretKey::new();
1256        unwrap!(key.write_canon(&mut canon_priv));
1257        assert_eq!(canon_priv.access(), ECDSA_DET_PRIV_KEY.access());
1258
1259        let mut canon_pub = CanonPkcPublicKey::new();
1260        unwrap!(unwrap!(key.pub_key()).write_canon(&mut canon_pub));
1261        assert_eq!(canon_pub.access(), ECDSA_DET_PUB_KEY.access());
1262    }
1263
1264    #[test]
1265    fn ecdsa_sign_then_verify() {
1266        let crypto = test_only_crypto();
1267        let key = unwrap!(crypto.secret_key(ECDSA_DET_PRIV_KEY));
1268        let msg = b"The quick brown fox jumps over the lazy dog";
1269
1270        let mut sig = CanonPkcSignature::new();
1271        unwrap!(key.sign(msg, &mut sig));
1272        assert_ne!(sig.access(), &[0u8; 64]);
1273
1274        // Verifies with the matching public key (imported from canon bytes as well)
1275        assert!(unwrap!(unwrap!(key.pub_key()).verify(msg, sig.reference())));
1276        let imported = unwrap!(crypto.pub_key(ECDSA_DET_PUB_KEY));
1277        assert!(unwrap!(imported.verify(msg, sig.reference())));
1278
1279        // Fails with a different key
1280        let other = unwrap!(crypto.pub_key(PUB_KEY1));
1281        assert!(!unwrap!(other.verify(msg, sig.reference())));
1282
1283        // Fails over a tampered message
1284        let mut tampered = *msg;
1285        tampered[0] ^= 0x20;
1286        assert!(!unwrap!(imported.verify(&tampered, sig.reference())));
1287
1288        // Fails with a tampered signature
1289        let mut bad_sig = sig.clone();
1290        bad_sig.access_mut()[63] ^= 0x01;
1291        assert!(!unwrap!(imported.verify(msg, bad_sig.reference())));
1292    }
1293
1294    /// A freshly generated key is non-trivial and signs/verifies.
1295    #[test]
1296    fn ecdsa_generated_key_signs() {
1297        let crypto = test_only_crypto();
1298        let key = unwrap!(crypto.generate_secret_key());
1299
1300        let mut canon = CanonPkcSecretKey::new();
1301        unwrap!(key.write_canon(&mut canon));
1302        assert_ne!(canon.access(), &[0u8; 32]);
1303
1304        let mut canon_pub = CanonPkcPublicKey::new();
1305        unwrap!(unwrap!(key.pub_key()).write_canon(&mut canon_pub));
1306        assert_eq!(canon_pub.access()[0], 0x04);
1307
1308        let mut sig = CanonPkcSignature::new();
1309        unwrap!(key.sign(b"hello", &mut sig));
1310        assert!(unwrap!(
1311            unwrap!(key.pub_key()).verify(b"hello", sig.reference())
1312        ));
1313
1314        // Re-importing the exported canon bytes gives the same public key
1315        let reimported = unwrap!(crypto.secret_key(canon.reference()));
1316        let mut canon_pub2 = CanonPkcPublicKey::new();
1317        unwrap!(unwrap!(reimported.pub_key()).write_canon(&mut canon_pub2));
1318        assert_eq!(canon_pub.access(), canon_pub2.access());
1319    }
1320
1321    /// The singleton signing key is the one `test_only_crypto` was built with.
1322    #[test]
1323    fn singleton_signing_key_matches_dac() {
1324        let crypto = test_only_crypto();
1325
1326        let singleton = unwrap!(crypto.singleton_singing_secret_key());
1327        let mut singleton_pub = CanonPkcPublicKey::new();
1328        unwrap!(unwrap!(singleton.pub_key()).write_canon(&mut singleton_pub));
1329
1330        let dac = unwrap!(crypto.secret_key(super::TEST_DAC_PRIVKEY));
1331        let mut dac_pub = CanonPkcPublicKey::new();
1332        unwrap!(unwrap!(dac.pub_key()).write_canon(&mut dac_pub));
1333
1334        assert_eq!(singleton_pub.access(), dac_pub.access());
1335
1336        let mut sig = CanonPkcSignature::new();
1337        unwrap!(singleton.sign(b"attest", &mut sig));
1338        assert!(unwrap!(
1339            unwrap!(dac.pub_key()).verify(b"attest", sig.reference())
1340        ));
1341
1342        let mut csr_buf = [0u8; 512];
1343        let csr = unwrap!(singleton.csr(&mut csr_buf));
1344        // DER SEQUENCE
1345        assert_eq!(csr[0], 0x30);
1346        assert!(csr.len() > PKC_CANON_PUBLIC_KEY_LEN);
1347    }
1348
1349    // Vectors from connectedhomeip src/crypto/tests/ECDH_P256_test_vectors.h (ecdh_v1..v3)
1350    #[test]
1351    fn ecdh_kat() {
1352        const VECTORS: &[([u8; 32], [u8; 65], [u8; 32])] = &[
1353            (
1354                [
1355                    0x7d, 0x7d, 0xc5, 0xf7, 0x1e, 0xb2, 0x9d, 0xda, 0xf8, 0x0d, 0x62, 0x14, 0x63,
1356                    0x2e, 0xea, 0xe0, 0x3d, 0x90, 0x58, 0xaf, 0x1f, 0xb6, 0xd2, 0x2e, 0xd8, 0x0b,
1357                    0xad, 0xb6, 0x2b, 0xc1, 0xa5, 0x34,
1358                ],
1359                [
1360                    0x04, 0x70, 0x0c, 0x48, 0xf7, 0x7f, 0x56, 0x58, 0x4c, 0x5c, 0xc6, 0x32, 0xca,
1361                    0x65, 0x64, 0x0d, 0xb9, 0x1b, 0x6b, 0xac, 0xce, 0x3a, 0x4d, 0xf6, 0xb4, 0x2c,
1362                    0xe7, 0xcc, 0x83, 0x88, 0x33, 0xd2, 0x87, 0xdb, 0x71, 0xe5, 0x09, 0xe3, 0xfd,
1363                    0x9b, 0x06, 0x0d, 0xdb, 0x20, 0xba, 0x5c, 0x51, 0xdc, 0xc5, 0x94, 0x8d, 0x46,
1364                    0xfb, 0xf6, 0x40, 0xdf, 0xe0, 0x44, 0x17, 0x82, 0xca, 0xb8, 0x5f, 0xa4, 0xac,
1365                ],
1366                [
1367                    0x46, 0xfc, 0x62, 0x10, 0x64, 0x20, 0xff, 0x01, 0x2e, 0x54, 0xa4, 0x34, 0xfb,
1368                    0xdd, 0x2d, 0x25, 0xcc, 0xc5, 0x85, 0x20, 0x60, 0x56, 0x1e, 0x68, 0x04, 0x0d,
1369                    0xd7, 0x77, 0x89, 0x97, 0xbd, 0x7b,
1370                ],
1371            ),
1372            (
1373                [
1374                    0xf5, 0xf8, 0xe0, 0x17, 0x46, 0x10, 0xa6, 0x61, 0x27, 0x79, 0x79, 0xb5, 0x8c,
1375                    0xe5, 0xc9, 0x0f, 0xee, 0x6c, 0x9b, 0x3b, 0xb3, 0x46, 0xa9, 0x0a, 0x71, 0x96,
1376                    0x25, 0x5e, 0x40, 0xb1, 0x32, 0xef,
1377                ],
1378                [
1379                    0x04, 0x33, 0xe8, 0x20, 0x92, 0xa0, 0xf1, 0xfb, 0x38, 0xf5, 0x64, 0x9d, 0x58,
1380                    0x67, 0xfb, 0xa2, 0x8b, 0x50, 0x31, 0x72, 0xb7, 0x03, 0x55, 0x74, 0xbf, 0x8e,
1381                    0x5b, 0x71, 0x00, 0xa3, 0x05, 0x27, 0x92, 0xf2, 0xcf, 0x6b, 0x60, 0x1e, 0x0a,
1382                    0x05, 0x94, 0x5e, 0x33, 0x55, 0x50, 0xbf, 0x64, 0x8d, 0x78, 0x2f, 0x46, 0x18,
1383                    0x6c, 0x77, 0x2c, 0x0f, 0x20, 0xd3, 0xcd, 0x0d, 0x6b, 0x8c, 0xa1, 0x4b, 0x2f,
1384                ],
1385                [
1386                    0x66, 0x4e, 0x45, 0xd5, 0xbb, 0xa4, 0xac, 0x93, 0x1c, 0xd6, 0x5d, 0x52, 0x01,
1387                    0x7e, 0x4b, 0xe9, 0xb1, 0x9a, 0x51, 0x5f, 0x66, 0x9b, 0xea, 0x47, 0x03, 0x54,
1388                    0x2a, 0x2c, 0x52, 0x5c, 0xd3, 0xd3,
1389                ],
1390            ),
1391            // Shared secret with a leading zero byte
1392            (
1393                [
1394                    0x7A, 0xE6, 0x7A, 0xFC, 0xF2, 0x50, 0x5C, 0x12, 0xB7, 0x60, 0x0F, 0xA2, 0x25,
1395                    0x85, 0x9A, 0xFE, 0x36, 0xFA, 0x01, 0xE7, 0xB0, 0x78, 0x9C, 0xF5, 0x9B, 0x06,
1396                    0xA1, 0xC9, 0xB8, 0xEF, 0x90, 0xD2,
1397                ],
1398                [
1399                    0x04, 0x19, 0x6C, 0x32, 0xA9, 0x90, 0x1B, 0xDC, 0x81, 0x70, 0x28, 0x0C, 0x78,
1400                    0x94, 0x71, 0x32, 0xB9, 0x2C, 0x9A, 0x7B, 0x8D, 0x4F, 0x59, 0x7A, 0x18, 0x33,
1401                    0x71, 0x25, 0x45, 0x8C, 0xCF, 0x92, 0x56, 0x1B, 0xA3, 0x80, 0x9E, 0xC1, 0xB9,
1402                    0x66, 0x8A, 0x29, 0x03, 0x68, 0x66, 0xE6, 0xD8, 0x45, 0x89, 0x11, 0x01, 0x3E,
1403                    0x2E, 0x78, 0xF9, 0x29, 0x6E, 0x86, 0xD6, 0x81, 0x7F, 0x7A, 0xE6, 0xF3, 0x09,
1404                ],
1405                [
1406                    0x00, 0x13, 0xB5, 0x76, 0xC6, 0xC0, 0x27, 0x02, 0xB1, 0xB6, 0x6C, 0x67, 0xFA,
1407                    0xB4, 0x6D, 0xA8, 0x54, 0x88, 0x0A, 0x39, 0xD7, 0x5F, 0xA7, 0x44, 0x64, 0x1F,
1408                    0xFA, 0x61, 0x11, 0x82, 0x3A, 0x4E,
1409                ],
1410            ),
1411        ];
1412
1413        let crypto = test_only_crypto();
1414
1415        for (priv_key, peer_pub, expected) in VECTORS {
1416            let key = unwrap!(crypto.secret_key(CryptoSensitiveRef::new(priv_key)));
1417            let peer = unwrap!(crypto.pub_key(CryptoSensitiveRef::new(peer_pub)));
1418
1419            let mut shared = CanonPkcSharedSecret::new();
1420            unwrap!(key.derive_shared_secret(&peer, &mut shared));
1421
1422            assert_eq!(shared.access(), expected);
1423        }
1424    }
1425
1426    /// ECDH is symmetric: both sides derive the same secret, and a third
1427    /// key derives something else.
1428    #[test]
1429    fn ecdh_symmetric() {
1430        let crypto = test_only_crypto();
1431
1432        let a = unwrap!(crypto.generate_secret_key());
1433        let b = unwrap!(crypto.generate_secret_key());
1434        let c = unwrap!(crypto.generate_secret_key());
1435
1436        let mut ab = CanonPkcSharedSecret::new();
1437        unwrap!(a.derive_shared_secret(&unwrap!(b.pub_key()), &mut ab));
1438
1439        let mut ba = CanonPkcSharedSecret::new();
1440        unwrap!(b.derive_shared_secret(&unwrap!(a.pub_key()), &mut ba));
1441
1442        let mut cb = CanonPkcSharedSecret::new();
1443        unwrap!(c.derive_shared_secret(&unwrap!(b.pub_key()), &mut cb));
1444
1445        assert_eq!(ab.access(), ba.access());
1446        assert_ne!(ab.access(), cb.access());
1447        assert_ne!(ab.access(), &[0u8; 32]);
1448    }
1449
1450    /// Importing a byte string that is not a point on the curve fails.
1451    #[test]
1452    fn pub_key_import_rejects_invalid_point() {
1453        let crypto = test_only_crypto();
1454
1455        let mut bad = *PUB_KEY1.access();
1456        bad[64] ^= 0x01;
1457
1458        assert!(crypto.pub_key(CryptoSensitiveRef::new(&bad)).is_err());
1459    }
1460
1461    /// A buffer shorter than the longest CSR.
1462    #[test]
1463    fn csr_into_small_buffer_fails() {
1464        let crypto = test_only_crypto();
1465        let key = unwrap!(crypto.secret_key(super::TEST_DAC_PRIVKEY));
1466
1467        let mut buf = [0u8; CSR_MAX_LEN - 1];
1468        let result = key.csr(&mut buf);
1469        assert_eq!(
1470            result.err().map(|e| e.code()),
1471            Some(ErrorCode::BufferTooSmall)
1472        );
1473    }
1474
1475    #[test]
1476    fn rand_draws_differ() {
1477        let crypto = test_only_crypto();
1478
1479        let mut rng = unwrap!(crypto.rand());
1480        let a = rng.next_u32();
1481        let b = rng.next_u32();
1482        let c = rng.next_u64();
1483        assert!(a != b || c != a as u64);
1484
1485        let mut x = [0u8; 16];
1486        let mut y = [0u8; 16];
1487        rng.fill_bytes(&mut x);
1488        rng.fill_bytes(&mut y);
1489        assert_ne!(x, y);
1490
1491        let mut weak = unwrap!(crypto.weak_rand());
1492        let mut wx = [0u8; 16];
1493        let mut wy = [0u8; 16];
1494        weak.fill_bytes(&mut wx);
1495        weak.fill_bytes(&mut wy);
1496        assert_ne!(wx, wy);
1497    }
1498
1499    #[test]
1500    fn rand_fill_large_buffer_is_nonzero() {
1501        let crypto = test_only_crypto();
1502
1503        let mut rng = unwrap!(crypto.rand());
1504        let mut buf = [0u8; 1024];
1505        rng.fill_bytes(&mut buf);
1506
1507        assert!(buf.iter().any(|b| *b != 0));
1508        // Every 64-byte window should have some entropy in it
1509        assert!(buf.chunks(64).all(|c| c.iter().any(|b| *b != 0)));
1510
1511        // An odd-length fill also works
1512        let mut odd = [0u8; 33];
1513        rng.fill_bytes(&mut odd);
1514        assert!(odd.iter().any(|b| *b != 0));
1515    }
1516
1517    // Vector v08 from connectedhomeip src/crypto/tests/Hash_SHA256_test_vectors.h (59 bytes)
1518    const SHA256_DATA08: &[u8] = &[
1519        0xd1, 0xbe, 0x3f, 0x13, 0xfe, 0xba, 0xfe, 0xfc, 0x14, 0x41, 0x4d, 0x9f, 0xb7, 0xf6, 0x93,
1520        0xdb, 0x16, 0xdc, 0x1a, 0xe2, 0x70, 0xc5, 0xb6, 0x47, 0xd8, 0x0d, 0xa8, 0x58, 0x35, 0x87,
1521        0xc1, 0xad, 0x8c, 0xb8, 0xcb, 0x01, 0x82, 0x43, 0x24, 0x41, 0x1c, 0xa5, 0xac, 0xe3, 0xca,
1522        0x22, 0xe1, 0x79, 0xa4, 0xff, 0x49, 0x86, 0xf3, 0xf2, 0x11, 0x90, 0xf3, 0xd7, 0xf3,
1523    ];
1524
1525    const SHA256_HASH08: [u8; HASH_LEN] = [
1526        0x02, 0x80, 0x49, 0x78, 0xeb, 0xa6, 0xe1, 0xde, 0x65, 0xaf, 0xdb, 0xc6, 0xa6, 0x09, 0x1e,
1527        0xd6, 0xb1, 0xec, 0xee, 0x51, 0xe8, 0xbf, 0xf4, 0x06, 0x46, 0xa2, 0x51, 0xde, 0x66, 0x78,
1528        0xb7, 0xef,
1529    ];
1530
1531    #[test]
1532    fn test_verify_msg_success() {
1533        let crypto = test_only_crypto();
1534
1535        let key = unwrap!(crypto.pub_key(PUB_KEY1));
1536        assert_eq!(unwrap!(key.verify(MSG1_SUCCESS, SIGNATURE1)), true);
1537    }
1538
1539    #[test]
1540    fn test_verify_msg_fail() {
1541        let crypto = test_only_crypto();
1542
1543        let key = unwrap!(crypto.pub_key(PUB_KEY1));
1544        assert_eq!(unwrap!(key.verify(MSG1_FAIL, SIGNATURE1)), false);
1545    }
1546
1547    const PUB_KEY1: CanonPkcPublicKeyRef = CanonPkcPublicKeyRef::new(&[
1548        0x4, 0x56, 0x19, 0x77, 0x18, 0x3f, 0xd4, 0xff, 0x2b, 0x58, 0x3d, 0xe9, 0x79, 0x34, 0x66,
1549        0xdf, 0xe9, 0x0, 0xfb, 0x6d, 0xa1, 0xef, 0xe0, 0xcc, 0xdc, 0x77, 0x30, 0xc0, 0x6f, 0xb6,
1550        0x2d, 0xff, 0xbe, 0x54, 0xa0, 0x95, 0x75, 0xb, 0x8b, 0x7, 0xbc, 0x55, 0xdb, 0x9c, 0xb6,
1551        0x55, 0x13, 0x8, 0xb8, 0xdf, 0x2, 0xe3, 0x40, 0x6b, 0xae, 0x34, 0xf5, 0xc, 0xba, 0xc9,
1552        0xf2, 0xbf, 0xf1, 0xe7, 0x50,
1553    ]);
1554
1555    const MSG1_SUCCESS: &[u8] = &[
1556        0x30, 0x82, 0x1, 0xa1, 0xa0, 0x3, 0x2, 0x1, 0x2, 0x2, 0x1, 0x1, 0x30, 0xa, 0x6, 0x8, 0x2a,
1557        0x86, 0x48, 0xce, 0x3d, 0x4, 0x3, 0x2, 0x30, 0x44, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b,
1558        0x6, 0x1, 0x4, 0x1, 0x82, 0xa2, 0x7c, 0x1, 0x3, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30,
1559        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x31, 0x20, 0x30, 0x1e,
1560        0x6, 0xa, 0x2b, 0x6, 0x1, 0x4, 0x1, 0x82, 0xa2, 0x7c, 0x1, 0x5, 0xc, 0x10, 0x30, 0x30,
1561        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30,
1562        0x1e, 0x17, 0xd, 0x32, 0x31, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1563        0x5a, 0x17, 0xd, 0x33, 0x30, 0x31, 0x32, 0x33, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1564        0x5a, 0x30, 0x44, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b, 0x6, 0x1, 0x4, 0x1, 0x82, 0xa2,
1565        0x7c, 0x1, 0x1, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1566        0x42, 0x43, 0x35, 0x43, 0x30, 0x32, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b, 0x6, 0x1, 0x4,
1567        0x1, 0x82, 0xa2, 0x7c, 0x1, 0x5, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1568        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30, 0x13, 0x6, 0x7, 0x2a,
1569        0x86, 0x48, 0xce, 0x3d, 0x2, 0x1, 0x6, 0x8, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x3, 0x1, 0x7,
1570        0x3, 0x42, 0x0, 0x4, 0x6, 0x47, 0xf2, 0x86, 0x4d, 0x27, 0x25, 0xdc, 0x1, 0xa, 0x87, 0xde,
1571        0x8d, 0xca, 0x88, 0x37, 0xcb, 0x3b, 0xd0, 0xea, 0x93, 0xa6, 0x24, 0x65, 0x8, 0x8f, 0xa1,
1572        0x75, 0xc2, 0xd4, 0x41, 0xfa, 0xca, 0x96, 0x54, 0xa3, 0xd8, 0x10, 0x85, 0x73, 0xce, 0x15,
1573        0xa5, 0x38, 0xc1, 0xe3, 0xb5, 0x6b, 0x61, 0x1, 0xd3, 0xc4, 0xb7, 0x6b, 0x61, 0x16, 0xc3,
1574        0x77, 0x8d, 0xe9, 0xb5, 0x44, 0xac, 0x14, 0xa3, 0x81, 0x83, 0x30, 0x81, 0x80, 0x30, 0xc,
1575        0x6, 0x3, 0x55, 0x1d, 0x13, 0x1, 0x1, 0xff, 0x4, 0x2, 0x30, 0x0, 0x30, 0xe, 0x6, 0x3, 0x55,
1576        0x1d, 0xf, 0x1, 0x1, 0xff, 0x4, 0x4, 0x3, 0x2, 0x7, 0x80, 0x30, 0x20, 0x6, 0x3, 0x55, 0x1d,
1577        0x25, 0x1, 0x1, 0xff, 0x4, 0x16, 0x30, 0x14, 0x6, 0x8, 0x2b, 0x6, 0x1, 0x5, 0x5, 0x7, 0x3,
1578        0x2, 0x6, 0x8, 0x2b, 0x6, 0x1, 0x5, 0x5, 0x7, 0x3, 0x1, 0x30, 0x1d, 0x6, 0x3, 0x55, 0x1d,
1579        0xe, 0x4, 0x16, 0x4, 0x14, 0xbd, 0xfd, 0x11, 0xac, 0x89, 0xb6, 0xe0, 0x90, 0x7a, 0xf6,
1580        0x12, 0x61, 0x78, 0x4d, 0x3d, 0x79, 0x56, 0xeb, 0xc2, 0xdc, 0x30, 0x1f, 0x6, 0x3, 0x55,
1581        0x1d, 0x23, 0x4, 0x18, 0x30, 0x16, 0x80, 0x14, 0xce, 0x60, 0xb4, 0x28, 0x96, 0x72, 0x27,
1582        0x64, 0x81, 0xbc, 0x4f, 0x0, 0x78, 0xa3, 0x30, 0x48, 0xfe, 0x6e, 0x65, 0x86,
1583    ];
1584
1585    const MSG1_FAIL: &[u8] = &[
1586        0x30, 0x82, 0x1, 0xa1, 0xa0, 0x3, 0x2, 0x1, 0x2, 0x2, 0x1, 0x1, 0x30, 0xa, 0x6, 0x8, 0x2a,
1587        0x86, 0x48, 0xce, 0x3d, 0x4, 0x3, 0x2, 0x30, 0x44, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b,
1588        0x6, 0x1, 0x4, 0x1, 0x82, 0xa2, 0x7c, 0x1, 0x3, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30,
1589        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x31, 0x20, 0x30, 0x1e,
1590        0x6, 0xa, 0x2b, 0x6, 0x1, 0x4, 0x1, 0x82, 0xa2, 0x7c, 0x1, 0x5, 0xc, 0x10, 0x30, 0x30,
1591        0x30, 0x31, 0x32, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30,
1592        0x1e, 0x17, 0xd, 0x32, 0x31, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1593        0x5a, 0x17, 0xd, 0x33, 0x30, 0x31, 0x32, 0x33, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1594        0x5a, 0x30, 0x44, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b, 0x6, 0x1, 0x4, 0x1, 0x82, 0xa2,
1595        0x7c, 0x1, 0x1, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1596        0x42, 0x43, 0x35, 0x43, 0x30, 0x32, 0x31, 0x20, 0x30, 0x1e, 0x6, 0xa, 0x2b, 0x6, 0x1, 0x4,
1597        0x1, 0x82, 0xa2, 0x7c, 0x1, 0x5, 0xc, 0x10, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
1598        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30, 0x13, 0x6, 0x7, 0x2a,
1599        0x86, 0x48, 0xce, 0x3d, 0x2, 0x1, 0x6, 0x8, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x3, 0x1, 0x7,
1600        0x3, 0x42, 0x0, 0x4, 0x6, 0x47, 0xf2, 0x86, 0x4d, 0x27, 0x25, 0xdc, 0x1, 0xa, 0x87, 0xde,
1601        0x8d, 0xca, 0x88, 0x37, 0xcb, 0x3b, 0xd0, 0xea, 0x93, 0xa6, 0x24, 0x65, 0x8, 0x8f, 0xa1,
1602        0x75, 0xc2, 0xd4, 0x41, 0xfa, 0xca, 0x96, 0x54, 0xa3, 0xd8, 0x10, 0x85, 0x73, 0xce, 0x15,
1603        0xa5, 0x38, 0xc1, 0xe3, 0xb5, 0x6b, 0x61, 0x1, 0xd3, 0xc4, 0xb7, 0x6b, 0x61, 0x16, 0xc3,
1604        0x77, 0x8d, 0xe9, 0xb5, 0x44, 0xac, 0x14, 0xa3, 0x81, 0x83, 0x30, 0x81, 0x80, 0x30, 0xc,
1605        0x6, 0x3, 0x55, 0x1d, 0x13, 0x1, 0x1, 0xff, 0x4, 0x2, 0x30, 0x0, 0x30, 0xe, 0x6, 0x3, 0x55,
1606        0x1d, 0xf, 0x1, 0x1, 0xff, 0x4, 0x4, 0x3, 0x2, 0x7, 0x80, 0x30, 0x20, 0x6, 0x3, 0x55, 0x1d,
1607        0x25, 0x1, 0x1, 0xff, 0x4, 0x16, 0x30, 0x14, 0x6, 0x8, 0x2b, 0x6, 0x1, 0x5, 0x5, 0x7, 0x3,
1608        0x2, 0x6, 0x8, 0x2b, 0x6, 0x1, 0x5, 0x5, 0x7, 0x3, 0x1, 0x30, 0x1d, 0x6, 0x3, 0x55, 0x1d,
1609        0xe, 0x4, 0x16, 0x4, 0x14, 0xbd, 0xfd, 0x11, 0xac, 0x89, 0xb6, 0xe0, 0x90, 0x7a, 0xf6,
1610        0x12, 0x61, 0x78, 0x4d, 0x3d, 0x79, 0x56, 0xeb, 0xc2, 0xdc, 0x30, 0x1f, 0x6, 0x3, 0x55,
1611        0x1d, 0x23, 0x4, 0x18, 0x30, 0x16, 0x80, 0x14, 0xce, 0x60, 0xb4, 0x28, 0x96, 0x72, 0x27,
1612        0x64, 0x81, 0xbc, 0x4f, 0x0, 0x78, 0xa3, 0x30, 0x48, 0xfe, 0x6e, 0x65, 0x86,
1613    ];
1614
1615    const SIGNATURE1: CanonPkcSignatureRef = CanonPkcSignatureRef::new(&[
1616        0x20, 0x16, 0xd0, 0x13, 0x1e, 0xd0, 0xb3, 0x9d, 0x44, 0x25, 0x16, 0xea, 0x9c, 0xf2, 0x72,
1617        0x44, 0xd7, 0xb0, 0xf4, 0xae, 0x4a, 0xa4, 0x37, 0x32, 0xcd, 0x6a, 0x79, 0x7a, 0x4c, 0x48,
1618        0x3, 0x6d, 0xef, 0xe6, 0x26, 0x82, 0x39, 0x28, 0x9, 0x22, 0xc8, 0x9a, 0xde, 0xd5, 0x13,
1619        0x9f, 0xc5, 0x40, 0x25, 0x85, 0x2c, 0x69, 0xe0, 0xdb, 0x6a, 0x79, 0x5b, 0x21, 0x82, 0x13,
1620        0xb0, 0x20, 0xb9, 0x69,
1621    ]);
1622}