Skip to main content

at_cryptoauth/client/
mod.rs

1//! Client module for ATECC608 communication.
2//!
3//! The [`AtCaClient`] is the main entry point for interacting with ATECC608 devices.
4//! It provides methods for cryptographic operations, key management, and device control.
5//!
6//! ## Sub-modules
7//!
8//! Specialized operations are organized into sub-modules accessible via client methods:
9//!
10//! - [`Aes`]: AES-128 encryption and decryption via [`AtCaClient::aes`]
11//! - [`Sha`]: SHA-256 hashing via [`AtCaClient::sha`]
12//! - [`SigningKey`]: ECDSA signing via [`AtCaClient::signer`]
13//! - [`VerifyingKey`]: ECDSA verification via [`AtCaClient::verifier`]
14//! - [`Memory`]: Device memory read/write/lock via [`AtCaClient::memory`]
15//! - [`Random`]: Cryptographic random number generation via [`AtCaClient::random`]
16//!
17//! ## Async vs Blocking
18//!
19//! All operations have both async and blocking variants. Async methods require
20//! `embedded_hal_async::i2c::I2c`, while blocking methods require `embedded_hal::i2c::I2c`.
21//! Blocking methods have a `_blocking` suffix (e.g., `sign` vs `sign_blocking`).
22
23mod aes;
24mod memory;
25mod random;
26mod sha;
27mod signing;
28mod verifying;
29
30pub use aes::Aes;
31pub use memory::Memory;
32pub use random::Random;
33pub use sha::Sha;
34pub use signing::SigningKey;
35pub use verifying::VerifyingKey;
36
37use core::future::Future;
38
39use crate::clock_divider::ClockDivider;
40use crate::command::{
41    self, Ecdh, GenKey, Info, NonceCtx, PrivWrite, PublicKey, SharedSecret, Word,
42};
43use crate::datalink::{I2c, I2cConfig};
44use crate::error::{Error, ErrorKind};
45use crate::memory::{Slot, Zone};
46use crate::packet::{Packet, PacketBuilder, Response};
47use crate::tngtls::TrustAndGo;
48use crate::{Block, Digest};
49use embassy_sync::blocking_mutex::raw::RawMutex;
50use embassy_sync::mutex::Mutex;
51use heapless::Vec;
52
53pub(crate) struct Inner<PHY> {
54    pub i2c: I2c<PHY>,
55    pub buffer: Vec<u8, 192>,
56    pub clock_divider: ClockDivider,
57}
58
59impl<PHY> Inner<PHY> {
60    pub(crate) fn packet_builder(&mut self) -> PacketBuilder<'_> {
61        let capacity = self.buffer.capacity();
62        self.buffer.clear();
63        self.buffer
64            .resize(capacity, 0x00u8)
65            .unwrap_or_else(|_| unreachable!("Input length equals to the current capacity."));
66        PacketBuilder::new(&mut self.buffer)
67    }
68}
69
70impl<PHY> Inner<PHY>
71where
72    PHY: embedded_hal_async::i2c::I2c,
73{
74    pub(crate) fn execute(
75        &mut self,
76        packet: Packet,
77    ) -> impl Future<Output = Result<Response<'_>, Error>> {
78        let exec_time = self.clock_divider.execution_time(packet.opcode());
79        self.i2c.execute(&mut self.buffer, packet, exec_time)
80    }
81}
82
83impl<PHY> Inner<PHY>
84where
85    PHY: embedded_hal::i2c::I2c,
86{
87    pub(crate) fn execute_blocking(&mut self, packet: Packet) -> Result<Response<'_>, Error> {
88        let exec_time = self.clock_divider.execution_time(packet.opcode());
89        self.i2c
90            .execute_blocking(&mut self.buffer, packet, exec_time)
91    }
92}
93
94pub struct AtCaClient<M: RawMutex, PHY> {
95    pub(crate) inner: Mutex<M, Inner<PHY>>,
96}
97
98impl<M: RawMutex, PHY> AtCaClient<M, PHY> {
99    /// Create a new client with default I2C configuration
100    pub fn new(phy: PHY) -> Self {
101        Self::with_config(phy, I2cConfig::default())
102    }
103
104    /// Create a new client with custom I2C configuration
105    pub fn with_config(phy: PHY, config: I2cConfig) -> Self {
106        let i2c = I2c::with_config(phy, config);
107        let buffer = Vec::new();
108
109        Self {
110            inner: Mutex::new(Inner {
111                i2c,
112                buffer,
113                clock_divider: ClockDivider::Zero,
114            }),
115        }
116    }
117
118    pub fn memory(&self) -> Memory<'_, M, PHY> {
119        Memory { atca: self }
120    }
121
122    pub fn aes(&self, key_id: Slot) -> Aes<'_, M, PHY> {
123        Aes { atca: self, key_id }
124    }
125
126    pub fn sha(&self) -> Sha<'_, M, PHY> {
127        let remaining_bytes = Vec::new();
128        Sha {
129            atca: self,
130            remaining_bytes,
131        }
132    }
133
134    pub fn signer(&self, key_id: Slot) -> SigningKey<'_, M, PHY> {
135        SigningKey { atca: self, key_id }
136    }
137
138    pub fn verifier(&self, key_id: Slot) -> VerifyingKey<'_, M, PHY> {
139        VerifyingKey { atca: self, key_id }
140    }
141
142    pub fn random(&self) -> Random<'_, M, PHY> {
143        Random::new(self)
144    }
145}
146
147impl<M, PHY> AtCaClient<M, PHY>
148where
149    PHY: embedded_hal_async::i2c::I2c,
150    M: RawMutex,
151{
152    pub async fn tng(&self) -> Result<TrustAndGo<'_, M, PHY>, Error> {
153        let mut tng = TrustAndGo { atca: self };
154        // Check if configuration zone is locked.
155        if !tng.atca.memory().is_locked(Zone::Config).await? {
156            tng.configure_permissions().await?;
157            tng.configure_chip_options().await?;
158            tng.configure_key_types().await?;
159            // Lock config zone
160            tng.atca.memory().lock(Zone::Config).await?;
161        }
162
163        // Check if data zone is locked.
164        if !tng.atca.memory().is_locked(Zone::Data).await? {
165            // Only lock the data zone for release build
166            #[cfg(not(debug_assertions))]
167            tng.atca.memory().lock(Zone::Data).await?;
168        }
169
170        Ok(tng)
171    }
172
173    pub async fn sleep(&self) -> Result<(), Error> {
174        self.inner.lock().await.i2c.sleep().await
175    }
176
177    pub async fn info(&self) -> Result<Word, Error> {
178        let mut inner = self.inner.lock().await;
179        let packet = Info::new(inner.packet_builder()).revision()?;
180        inner.execute(packet).await?.as_ref().try_into()
181    }
182
183    /// Issue a Random command to update the ATECC's internal RNG seed, discarding the output.
184    pub(crate) async fn update_seed(&self) -> Result<(), Error> {
185        let mut inner = self.inner.lock().await;
186        let packet = command::Random::new(inner.packet_builder()).random()?;
187        inner.execute(packet).await.map(drop)
188    }
189
190    /// Write to device's digest message buffer
191    pub async fn write_message_digest_buffer(&self, msg: &Digest) -> Result<(), Error> {
192        let mut inner = self.inner.lock().await;
193        let packet = NonceCtx::new(inner.packet_builder()).message_digest_buffer(msg)?;
194        inner.execute(packet).await.map(drop)
195    }
196
197    /// Create private key and output its public key
198    pub async fn create_private_key(&self, key_id: Slot) -> Result<PublicKey, Error> {
199        let mut inner = self.inner.lock().await;
200        let packet = GenKey::new(inner.packet_builder()).private_key(key_id)?;
201        inner.execute(packet).await?.as_ref().try_into()
202    }
203
204    /// Write private key to device
205    pub async fn write_private_key(&self, key_id: Slot, private_key: &Block) -> Result<(), Error> {
206        let mut inner = self.inner.lock().await;
207        let packet =
208            PrivWrite::new(inner.packet_builder()).write_private_key(key_id, private_key)?;
209        inner.execute(packet).await.map(drop)
210    }
211
212    /// Given a private key created and stored in advance, calculate its public key
213    pub async fn generate_pubkey(&self, key_id: Slot) -> Result<PublicKey, Error> {
214        let mut inner = self.inner.lock().await;
215        let packet = GenKey::new(inner.packet_builder()).public_key(key_id)?;
216        inner.execute(packet).await?.as_ref().try_into()
217    }
218
219    /// Perform Diffie-Hellman key exchange
220    pub async fn diffie_hellman(
221        &self,
222        key_id: Slot,
223        public_key: PublicKey,
224    ) -> Result<SharedSecret, Error> {
225        let mut inner = self.inner.lock().await;
226        let packet = Ecdh::new(inner.packet_builder()).diffie_hellman(key_id, public_key)?;
227        inner.execute(packet).await?.as_ref().try_into()
228    }
229
230    /// Verify a signature over a pre-hashed digest using an external public key.
231    ///
232    /// Atomically writes the digest to the message buffer and executes the
233    /// Verify command under a single lock acquisition.
234    pub async fn verify_external(
235        &self,
236        digest: &Digest,
237        signature: &p256::ecdsa::Signature,
238        public_key: &PublicKey,
239    ) -> Result<(), Error> {
240        let mut inner = self.inner.lock().await;
241
242        let packet = NonceCtx::new(inner.packet_builder()).message_digest_buffer(digest)?;
243        inner.execute(packet).await?;
244
245        let packet =
246            command::Verify::new(inner.packet_builder()).external(signature, public_key)?;
247        inner.execute(packet).await?;
248
249        Ok(())
250    }
251}
252
253impl<M, PHY> AtCaClient<M, PHY>
254where
255    PHY: embedded_hal::i2c::I2c,
256    M: RawMutex,
257{
258    pub fn sleep_blocking(&self) -> Result<(), Error> {
259        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
260        inner.i2c.sleep_blocking()
261    }
262
263    pub fn info_blocking(&self) -> Result<Word, Error> {
264        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
265        let packet = Info::new(inner.packet_builder()).revision()?;
266        inner.execute_blocking(packet)?.as_ref().try_into()
267    }
268
269    /// Issue a Random command to update the ATECC's internal RNG seed, discarding the output.
270    pub(crate) fn update_seed_blocking(&self) -> Result<(), Error> {
271        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
272        let packet = command::Random::new(inner.packet_builder()).random()?;
273        inner.execute_blocking(packet).map(drop)
274    }
275
276    /// Write to device's digest message buffer
277    pub fn write_message_digest_buffer_blocking(&self, msg: &Digest) -> Result<(), Error> {
278        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
279        let packet = NonceCtx::new(inner.packet_builder()).message_digest_buffer(msg)?;
280        inner.execute_blocking(packet).map(drop)
281    }
282
283    /// Create private key and output its public key
284    pub fn create_private_key_blocking(&self, key_id: Slot) -> Result<PublicKey, Error> {
285        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
286        let packet = GenKey::new(inner.packet_builder()).private_key(key_id)?;
287        inner.execute_blocking(packet)?.as_ref().try_into()
288    }
289
290    /// Write private key to device
291    pub fn write_private_key_blocking(
292        &self,
293        key_id: Slot,
294        private_key: &Block,
295    ) -> Result<(), Error> {
296        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
297        let packet =
298            PrivWrite::new(inner.packet_builder()).write_private_key(key_id, private_key)?;
299        inner.execute_blocking(packet).map(drop)
300    }
301
302    /// Given a private key created and stored in advance, calculate its public key
303    pub fn generate_pubkey_blocking(&self, key_id: Slot) -> Result<PublicKey, Error> {
304        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
305        let packet = GenKey::new(inner.packet_builder()).public_key(key_id)?;
306        inner.execute_blocking(packet)?.as_ref().try_into()
307    }
308
309    /// Perform Diffie-Hellman key exchange
310    pub fn diffie_hellman_blocking(
311        &self,
312        key_id: Slot,
313        public_key: PublicKey,
314    ) -> Result<SharedSecret, Error> {
315        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
316        let packet = Ecdh::new(inner.packet_builder()).diffie_hellman(key_id, public_key)?;
317        inner.execute_blocking(packet)?.as_ref().try_into()
318    }
319
320    /// Verify a signature over a pre-hashed digest using an external public key.
321    ///
322    /// Atomically writes the digest to the message buffer and executes the
323    /// Verify command under a single lock acquisition.
324    pub fn verify_external_blocking(
325        &self,
326        digest: &Digest,
327        signature: &p256::ecdsa::Signature,
328        public_key: &PublicKey,
329    ) -> Result<(), Error> {
330        let mut inner = self.inner.try_lock().map_err(|_| ErrorKind::MutexLocked)?;
331
332        let packet = NonceCtx::new(inner.packet_builder()).message_digest_buffer(digest)?;
333        inner.execute_blocking(packet)?;
334
335        let packet =
336            command::Verify::new(inner.packet_builder()).external(signature, public_key)?;
337        inner.execute_blocking(packet)?;
338
339        Ok(())
340    }
341}