Skip to main content

at_cryptoauth/client/
aes.rs

1//! AES encryption/decryption operations
2
3use crate::command;
4use crate::error::{Error, ErrorKind};
5use crate::memory::Slot;
6use embassy_sync::blocking_mutex::raw::RawMutex;
7
8use super::AtCaClient;
9
10pub struct Aes<'a, M: RawMutex, PHY> {
11    pub(crate) atca: &'a AtCaClient<M, PHY>,
12    pub(crate) key_id: Slot,
13}
14
15impl<'a, M, PHY> Aes<'a, M, PHY>
16where
17    PHY: embedded_hal_async::i2c::I2c,
18    M: RawMutex,
19{
20    pub async fn encrypt(&mut self, plaintext: &[u8], ciphertext: &mut [u8]) -> Result<(), Error> {
21        use command::Aes as AesCmd;
22
23        if plaintext.len() != ciphertext.len() {
24            return Err(ErrorKind::BadParam.into());
25        }
26
27        for (plain, cipher) in plaintext
28            .chunks(AesCmd::DATA_SIZE)
29            .zip(ciphertext.chunks_mut(AesCmd::DATA_SIZE))
30        {
31            let mut inner = self.atca.inner.lock().await;
32
33            // Input length should be exactly 16 bytes. Otherwise the device
34            // couldn't recognize the command properly. If the length is not
35            // enough, sufficient number of 0s are padded.
36            let packet = AesCmd::new(inner.packet_builder()).encrypt(self.key_id, plain)?;
37
38            // Encrypt plain bytes and write the result to cipher.
39            let response = inner.execute(packet).await?;
40            if response.as_ref().len() != AesCmd::DATA_SIZE {
41                return Err(ErrorKind::InvalidSize.into());
42            }
43            cipher.copy_from_slice(response.as_ref());
44        }
45        Ok(())
46    }
47
48    pub async fn decrypt(&mut self, ciphertext: &[u8], plaintext: &mut [u8]) -> Result<(), Error> {
49        use command::Aes as AesCmd;
50
51        if ciphertext.len() != plaintext.len() {
52            return Err(ErrorKind::BadParam.into());
53        }
54
55        for (cipher, plain) in ciphertext
56            .chunks(AesCmd::DATA_SIZE)
57            .zip(plaintext.chunks_mut(AesCmd::DATA_SIZE))
58        {
59            let mut inner = self.atca.inner.lock().await;
60
61            // Input length should be exactly 16 bytes. Otherwise the device
62            // couldn't recognize the command properly. If the length is not
63            // enough, sufficient number of 0s are padded.
64            let packet = AesCmd::new(inner.packet_builder()).decrypt(self.key_id, cipher)?;
65
66            // Decrypt cipher bytes and write the result to plain.
67            let response = inner.execute(packet).await?;
68            if response.as_ref().len() != AesCmd::DATA_SIZE {
69                return Err(ErrorKind::InvalidSize.into());
70            }
71            plain.copy_from_slice(response.as_ref());
72        }
73        Ok(())
74    }
75}
76
77impl<'a, M, PHY> Aes<'a, M, PHY>
78where
79    PHY: embedded_hal::i2c::I2c,
80    M: RawMutex,
81{
82    pub fn encrypt_blocking(
83        &mut self,
84        plaintext: &[u8],
85        ciphertext: &mut [u8],
86    ) -> Result<(), Error> {
87        use command::Aes as AesCmd;
88
89        let mut inner = self
90            .atca
91            .inner
92            .try_lock()
93            .map_err(|_| ErrorKind::MutexLocked)?;
94
95        if plaintext.len() != ciphertext.len() {
96            return Err(ErrorKind::BadParam.into());
97        }
98
99        for (plain, cipher) in plaintext
100            .chunks(AesCmd::DATA_SIZE)
101            .zip(ciphertext.chunks_mut(AesCmd::DATA_SIZE))
102        {
103            // Input length should be exactly 16 bytes. Otherwise the device
104            // couldn't recognize the command properly. If the length is not
105            // enough, sufficient number of 0s are padded.
106            let packet = AesCmd::new(inner.packet_builder()).encrypt(self.key_id, plain)?;
107
108            // Encrypt plain bytes and write the result to cipher.
109            let response = inner.execute_blocking(packet)?;
110            if response.as_ref().len() != AesCmd::DATA_SIZE {
111                return Err(ErrorKind::InvalidSize.into());
112            }
113            cipher.copy_from_slice(response.as_ref());
114        }
115        Ok(())
116    }
117
118    pub fn decrypt_blocking(
119        &mut self,
120        ciphertext: &[u8],
121        plaintext: &mut [u8],
122    ) -> Result<(), Error> {
123        use command::Aes as AesCmd;
124
125        let mut inner = self
126            .atca
127            .inner
128            .try_lock()
129            .map_err(|_| ErrorKind::MutexLocked)?;
130
131        if ciphertext.len() != plaintext.len() {
132            return Err(ErrorKind::BadParam.into());
133        }
134
135        for (cipher, plain) in ciphertext
136            .chunks(AesCmd::DATA_SIZE)
137            .zip(plaintext.chunks_mut(AesCmd::DATA_SIZE))
138        {
139            // Input length should be exactly 16 bytes. Otherwise the device
140            // couldn't recognize the command properly. If the length is not
141            // enough, sufficient number of 0s are padded.
142            let packet = AesCmd::new(inner.packet_builder()).decrypt(self.key_id, cipher)?;
143
144            // Decrypt cipher bytes and write the result to plain.
145            let response = inner.execute_blocking(packet)?;
146            if response.as_ref().len() != AesCmd::DATA_SIZE {
147                return Err(ErrorKind::InvalidSize.into());
148            }
149            plain.copy_from_slice(response.as_ref());
150        }
151        Ok(())
152    }
153}