Skip to main content

at_cryptoauth/
command.rs

1// Command definitions
2// Overall structure is modeled after https://github.com/tokio-rs/mini-redis/blob/master/src/cmd/mod.rs
3use super::error::{Error, ErrorKind};
4use super::memory::{Size, Slot, Zone};
5use super::packet::{Packet, PacketBuilder};
6use core::convert::TryFrom;
7use signature::digest::generic_array::GenericArray;
8use signature::digest::generic_array::typenum::{U4, U9, U32, U64};
9
10// Encapsulates raw 4 bytes. When it is a return value of `info`, it contains
11// the device's revision number.
12#[derive(Clone, Copy, Debug, Default)]
13pub struct Word {
14    value: GenericArray<u8, U4>,
15}
16
17impl TryFrom<&[u8]> for Word {
18    type Error = Error;
19    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
20        if buffer.len() != Size::Word.len() {
21            return Err(ErrorKind::BadParam.into());
22        }
23
24        let mut value = Self::default();
25        value.as_mut().copy_from_slice(buffer);
26        Ok(value)
27    }
28}
29
30impl AsRef<[u8]> for Word {
31    fn as_ref(&self) -> &[u8] {
32        self.value.as_ref()
33    }
34}
35
36impl AsMut<[u8]> for Word {
37    fn as_mut(&mut self) -> &mut [u8] {
38        self.value.as_mut()
39    }
40}
41
42// Encapsulates raw 32 bytes.
43#[derive(Clone, Copy, Debug, Default)]
44pub struct Block {
45    value: GenericArray<u8, U32>,
46}
47
48impl TryFrom<&[u8]> for Block {
49    type Error = Error;
50    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
51        if buffer.len() != Size::Block.len() {
52            return Err(ErrorKind::BadParam.into());
53        }
54
55        let mut value = Self::default();
56        value.as_mut().copy_from_slice(buffer);
57        Ok(value)
58    }
59}
60
61impl AsRef<[u8]> for Block {
62    fn as_ref(&self) -> &[u8] {
63        self.value.as_ref()
64    }
65}
66
67impl AsMut<[u8]> for Block {
68    fn as_mut(&mut self) -> &mut [u8] {
69        self.value.as_mut()
70    }
71}
72
73// Represents a serial number consisting of 9 bytes. Its uniqueness is
74// guaranteed. A return type of API `read_serial`.
75#[derive(Clone, Copy, Debug, Default)]
76pub struct Serial {
77    value: GenericArray<u8, U9>,
78}
79
80impl TryFrom<&[u8]> for Serial {
81    type Error = Error;
82    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
83        if buffer.len() != Size::Block.len() {
84            return Err(ErrorKind::BadParam.into());
85        }
86
87        let mut value = [0x00; 9];
88        value[0..4].as_mut().copy_from_slice(&buffer[0..4]);
89        value[4..9].as_mut().copy_from_slice(&buffer[8..13]);
90        Ok(Self {
91            value: value.into(),
92        })
93    }
94}
95
96impl Serial {
97    /// Create a Serial from a 9-byte array (for testing purposes)
98    #[cfg(test)]
99    pub fn new_for_test(bytes: &[u8; 9]) -> Self {
100        Self {
101            value: (*bytes).into(),
102        }
103    }
104}
105
106impl AsRef<[u8]> for Serial {
107    fn as_ref(&self) -> &[u8] {
108        self.value.as_ref()
109    }
110}
111
112impl AsMut<[u8]> for Serial {
113    fn as_mut(&mut self) -> &mut [u8] {
114        self.value.as_mut()
115    }
116}
117
118#[derive(Clone, Copy, Debug, Default)]
119pub struct PublicKey {
120    pub(crate) value: GenericArray<u8, U64>,
121}
122
123impl AsRef<[u8]> for PublicKey {
124    fn as_ref(&self) -> &[u8] {
125        self.value.as_ref()
126    }
127}
128
129impl AsMut<[u8]> for PublicKey {
130    fn as_mut(&mut self) -> &mut [u8] {
131        self.value.as_mut()
132    }
133}
134
135impl TryFrom<&[u8]> for PublicKey {
136    type Error = Error;
137    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
138        if buffer.len() != 0x40 {
139            return Err(ErrorKind::BadParam.into());
140        }
141
142        let mut value = Self::default();
143        value.as_mut().copy_from_slice(buffer);
144        Ok(value)
145    }
146}
147
148#[derive(Clone, Copy, Debug, Default)]
149pub struct SharedSecret {
150    value: GenericArray<u8, U32>,
151}
152
153impl AsRef<[u8]> for SharedSecret {
154    fn as_ref(&self) -> &[u8] {
155        self.value.as_ref()
156    }
157}
158
159impl AsMut<[u8]> for SharedSecret {
160    fn as_mut(&mut self) -> &mut [u8] {
161        self.value.as_mut()
162    }
163}
164
165impl TryFrom<&[u8]> for SharedSecret {
166    type Error = Error;
167    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
168        if buffer.len() != 32 {
169            return Err(ErrorKind::BadParam.into());
170        }
171
172        let mut value = Self::default();
173        value.as_mut().copy_from_slice(buffer);
174        Ok(value)
175    }
176}
177
178// A digest yielded from cryptographic hash functions. Merely a wrapper around
179// `GenericArray<u8, 32>` of `digest` crate.
180#[derive(Clone, Copy, Debug, Default)]
181pub struct Digest {
182    pub(crate) value: GenericArray<u8, U32>,
183}
184
185impl TryFrom<&[u8]> for Digest {
186    type Error = Error;
187    fn try_from(buffer: &[u8]) -> Result<Self, Self::Error> {
188        if buffer.len() != 32 {
189            return Err(ErrorKind::BadParam.into());
190        }
191
192        let mut value = Self::default();
193        value.as_mut().copy_from_slice(buffer);
194        Ok(value)
195    }
196}
197
198impl AsRef<[u8]> for Digest {
199    fn as_ref(&self) -> &[u8] {
200        self.value.as_ref()
201    }
202}
203
204impl AsMut<[u8]> for Digest {
205    fn as_mut(&mut self) -> &mut [u8] {
206        self.value.as_mut()
207    }
208}
209
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub(crate) enum OpCode {
212    /// CheckMac command op-code
213    #[allow(dead_code)]
214    CheckMac = 0x28,
215    /// DeriveKey command op-code
216    #[allow(dead_code)]
217    DeriveKey = 0x1C,
218    /// Info command op-code
219    Info = 0x30,
220    /// GenDig command op-code
221    GenDig = 0x15,
222    /// GenKey command op-code
223    GenKey = 0x40,
224    /// HMAC command op-code
225    #[allow(dead_code)]
226    HMac = 0x11,
227    /// Lock command op-code
228    Lock = 0x17,
229    /// MAC command op-code
230    #[allow(dead_code)]
231    Mac = 0x08,
232    /// Nonce command op-code
233    Nonce = 0x16,
234    /// Pause command op-code
235    #[allow(dead_code)]
236    Pause = 0x01,
237    /// PrivWrite command op-code
238    PrivWrite = 0x46,
239    /// Random command op-code
240    Random = 0x1B,
241    /// Read command op-code
242    Read = 0x02,
243    /// Sign command op-code
244    Sign = 0x41,
245    /// UpdateExtra command op-code
246    #[allow(dead_code)]
247    UpdateExtra = 0x20,
248    /// Verify command op-code
249    Verify = 0x45,
250    /// Write command op-code
251    Write = 0x12,
252    /// ECDH command op-code
253    #[allow(dead_code)]
254    Ecdh = 0x43,
255    /// Counter command op-code
256    #[allow(dead_code)]
257    Counter = 0x24,
258    /// SHA command op-code
259    Sha = 0x47,
260    /// AES command op-code
261    Aes = 0x51,
262    /// KDF command op-code
263    #[allow(dead_code)]
264    Kdf = 0x56,
265    /// Secure Boot command op-code
266    #[allow(dead_code)]
267    SecureBoot = 0x80,
268    /// Self test command op-code
269    #[allow(dead_code)]
270    SelfTest = 0x77,
271}
272
273#[allow(dead_code)]
274pub(crate) struct CheckMac<'a>(PacketBuilder<'a>);
275#[allow(dead_code)]
276pub(crate) struct Counter<'a>(PacketBuilder<'a>);
277#[allow(dead_code)]
278pub(crate) struct DeriveKey<'a>(PacketBuilder<'a>);
279#[allow(dead_code)]
280pub(crate) struct Ecdh<'a>(PacketBuilder<'a>);
281pub(crate) struct GenDig<'a>(PacketBuilder<'a>);
282pub(crate) struct GenKey<'a>(PacketBuilder<'a>);
283#[allow(dead_code)]
284pub(crate) struct HMac<'a>(PacketBuilder<'a>);
285pub(crate) struct Info<'a>(PacketBuilder<'a>);
286pub(crate) struct Lock<'a>(PacketBuilder<'a>);
287#[allow(dead_code)]
288pub(crate) struct Mac<'a>(PacketBuilder<'a>);
289pub(crate) struct NonceCtx<'a> {
290    builder: PacketBuilder<'a>,
291    #[allow(dead_code)]
292    counter: u32,
293}
294#[allow(dead_code)]
295pub(crate) struct Pause<'a>(PacketBuilder<'a>);
296
297// For best security, it is recommended that the `PrivWrite` command not be
298// used, and that private keys be internally generated from the RNG using the
299// `GenKey` command.
300pub(crate) struct PrivWrite<'a>(PacketBuilder<'a>);
301pub(crate) struct Random<'a>(PacketBuilder<'a>);
302pub(crate) struct Read<'a>(PacketBuilder<'a>);
303pub(crate) struct Sign<'a>(PacketBuilder<'a>);
304#[allow(dead_code)]
305pub(crate) struct UpdateExtra<'a>(PacketBuilder<'a>);
306pub(crate) struct Verify<'a>(PacketBuilder<'a>);
307pub(crate) struct Write<'a>(PacketBuilder<'a>);
308pub(crate) struct Sha<'a>(PacketBuilder<'a>);
309pub(crate) struct Aes<'a>(PacketBuilder<'a>);
310#[allow(dead_code)]
311pub(crate) struct Kdf<'a>(PacketBuilder<'a>);
312#[allow(dead_code)]
313pub(crate) struct SecureBoot<'a>(PacketBuilder<'a>);
314#[allow(dead_code)]
315pub(crate) struct SelfTest<'a>(PacketBuilder<'a>);
316
317#[allow(dead_code)]
318impl<'a> Ecdh<'a> {
319    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
320        Self(builder)
321    }
322
323    pub(crate) fn diffie_hellman(
324        &mut self,
325        private_key_id: Slot,
326        public_key: PublicKey,
327    ) -> Result<Packet, Error> {
328        let packet = self
329            .0
330            .opcode(OpCode::Ecdh)
331            .mode(0x00)
332            .param2(private_key_id as u16)
333            .pdu_data(public_key.as_ref())
334            .build()?;
335        Ok(packet)
336    }
337}
338
339// Used when signing an internally stored digest. The GenDig command uses
340// SHA-256 to combine a stored value with the contents of TempKey, which must
341// have been valid prior to the execution of this command.
342#[allow(dead_code)]
343impl<'a> GenDig<'a> {
344    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
345        Self(builder)
346    }
347
348    pub(crate) fn gendig(&mut self, key_id: Slot) -> Result<Packet, Error> {
349        let packet = self
350            .0
351            .opcode(OpCode::GenDig)
352            .param2(key_id as u16)
353            .build()?;
354        Ok(packet)
355    }
356}
357
358/// GenKey
359impl<'a> GenKey<'a> {
360    // Config zone should be locked, otherwise GenKey always fails regardless of
361    // a mode parameter.
362    const MODE_PRIVATE: u8 = 0x04; // Private key generation
363    const MODE_PUBLIC: u8 = 0x00; // Public key calculation
364    #[allow(dead_code)]
365    const MODE_DIGEST: u8 = 0x08; // PubKey digest will be created after the public key is calculated
366    #[allow(dead_code)]
367    const MODE_PUBKEY_DIGEST: u8 = 0x10; // Calculate a digest on the public key
368
369    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
370        Self(builder)
371    }
372
373    pub(crate) fn private_key(&mut self, key_id: Slot) -> Result<Packet, Error> {
374        let packet = self
375            .0
376            .opcode(OpCode::GenKey)
377            .mode(Self::MODE_PRIVATE)
378            .param2(key_id as u16)
379            .build()?;
380        Ok(packet)
381    }
382
383    pub(crate) fn public_key(&mut self, key_id: Slot) -> Result<Packet, Error> {
384        let packet = self
385            .0
386            .opcode(OpCode::GenKey)
387            .mode(Self::MODE_PUBLIC)
388            .param2(key_id as u16)
389            .build()?;
390        Ok(packet)
391    }
392}
393
394impl<'a> Info<'a> {
395    // Info mode Revision
396    const MODE_REVISION: u8 = 0x00;
397
398    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
399        Self(builder)
400    }
401
402    /// Command execution will return a word containing the revision.
403    pub(crate) fn revision(&mut self) -> Result<Packet, Error> {
404        let packet = self
405            .0
406            .opcode(OpCode::Info)
407            .mode(Self::MODE_REVISION)
408            .build()?;
409        Ok(packet)
410    }
411}
412
413impl<'a> Lock<'a> {
414    const LOCK_ZONE_NO_CRC: u8 = 0x80;
415
416    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
417        Self(builder)
418    }
419
420    pub(crate) fn zone(&mut self, zone: Zone, crc: Option<u16>) -> Result<Packet, Error> {
421        // Lock command uses its own zone encoding (bit 0: 0=Config, 1=Data/OTP),
422        // which differs from Read/Write (bits 1:0: 00=Config, 01=OTP, 02=Data).
423        let lock_zone = match zone {
424            Zone::Config => 0x00,
425            Zone::Data => 0x01,
426            Zone::Otp => return Err(ErrorKind::BadParam.into()),
427        };
428
429        let packet = match crc {
430            None => self
431                .0
432                .opcode(OpCode::Lock)
433                .mode(Self::LOCK_ZONE_NO_CRC | lock_zone)
434                .build()?,
435            Some(crc) => self
436                .0
437                .opcode(OpCode::Lock)
438                .mode(lock_zone)
439                .param2(crc)
440                .build()?,
441        };
442
443        Ok(packet)
444    }
445
446    pub(crate) fn slot(&mut self, key_id: Slot) -> Result<Packet, Error> {
447        let mode = (key_id as u8) << 2 | 0x02 | Self::LOCK_ZONE_NO_CRC;
448        let packet = self.0.opcode(OpCode::Lock).mode(mode).build()?;
449        Ok(packet)
450    }
451}
452
453/// Nonce
454impl<'a> NonceCtx<'a> {
455    #[allow(dead_code)]
456    const MODE_MASK: u8 = 0x03; // Nonce mode bits 2 to 7 are 0.
457    #[allow(dead_code)]
458    const MODE_SEED_UPDATE: u8 = 0x00; // Nonce mode: update seed
459    #[allow(dead_code)]
460    const MODE_NO_SEED_UPDATE: u8 = 0x01; // Nonce mode: do not update seed
461    #[allow(dead_code)]
462    const MODE_INVALID: u8 = 0x02; // Nonce mode 2 is invalid.
463    const MODE_PASSTHROUGH: u8 = 0x03; // Nonce mode: pass-through
464    #[allow(dead_code)]
465    const MODE_INPUT_LEN_MASK: u8 = 0x20; // Nonce mode: input size mask
466    #[allow(dead_code)]
467    const MODE_INPUT_LEN_32: u8 = 0x00; // Nonce mode: input size is 32 bytes
468    #[allow(dead_code)]
469    const MODE_INPUT_LEN_64: u8 = 0x20; // Nonce mode: input size is 64 bytes
470    const MODE_TARGET_MASK: u8 = 0xc0; // Nonce mode: target mask
471    #[allow(dead_code)]
472    const MODE_TARGET_TEMPKEY: u8 = 0x00; // Nonce mode: target is TempKey
473    const MODE_TARGET_MSGDIGBUF: u8 = 0x40; // Nonce mode: target is Message Digest Buffer
474    #[allow(dead_code)]
475    const MODE_TARGET_ALTKEYBUF: u8 = 0x80; // Nonce mode: target is Alternate Key Buffer
476
477    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
478        let counter = 0x4432;
479        Self { builder, counter }
480    }
481
482    // TODO: Usage of Nonce, especially its correct timing is not clear. In
483    // `test/api_atcab/atca_tests_aes.c`, AES encryption/decryption assumes
484    // nonce value is loaded to TempKey in advance.
485    pub(crate) fn message_digest_buffer(&mut self, msg: &Digest) -> Result<Packet, Error> {
486        let mode = Self::MODE_PASSTHROUGH | (Self::MODE_TARGET_MSGDIGBUF & Self::MODE_TARGET_MASK);
487        let packet = self
488            .builder
489            .opcode(OpCode::Nonce)
490            .mode(mode)
491            .pdu_data(msg.as_ref())
492            .build()?;
493        Ok(packet)
494    }
495
496    #[allow(dead_code)]
497    fn load(&mut self) -> Self {
498        unimplemented!()
499    }
500
501    #[allow(dead_code)]
502    fn rand(&mut self) -> Self {
503        unimplemented!()
504    }
505
506    #[allow(dead_code)]
507    fn challenge(&mut self) -> Self {
508        unimplemented!()
509    }
510
511    #[allow(dead_code)]
512    fn challenge_seed_update(&mut self) -> Self {
513        unimplemented!()
514    }
515}
516
517/// PrivWrite
518impl<'a> PrivWrite<'a> {
519    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
520        Self(builder)
521    }
522
523    pub(crate) fn write_private_key(
524        &mut self,
525        key_id: Slot,
526        private_key: &Block,
527    ) -> Result<Packet, Error> {
528        // Input is an ECC private key consisting of padding 4 bytes of all 0s
529        // and 32 byte integer.
530        let private_key_range = 4..Size::Block.len() + 4;
531        let private_key_length = private_key_range.end;
532        let mac_range = private_key_length..private_key_length + Size::Block.len();
533        let mac_length = mac_range.end;
534        // Write the padding and private key to the PDU buffer directly.
535        self.0.pdu_buffer()[private_key_range]
536            .as_mut()
537            .copy_from_slice(private_key.as_ref());
538        let packet = self
539            .0
540            .pdu_length(mac_length)
541            .opcode(OpCode::PrivWrite)
542            .param2(key_id as u16)
543            .build()?;
544        Ok(packet)
545    }
546}
547
548impl<'a> Sha<'a> {
549    /// Initialization, does not accept a message
550    const MODE_SHA256_START: u8 = 0x00;
551    /// Add 64 bytes in the meesage to the SHA context
552    const MODE_SHA256_UPDATE: u8 = 0x01;
553    /// Complete the calculation and return the digest
554    const MODE_SHA256_END: u8 = 0x02;
555    /// Add 64 byte ECC public key in the slot to the SHA context
556    #[allow(dead_code)]
557    const MODE_SHA256_PUBLIC: u8 = 0x03;
558
559    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
560        Self(builder)
561    }
562
563    pub(crate) fn start(&mut self) -> Result<Packet, Error> {
564        let packet = self
565            .0
566            .opcode(OpCode::Sha)
567            .mode(Self::MODE_SHA256_START)
568            .build()?;
569        Ok(packet)
570    }
571
572    /// Data length should be exactly 64 bytes.
573    pub(crate) fn update(&mut self, data: &[u8]) -> Result<Packet, Error> {
574        let length = data.len();
575        if length != 64 {
576            return Err(ErrorKind::BadParam.into());
577        }
578
579        let packet = self
580            .0
581            .opcode(OpCode::Sha)
582            .mode(Self::MODE_SHA256_UPDATE)
583            .param2(length as u16)
584            .pdu_data(data)
585            .build()?;
586        Ok(packet)
587    }
588
589    /// Command execution will return a digest of Block size.
590    pub(crate) fn end(&mut self, data: &[u8]) -> Result<Packet, Error> {
591        let length = data.len();
592        if length > 64 {
593            return Err(ErrorKind::BadParam.into());
594        }
595
596        let packet = self
597            .0
598            .opcode(OpCode::Sha)
599            .mode(Self::MODE_SHA256_END)
600            .param2(length as u16)
601            .pdu_data(data)
602            .build()?;
603        Ok(packet)
604    }
605}
606
607/// AES
608impl<'a> Aes<'a> {
609    pub(crate) const DATA_SIZE: usize = 0x10;
610    /// AES mode: Encrypt
611    const MODE_ENCRYPT: u8 = 0x00;
612    /// AES mode: Decrypt
613    const MODE_DECRYPT: u8 = 0x01;
614
615    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
616        Self(builder)
617    }
618
619    /// Plain text has length of 16 bytes.
620    pub(crate) fn encrypt(&mut self, slot: Slot, plaintext: &[u8]) -> Result<Packet, Error> {
621        if !slot.is_private_key() {
622            return Err(ErrorKind::BadParam.into());
623        }
624
625        // Input length should be exactly 16 bytes. Otherwise the device
626        // couldn't recognize the command properly.
627        if plaintext.len() != Self::DATA_SIZE {
628            return Err(ErrorKind::InvalidSize.into());
629        }
630
631        let packet = self
632            .0
633            .opcode(OpCode::Aes)
634            .mode(Self::MODE_ENCRYPT)
635            .param2(slot as u16)
636            .pdu_data(plaintext)
637            .build()?;
638        Ok(packet)
639    }
640
641    /// Cipher text has length of 16 bytes.
642    pub(crate) fn decrypt(&mut self, slot: Slot, ciphertext: &[u8]) -> Result<Packet, Error> {
643        if !slot.is_private_key() {
644            return Err(ErrorKind::BadParam.into());
645        }
646
647        // Input length should be exactly 16 bytes. Otherwise the device
648        // couldn't recognize the command properly.
649        if ciphertext.len() != Self::DATA_SIZE {
650            return Err(ErrorKind::InvalidSize.into());
651        }
652
653        let packet = self
654            .0
655            .opcode(OpCode::Aes)
656            .mode(Self::MODE_DECRYPT)
657            .param2(slot as u16)
658            .pdu_data(ciphertext)
659            .build()?;
660        Ok(packet)
661    }
662}
663
664/// Random
665impl<'a> Random<'a> {
666    const MODE_SEED_UPDATE: u8 = 0x00;
667
668    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
669        Self(builder)
670    }
671
672    pub(crate) fn random(&mut self) -> Result<Packet, Error> {
673        let packet = self
674            .0
675            .opcode(OpCode::Random)
676            .mode(Self::MODE_SEED_UPDATE)
677            .build()?;
678        Ok(packet)
679    }
680}
681
682/// Read
683impl<'a> Read<'a> {
684    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
685        Self(builder)
686    }
687
688    pub(crate) fn slot(&mut self, slot: Slot, block: u8) -> Result<Packet, Error> {
689        let addr = Zone::Data.get_slot_addr(slot, block)?;
690        let mode = Zone::Data.encode(Size::Block);
691        let packet = self
692            .0
693            .opcode(OpCode::Read)
694            .mode(mode)
695            .param2(addr)
696            .build()?;
697        Ok(packet)
698    }
699
700    pub(crate) fn read(
701        &mut self,
702        zone: Zone,
703        size: Size,
704        block: u8,
705        offset: u8,
706    ) -> Result<Packet, Error> {
707        let addr = zone.get_addr(block, offset)?;
708        let mode = zone.encode(size);
709        let packet = self
710            .0
711            .opcode(OpCode::Read)
712            .mode(mode)
713            .param2(addr)
714            .build()?;
715        Ok(packet)
716    }
717}
718
719/// Sign
720impl<'a> Sign<'a> {
721    /// Sign mode bit 0: internal
722    #[allow(dead_code)]
723    const MODE_INTERNAL: u8 = 0x00;
724    /// Sign mode bit 1: Signature will be used for Verify(Invalidate)
725    #[allow(dead_code)]
726    const MODE_INVALIDATE: u8 = 0x01;
727    /// Sign mode bit 6: include serial number
728    #[allow(dead_code)]
729    const MODE_INCLUDE_SN: u8 = 0x40;
730    /// Sign mode bit 7: external
731    const MODE_EXTERNAL: u8 = 0x80;
732
733    /// Sign mode message source is TempKey
734    #[allow(dead_code)]
735    const MODE_SOURCE_TEMPKEY: u8 = 0x00;
736    /// Sign mode message source is the Message Digest Buffer
737    const MODE_SOURCE_MSGDIGBUF: u8 = 0x20;
738
739    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
740        Self(builder)
741    }
742
743    // Sign a 32-byte external message using the private key in the specified
744    // slot.
745    pub(crate) fn external(&mut self, key_id: Slot) -> Result<Packet, Error> {
746        let mode = Self::MODE_EXTERNAL | Self::MODE_SOURCE_MSGDIGBUF;
747        let packet = self
748            .0
749            .opcode(OpCode::Sign)
750            .mode(mode)
751            .param2(key_id as u16)
752            .build()?;
753        Ok(packet)
754    }
755}
756
757/// Verify
758impl<'a> Verify<'a> {
759    const MODE_SOURCE_MSGDIGBUF: u8 = 0x20;
760    const MODE_EXTERNAL: u8 = 0x02;
761    const KEY_P256: u16 = 0x0004;
762
763    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
764        Self(builder)
765    }
766
767    // Verify a 32-byte external message using the provided private key.
768    pub(crate) fn external(
769        &mut self,
770        signature: &p256::ecdsa::Signature,
771        public_key: &PublicKey,
772    ) -> Result<Packet, Error> {
773        let mode = Self::MODE_EXTERNAL | Self::MODE_SOURCE_MSGDIGBUF;
774
775        // Load PDU data
776        let sig_bytes = signature.to_bytes();
777        let sig_length = sig_bytes.len();
778        let (sig_buf, pdu_buffer) = self.0.pdu_buffer().split_at_mut(sig_length);
779        sig_buf.copy_from_slice(sig_bytes.as_slice());
780        let pubkey_length = public_key.as_ref().len();
781        let (pubkey_buffer, _) = pdu_buffer.split_at_mut(pubkey_length);
782        pubkey_buffer.copy_from_slice(public_key.as_ref());
783
784        let packet = self
785            .0
786            .opcode(OpCode::Verify)
787            .mode(mode)
788            .param2(Self::KEY_P256)
789            .pdu_length(sig_length + pubkey_length)
790            .build()?;
791        Ok(packet)
792    }
793}
794
795/// Write
796impl<'a> Write<'a> {
797    pub(crate) fn new(builder: PacketBuilder<'a>) -> Self {
798        Self(builder)
799    }
800
801    pub(crate) fn slot(&mut self, slot: Slot, block: u8, data: &Block) -> Result<Packet, Error> {
802        let addr = Zone::Data.get_slot_addr(slot, block)?;
803        let mode = Zone::Data.encode(Size::Block);
804        let packet = self
805            .0
806            .opcode(OpCode::Write)
807            .mode(mode)
808            .param2(addr)
809            .pdu_data(data.as_ref())
810            .build()?;
811        Ok(packet)
812    }
813
814    pub(crate) fn write(
815        &mut self,
816        zone: Zone,
817        size: Size,
818        block: u8,
819        offset: u8,
820        data: &[u8],
821    ) -> Result<Packet, Error> {
822        if size.len() != data.len() {
823            return Err(ErrorKind::BadParam.into());
824        }
825
826        let addr = zone.get_addr(block, offset)?;
827        let mode = zone.encode(size);
828        let packet = self
829            .0
830            .opcode(OpCode::Write)
831            .mode(mode)
832            .param2(addr)
833            .pdu_data(data)
834            .build()?;
835        Ok(packet)
836    }
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842
843    #[test]
844    fn sha() {
845        let buf = &mut [0x00u8; 0xff];
846        let packet = Sha::new(PacketBuilder::new(buf.as_mut()))
847            .start()
848            .unwrap()
849            .buffer(buf.as_ref());
850        assert_eq!(packet[0x01], 0x07);
851        assert_eq!(packet[0x02], OpCode::Sha as u8);
852        assert_eq!(packet[0x03], Sha::MODE_SHA256_START);
853        assert_eq!(packet[0x04..0x06], [0x00, 0x00]);
854    }
855
856    #[test]
857    fn lock() {
858        let buf = &mut [0x00u8; 0xff];
859        let packet = Lock::new(PacketBuilder::new(buf.as_mut()))
860            .zone(Zone::Config, None)
861            .unwrap()
862            .buffer(buf.as_ref());
863        assert_eq!(packet[0x01], 0x07);
864        assert_eq!(packet[0x02], OpCode::Lock as u8);
865        assert_eq!(packet[0x03], 0x80);
866        assert_eq!(packet[0x04..0x06], [0x00, 0x00]);
867    }
868
869    #[test]
870    fn lock_crc() {
871        let buf = &mut [0x00u8; 0xff];
872        let crc = 0xDEAD;
873        let packet = Lock::new(PacketBuilder::new(buf.as_mut()))
874            .zone(Zone::Config, Some(crc))
875            .unwrap()
876            .buffer(buf.as_ref());
877        assert_eq!(packet[0x01], 0x07);
878        assert_eq!(packet[0x02], OpCode::Lock as u8);
879        assert_eq!(packet[0x03], 0x00);
880        assert_eq!(packet[0x04..0x06], crc.to_le_bytes());
881    }
882
883    #[test]
884    fn genkey() {
885        let buf = &mut [0x00u8; 0xff];
886        let packet = GenKey::new(PacketBuilder::new(buf.as_mut()))
887            .private_key(Slot::PrivateKey01)
888            .unwrap()
889            .buffer(buf.as_ref());
890        assert_eq!(packet[0x01], 0x07);
891        assert_eq!(packet[0x02], OpCode::GenKey as u8);
892        assert_eq!(packet[0x03], 0x04);
893        assert_eq!(packet[0x04..0x06], [0x01, 0x00]);
894    }
895
896    #[test]
897    fn privwrite() {
898        let buf = &mut [0x00u8; 0xff];
899        let mut data = Block::default();
900        data.as_mut()
901            .iter_mut()
902            .enumerate()
903            .for_each(|(i, v)| *v = i as u8);
904        let packet = PrivWrite::new(PacketBuilder::new(buf.as_mut()))
905            .write_private_key(Slot::PrivateKey01, &data)
906            .unwrap()
907            .buffer(buf.as_ref());
908        assert_eq!(packet[0x01], 0x4b);
909        assert_eq!(packet[0x02], OpCode::PrivWrite as u8);
910        assert_eq!(packet[0x03], 0x00);
911        assert_eq!(packet[0x04..0x06], [0x01, 0x00]);
912        assert_eq!(packet[0x06..0x0a], [0x00; 0x04]);
913        assert_eq!(packet[0x0a..0x2a].as_ref(), data.as_ref());
914    }
915
916    // #[test]
917    // fn verify() {
918    //     let buf = &mut [0x00u8; 0xff];
919    //     let mut signature = p256::ecdsa::Signature::default();
920    //     let mut public_key = PublicKey::default();
921
922    //     let (r, s) = signature.as_mut().split_at_mut(32);
923    //     r.iter_mut().for_each(|v| *v = 'r' as u8);
924    //     s.iter_mut().for_each(|v| *v = 's' as u8);
925    //     let (x, y) = public_key.as_mut().split_at_mut(32);
926    //     x.iter_mut().for_each(|v| *v = 'x' as u8);
927    //     y.iter_mut().for_each(|v| *v = 'y' as u8);
928
929    //     let packet = Verify::new(PacketBuilder::new(buf.as_mut()))
930    //         .external(&signature, &public_key)
931    //         .unwrap()
932    //         .buffer(buf.as_ref());
933    //     assert_eq!(packet[0x01], 0x87);
934    //     assert_eq!(packet[0x02], OpCode::Verify as u8);
935    //     assert_eq!(packet[0x03], 0x22);
936    //     assert_eq!(packet[0x04..0x06], [0x04, 0x00]);
937    //     assert_eq!(packet[0x06..0x46].as_ref(), signature.as_ref());
938    //     assert_eq!(packet[0x46..0x86].as_ref(), public_key.as_ref());
939    // }
940}