at-cryptoauth 0.6.0

Driver for ATECC608 Crypto Authentication secure elements
Documentation
//! ECDSA signature verification operations

use core::future::Future;

use crate::command::PublicKey;
use crate::error::Error;
use crate::memory::Slot;
use crate::{Digest, Signature};
use embassy_sync::blocking_mutex::raw::RawMutex;

use super::AtCaClient;

pub struct VerifyingKey<'a, M: RawMutex, PHY> {
    pub(crate) atca: &'a AtCaClient<M, PHY>,
    pub(crate) key_id: Slot,
}

impl<'a, M, PHY> VerifyingKey<'a, M, PHY>
where
    PHY: embedded_hal_async::i2c::I2c,
    M: RawMutex,
{
    /// Takes a 32-byte digest (typically the SHA256 hash of the full message)
    /// and verifies it against the provided signature and public key.
    pub fn verify_digest(
        &self,
        digest: &Digest,
        signature: &Signature,
        public_key: &PublicKey,
    ) -> impl Future<Output = Result<(), Error>> {
        self.atca.verify_external(digest, signature, public_key)
    }

    pub async fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), Error> {
        let digest = self.atca.sha().digest(msg).await?;
        let public_key = if self.key_id.is_certificate() {
            self.atca.memory().pubkey(self.key_id).await?
        } else {
            self.atca.generate_pubkey(self.key_id).await?
        };
        self.verify_digest(&digest, signature, &public_key).await
    }
}

impl<'a, M, PHY> VerifyingKey<'a, M, PHY>
where
    PHY: embedded_hal::i2c::I2c,
    M: RawMutex,
{
    /// Takes a 32-byte digest (typically the SHA256 hash of the full message)
    /// and verifies it against the provided signature and public key.
    pub fn verify_digest_blocking(
        &self,
        digest: &Digest,
        signature: &Signature,
        public_key: &PublicKey,
    ) -> Result<(), Error> {
        self.atca
            .verify_external_blocking(digest, signature, public_key)
    }

    pub fn verify_blocking(&self, msg: &[u8], signature: &Signature) -> Result<(), Error> {
        let digest = self.atca.sha().digest_blocking(msg)?;
        let public_key = if self.key_id.is_certificate() {
            self.atca.memory().pubkey_blocking(self.key_id)?
        } else {
            self.atca.generate_pubkey_blocking(self.key_id)?
        };
        self.verify_digest_blocking(&digest, signature, &public_key)
    }
}

impl<'a, M, PHY> signature::Verifier<Signature> for VerifyingKey<'a, M, PHY>
where
    PHY: embedded_hal::i2c::I2c,
    M: RawMutex,
{
    fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
        self.verify_blocking(msg, signature)
            .map_err(|_| signature::Error::new())
    }
}