Skip to main content

at_cryptoauth/client/
verifying.rs

1//! ECDSA signature verification operations
2
3use core::future::Future;
4
5use crate::command::PublicKey;
6use crate::error::Error;
7use crate::memory::Slot;
8use crate::{Digest, Signature};
9use embassy_sync::blocking_mutex::raw::RawMutex;
10
11use super::AtCaClient;
12
13pub struct VerifyingKey<'a, M: RawMutex, PHY> {
14    pub(crate) atca: &'a AtCaClient<M, PHY>,
15    pub(crate) key_id: Slot,
16}
17
18impl<'a, M, PHY> VerifyingKey<'a, M, PHY>
19where
20    PHY: embedded_hal_async::i2c::I2c,
21    M: RawMutex,
22{
23    /// Takes a 32-byte digest (typically the SHA256 hash of the full message)
24    /// and verifies it against the provided signature and public key.
25    pub fn verify_digest(
26        &self,
27        digest: &Digest,
28        signature: &Signature,
29        public_key: &PublicKey,
30    ) -> impl Future<Output = Result<(), Error>> {
31        self.atca.verify_external(digest, signature, public_key)
32    }
33
34    pub async fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), Error> {
35        let digest = self.atca.sha().digest(msg).await?;
36        let public_key = if self.key_id.is_certificate() {
37            self.atca.memory().pubkey(self.key_id).await?
38        } else {
39            self.atca.generate_pubkey(self.key_id).await?
40        };
41        self.verify_digest(&digest, signature, &public_key).await
42    }
43}
44
45impl<'a, M, PHY> VerifyingKey<'a, M, PHY>
46where
47    PHY: embedded_hal::i2c::I2c,
48    M: RawMutex,
49{
50    /// Takes a 32-byte digest (typically the SHA256 hash of the full message)
51    /// and verifies it against the provided signature and public key.
52    pub fn verify_digest_blocking(
53        &self,
54        digest: &Digest,
55        signature: &Signature,
56        public_key: &PublicKey,
57    ) -> Result<(), Error> {
58        self.atca
59            .verify_external_blocking(digest, signature, public_key)
60    }
61
62    pub fn verify_blocking(&self, msg: &[u8], signature: &Signature) -> Result<(), Error> {
63        let digest = self.atca.sha().digest_blocking(msg)?;
64        let public_key = if self.key_id.is_certificate() {
65            self.atca.memory().pubkey_blocking(self.key_id)?
66        } else {
67            self.atca.generate_pubkey_blocking(self.key_id)?
68        };
69        self.verify_digest_blocking(&digest, signature, &public_key)
70    }
71}
72
73impl<'a, M, PHY> signature::Verifier<Signature> for VerifyingKey<'a, M, PHY>
74where
75    PHY: embedded_hal::i2c::I2c,
76    M: RawMutex,
77{
78    fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
79        self.verify_blocking(msg, signature)
80            .map_err(|_| signature::Error::new())
81    }
82}