rust_cryptoauthlib/
types.rs

1use std::mem::MaybeUninit;
2
3use cryptoauthlib_sys::atca_aes_ctr_ctx_t;
4use cryptoauthlib_sys::atca_aes_cmac_ctx_t;
5
6/// An ATECC/ATSHA device buffer to load
7#[repr(u8)]
8#[derive(Copy, Clone, Debug, PartialEq)]
9pub enum NonceTarget {
10    TempKey = 0x00,
11    MsgDigBuf = 0x40,
12    AltKeyBuf = 0x80,
13}
14
15/// Designates the source of the data to hash with TempKey for Generate Digest
16#[repr(u8)]
17#[derive(Copy, Clone, Debug, PartialEq)]
18pub enum GenDigZone {
19    Data = 0x02,
20    SharedNonce = 0x03,
21}
22
23/// Modes of calling the info_cmd() function
24#[allow(dead_code)]
25#[repr(u8)]
26pub enum InfoCmdType {
27    Revision = 0x00,
28    KeyValid = 0x01,
29    State = 0x02,
30    Gpio = 0x03,
31    VolKeyPermit = 0x04,
32}
33
34/// The mode of calling the ECDSA signature function
35pub enum SignMode {
36    /// The input parameter is hash to be signed
37    External(Vec<u8>),
38    Internal(SignEcdsaParam),
39}
40
41/// The mode of calling the ECDSA verification function
42pub enum VerifyMode {
43    /// The input parameter is public key
44    External(Vec<u8>),
45    ExternalMac(VerifyEcdsaParam),
46    /// The input parameter is slot number
47    Internal(u8),
48    InternalMac(VerifyEcdsaParam),
49}
50
51/// Detailed parameters of calling the ECDSA signature function
52pub struct SignEcdsaParam {
53    /// Set to true if the signature will be used with
54    /// the Verify(Invalidate) command. false for all other cases.
55    pub is_invalidate: bool,
56    /// Set to true if the message should incorporate
57    /// the device's full serial number.
58    pub is_full_sn: bool,
59}
60
61/// Detailed parameters of calling the ECDSA verification function
62#[derive(Default)]
63pub struct VerifyEcdsaParam {
64    /// Public key for ExternalMac mode 
65    pub public_key: Option<Vec<u8>>,
66    /// Slot number for InternalMac mode
67    pub slot_number: Option<u8>,
68    /// System nonce (32 byte) used for the verification MAC
69    pub num_in: Vec<u8>,
70    /// IO protection key for verifying the validation MAC
71    pub io_key: u8,
72}
73
74/// Cipher operation type
75#[derive(Copy, Clone, Debug, PartialEq)]
76pub enum CipherOperation {
77    Encrypt,
78    Decrypt,
79}
80
81/// Feedback mode of cipher algorithm
82#[derive(Copy, Clone, Debug, PartialEq)]
83pub enum FeedbackMode {
84    Cfb,
85    Ofb,
86}
87/// Type of Cipher algorithm
88#[derive(Clone, Debug, PartialEq)]
89pub enum CipherAlgorithm {
90    /// Counter
91    Ctr(CipherParam),
92    /// Cipher Feedback
93    Cfb(CipherParam),
94    /// Output Feedback
95    Ofb(CipherParam),
96    /// XEX-based tweaked-codebook mode with ciphertext stealing
97    Xts(CipherParam),
98    /// Electronic Codebook
99    Ecb(CipherParam),
100    /// Cipher-Block Chaining
101    Cbc(CipherParam),
102    /// Cipher-Block Chaining with PKCS#7 padding
103    CbcPkcs7(CipherParam),
104}
105
106/// Cipher algorithm parameters for compute
107#[derive(Clone, Debug, PartialEq, Default)]
108pub struct CipherParam {
109    /// IV - Initialization Vector.
110    /// For CTR mode it is concatenation of nonce and initial counter value.
111    pub iv: Option<[u8; ATCA_AES_KEY_SIZE]>,
112    /// Size of counter in IV in bytes for CTR mode. 4 bytes is a common size.
113    pub counter_size: Option<u8>,
114    /// external encryption/decryption key needed
115    /// when an AES key stored in the cryptochip is not used
116    pub key: Option<Vec<u8>>,
117}
118
119/// Type of AEAD algorithm
120#[derive(Clone, Debug, PartialEq)]
121pub enum AeadAlgorithm {
122    Ccm(AeadParam),
123    Gcm(AeadParam),
124}
125
126/// AEAD algorithm parameters for compute
127#[derive(Clone, Debug, PartialEq, Default)]
128pub struct AeadParam {
129    /// Nonce [number used once aka IV] (default length is 12 bytes)
130    pub nonce: Vec<u8>,
131    /// external encryption/decryption key needed
132    /// when an AES key stored in the cryptochip is not used
133    pub key: Option<[u8; ATCA_AES_KEY_SIZE]>,
134    /// tag to verify authenticity of decrypted data (16 bytes)
135    pub tag: Option<Vec<u8>>,
136    /// tag length generated during encryption
137    pub tag_length: Option<u8>,
138    /// Additional data that will be authenticated but not encrypted
139    pub additional_data: Option<Vec<u8>>,
140}
141
142/// MAC algorithm to compute
143#[derive(Clone, Debug, PartialEq)]
144pub enum MacAlgorithm {
145    HmacSha256(MacParam),
146    Cbcmac(MacParam),
147    Cmac(MacParam),
148}
149
150/// MAC algorithm parameters for compute
151#[derive(Clone, Debug, PartialEq, Default)]
152pub struct MacParam {
153    /// external encryption/decryption key needed for MAC calculation
154    /// when an 'AES' or 'ShaOrText' key stored in the cryptochip is not used
155    pub key: Option<Vec<u8>>,
156    /// MAC length generated during calculation
157    pub mac_length: Option<u8>,
158    /// MAC to verify authenticity of the provided data
159    pub mac: Option<Vec<u8>>,
160}
161
162/// KDF algorithm to derive key
163#[derive(Clone, Debug, PartialEq)]
164pub enum KdfAlgorithm {
165    Prf(PrfDetails),
166    Hkdf(HkdfDetails),
167    Aes,
168}
169
170/// KDF function parameters
171#[derive(Clone, Debug, PartialEq)]
172pub struct KdfParams {
173    pub source: KdfSource,
174    pub target: KdfTarget,
175    pub source_slot_id: Option<u8>,
176    pub target_slot_id: Option<u8>,
177}
178
179impl Default for KdfParams {
180    fn default() -> KdfParams {
181        KdfParams {
182            source: KdfSource::TempKey,
183            target: KdfTarget::Output,
184            source_slot_id: None,
185            target_slot_id: None,
186        }
187    }
188}
189
190/// KDF sources
191#[derive(Clone, Debug, PartialEq)]
192#[repr(u8)]
193pub enum KdfSource {
194    /// source key in TempKey
195    TempKey = 0x00,
196    /// source key in upper TempKey
197    TempKeyUp = 0x01,
198    /// source key in a slot
199    Slot = 0x02,
200    /// source key in alternate key buffer
201    AltKeyBuf = 0x03,
202}
203
204/// KDF targets. Possibility of exporting KDF function result outside the chip
205/// depends on "chip_options.kdf_output_protection" variable
206#[derive(Clone, Debug, PartialEq)]
207#[repr(u8)]
208pub enum KdfTarget {
209    /// target key in TempKey
210    TempKey = 0x00,
211    /// target key in upper TempKey
212    TempKeyUp = 0x04,
213    /// target key in slot
214    Slot = 0x08,
215    /// target key in alternate key buffer
216    AltKeyBuf = 0x0C,
217    /// target key in output buffer
218    Output = 0x10,
219    /// target key encrypted in output buffer
220    OutputEnc = 0x14,
221}
222
223/// KDF details for PRF, source key length
224#[derive(Clone, Debug, PartialEq)]
225#[repr(u32)]
226pub enum KdfPrfKeyLen {
227    /// source key length is 16 bytes
228    Len16 = 0x00000000,
229    /// source key length is 32 bytes
230    Len32 = 0x00000001,
231    /// source key length is 48 bytes
232    Len48 = 0x00000002,
233    /// source key length is 64 bytes
234    Len64 = 0x00000003,
235}
236
237/// KDF details for PRF, target length
238#[derive(Clone, Debug, PartialEq)]
239#[repr(u32)]
240pub enum KdfPrfTargetLen {
241    /// target length is 32 bytes
242    Len32 = 0x00000000,
243    /// target length is 64 bytes
244    Len64 = 0x00000100,
245}
246
247impl From<KdfPrfTargetLen> for usize {
248    fn from(orig: KdfPrfTargetLen) -> Self {
249        match orig {
250            KdfPrfTargetLen::Len32 => 32,
251            KdfPrfTargetLen::Len64 => 64,
252        }
253    }
254}
255
256/// KDF details for PRF
257#[derive(Clone, Debug, PartialEq)]
258pub struct PrfDetails {
259    pub key_length: KdfPrfKeyLen,
260    pub target_length: KdfPrfTargetLen,
261}
262
263impl Default for PrfDetails {
264    fn default() -> PrfDetails {
265        PrfDetails {
266            key_length: KdfPrfKeyLen::Len32,
267            target_length: KdfPrfTargetLen::Len64,
268        }
269    }
270}
271
272/// KDF details for HKDF. [place from which function should retrieve message for calculations]
273#[derive(Clone, Debug, PartialEq)]
274#[repr(u32)]
275pub enum HkdfMsgLoc {
276    /// message location in slot
277    Slot = 0x00000000,
278    /// message location in TempKey
279    TempKey = 0x00000001,
280    /// message location in input parameter
281    Input = 0x00000002,
282    /// message location is a special IV function
283    Iv = 0x00000003,
284}
285
286/// KDF details for HKDF
287#[derive(Clone, Debug, PartialEq)]
288pub struct HkdfDetails {
289    pub msg_loc: HkdfMsgLoc,
290    /// if true then a vector of thirty-two zero bytes will be used as the key
291    pub zero_key: bool,
292    /// if source of message is a slot, its identifier must be entered
293    pub msg_slot: Option<u8>,
294}
295
296impl Default for HkdfDetails {
297    fn default() -> HkdfDetails {
298        HkdfDetails {
299            msg_loc: HkdfMsgLoc::Input,
300            zero_key: false,
301            msg_slot: None,
302        }
303    }
304}
305
306/// KDF result structure
307#[derive(Clone, Debug, PartialEq)]
308pub struct KdfResult {
309    /// Data are available only when the target of the KDF function is 'Output' or 'OutputEnc'
310    pub out_data: Option<Vec<u8>>,
311    /// Data are available only when the target of the KDF function is 'OutputEnc'
312    pub out_nonce: Option<Vec<u8>>,
313}
314
315/// ECDH function parameters
316#[derive(Clone, Debug, PartialEq)]
317pub struct EcdhParams {
318    /// private key source for ECDH
319    pub key_source: EcdhSource,
320    /// target where the result of the ECDH operation will be placed
321    pub out_target: EcdhTarget,
322    /// parameter that specifies whether the output should be encrypted
323    /// (only relevant for the ATECC608x chip)
324    pub out_encrypt: bool,
325    /// slot number where the private key will be retrieved
326    /// or where result of the ECDH operation will be placed
327    pub slot_id: Option<u8>,
328}
329
330impl Default for EcdhParams {
331    fn default() -> EcdhParams {
332        EcdhParams {
333            key_source: EcdhSource::Slot,
334            out_target: EcdhTarget::Compatibility,
335            out_encrypt: false,
336            slot_id: None,
337        }
338    }
339}
340
341/// Private key source for ECDH
342#[derive(Clone, Debug, PartialEq)]
343#[repr(u8)]
344pub enum EcdhSource{
345    /// source key in a slot
346    Slot = 0x00,
347    /// source key in TempKey (only relevant for the ATECC608x chip)
348    TempKey = 0x01,
349}
350
351/// Target where the result of the ECDH operation will be placed
352#[derive(Clone, Debug, PartialEq)]
353#[repr(u8)]
354pub enum EcdhTarget {
355    /// Compatibility mode for ATECC508A. Result goes to either the output buffer
356    /// or (slot_id + 1) depending on the state of slots[slot_idx].config.ecc_key_attr.ecdh_secret_out
357    Compatibility = 0x00,
358    /// Result goes to slot specified by KeyID. slots[slot_idx].write_config must be ALWAYS
359    /// (only relevant for the ATECC608x chip)
360    Slot  = 0x04,
361    /// Result goes to TempKey (only relevant for the ATECC608x chip)
362    TempKey = 0x08,
363    /// Result goes to the output buffer (only relevant for the ATECC608x chip)
364    Output = 0x0C,
365}
366
367/// ECDH result structure
368#[derive(Clone, Debug, PartialEq)]
369pub struct EcdhResult {
370    /// Computed ECDH pre-master secret (32 bytes) if returned directly
371    pub pms: Option<Vec<u8>>,
372    /// Nonce used to encrypt pre-master secret
373    pub out_nonce: Option<Vec<u8>>,
374}
375
376/// Data context structure for AEAD encryption in CCM mode
377#[derive(Copy, Clone, Debug)]//, PartialEq)]
378pub struct AtcaAesCcmCtx {
379    pub cbc_mac_ctx: atca_aes_cmac_ctx_t,           // CBC_MAC context
380    pub ctr_ctx: atca_aes_ctr_ctx_t,                // CTR context
381    pub iv_size: u8,                                // iv size
382    pub m: u8,                                      // Tag size
383    pub counter: [u8; ATCA_AES_DATA_SIZE],          // Initial counter value
384    pub partial_aad: [u8; ATCA_AES_DATA_SIZE],      // Partial blocks of data waiting to be processed
385    pub partial_aad_size: usize,                    // Amount of data in the partial block buffer
386    pub text_size: usize,                           // Size of data to be processed
387    pub enc_cb: [u8; ATCA_AES_DATA_SIZE],           // Last encrypted counter block
388    pub data_size: u32,                             // Size of the data being encrypted/decrypted in bytes.
389    pub ciphertext_block: [u8; ATCA_AES_DATA_SIZE]  // Last ciphertext block
390}
391
392impl Default for AtcaAesCcmCtx {
393    fn default() -> AtcaAesCcmCtx {
394        AtcaAesCcmCtx {
395            cbc_mac_ctx: {
396                let ctx = MaybeUninit::<atca_aes_cmac_ctx_t>::zeroed();
397                unsafe { ctx.assume_init() }
398            },
399            ctr_ctx: {
400                let ctx = MaybeUninit::<atca_aes_ctr_ctx_t>::zeroed();
401                unsafe { ctx.assume_init() }
402            },
403            iv_size: ATCA_AES_DATA_SIZE as u8,
404            m: ATCA_AES_DATA_SIZE as u8,
405            counter: [0x00; ATCA_AES_DATA_SIZE],
406            partial_aad: [0x00; ATCA_AES_DATA_SIZE],
407            partial_aad_size: 0,
408            text_size: 0,
409            enc_cb: [0x00; ATCA_AES_DATA_SIZE],
410            data_size: 0,
411            ciphertext_block: [0x00; ATCA_AES_DATA_SIZE],
412        }
413    }
414}
415
416/// structure that stores data for options supported by the chip
417#[derive(Copy, Clone, Debug, PartialEq)]
418pub struct ChipOptions {
419    /// If true, then the protection functions are enabled via the secret key
420    /// stored in the slot indicated by io_key_in_slot.
421    /// If false, the security functions are disabled and fields 'io_key_in_slot',
422    /// 'ecdh_output_protection' and 'kdf_output_protection' are irrelevant
423    /// (only relevant for the ATECC608x chip)
424    pub io_key_enabled: bool,
425    /// slot number where the key for encrypting transmission between chip and host is placed
426    pub io_key_in_slot: u8,
427    /// flag, on-chip availability, AES function
428    pub aes_enabled: bool,
429    /// flag, on-chip availability, AES functionality for KDF command
430    pub kdf_aes_enabled: bool,
431    /// restrictions on the way the ECDH command result can be used
432    pub ecdh_output_protection: OutputProtectionState,
433    /// restrictions on the way the KDF command result can be used
434    pub kdf_output_protection: OutputProtectionState,
435    /// availability flag of the special function of the IV KDF command 
436    pub kdf_iv_enabled: bool,
437    /// place in message where special data bytes must be placed
438    /// when calling function IV of the KDF command
439    pub kdf_iv_location_at: usize,
440    /// two bytes of data that must be included in message
441    /// when calling function IV of the KDF command
442    pub kdf_iv_str: [u8; 0x02],
443}
444
445impl Default for ChipOptions {
446    fn default() -> ChipOptions {
447        ChipOptions {
448            io_key_enabled: false,
449            io_key_in_slot: 0x00,
450            aes_enabled: false,
451            kdf_aes_enabled: false,
452            ecdh_output_protection: OutputProtectionState::Invalid,
453            kdf_output_protection: OutputProtectionState::Invalid,
454            kdf_iv_enabled: false,
455            kdf_iv_location_at: 0x00,
456            kdf_iv_str: [0x00, 0x00],
457        }
458    }
459}
460
461/// Allowed IO transmission states between chip and host MCU
462/// for ECDH, KDF, Verify and SecureBoot commands.
463#[repr(u8)]
464#[derive(Copy, Clone, Debug, PartialEq)]
465pub enum OutputProtectionState {
466    /// Output in the clear is OK, though encryption can still be indicated in the mode parameter
467    ClearTextAllowed = 0x00,
468    /// Output is OK, but the result must be encrypted.
469    /// The state of the encryption bit in the mode parameter will be ignored by the ECDH command.
470    EncryptedOutputOnly = 0x01,
471    /// Result must be stored in TempKey or and key slot, output outside the chip is forbidden
472    ForbiddenOutputOutsideChip = 0x02,
473    /// Invalid state
474    Invalid = 0x03,
475}
476
477impl From<u8> for OutputProtectionState {
478    fn from(orig: u8) -> Self {
479        match orig {
480            0x0 => OutputProtectionState::ClearTextAllowed,
481            0x1 => OutputProtectionState::EncryptedOutputOnly,
482            0x2 => OutputProtectionState::ForbiddenOutputOutsideChip,
483            _ => OutputProtectionState::Invalid,
484        }
485    }
486}
487
488/// An ATECC slot
489#[derive(Copy, Clone, Debug, Default)]
490pub struct AtcaSlot {
491    /// ATECC slot id (for diagnostic)
492    pub id: u8,
493    /// Lock status of slot (locked or not). If is_locked is true,
494    /// slot cannot be written
495    pub is_locked: bool,
496    /// Slot configuration as can be read from configuration zone
497    pub config: SlotConfig,
498}
499
500/// An ATECC slot capacity
501#[derive(Copy, Clone, Debug, Default)]
502pub struct AtcaSlotCapacity {
503    pub blocks: u8,
504    pub last_block_bytes: u8,
505    pub bytes: u16,
506}
507
508/// Detailed ATECC key slot configuration
509#[derive(Copy, Clone, Debug)]
510pub struct SlotConfig {
511    /// Controls the ability to modify the data in this slot.
512    pub write_config: WriteConfig,
513
514    pub key_type: KeyType,
515
516    pub read_key: ReadKey,
517
518    pub ecc_key_attr: EccKeyAttr,
519
520    /// The index into the X509format array within the Configuration zone
521    /// which corresponds to this slot.
522    /// If the corresponding format byte is zero, then the public key
523    /// can be validated by any format signature by the parent.
524    /// If the corresponding format byte is non-zero, then the validating
525    /// certificate must be of a certain length;
526    /// the stored public key must be locateindicates this slot contains
527    /// an ECC private key at a certain place within the message and the SHA()
528    /// commands must be used to generate the digest of the message.
529    /// Must be zero if the slot does not contain a public key.
530    /// Valid range from 0 to 3.
531    pub x509id: u8,
532
533    /// If 'req_auth' is true, this field points to the key that must be used
534    /// for authorization before the key associated with this slot may be used.
535    /// Must be zero if 'req_auth' is false.
536    /// Valid range from 0 to 15.
537    pub auth_key: u8,
538
539    /// Use this key to validate and encrypt data written to the slot
540    /// indicated by this variable.
541    /// Valid range from 0 to 15.
542    pub write_key: u8,
543
544    /// true = The contents of this slot are secret – Clear text reads are prohibited
545    /// and both 4-byte reads and writes are prohibited.
546    /// This variable must be true if 'encrypt_read' is a true or if 'write_config'
547    /// has any value other than 'Always' to ensure proper operation of the device.
548    /// false = The contents of this slot should contain neither confidential data nor keys.
549    /// The GenKey and Sign commands will fail if 'is_secret'
550    /// is set to false for any ECC private key.
551    pub is_secret: bool,
552
553    /// true = The key stored in the slot is "Limited Use".
554    /// The number of uses of this key is limited by a in chip monotonic counter.
555    /// false = There are no usage limitations.
556    pub limited_use: bool,
557
558    /// true = The key stored in the slot is intended for verification usage
559    /// and cannot be used by the MAC or HMAC commands.
560    /// When this key is used to generate or modify TempKey,
561    /// then that value may not be used by the MAC and HMAC commands.
562    /// Also cannot be used with the SHA command in HMAC mode.
563    /// false = The key stored in the slot can be used by all commands.
564    pub no_mac: bool,
565
566    /// true = Use of this key is prohibited for all commands other than
567    /// GenKey if the PersistentLatch is zero.
568    /// GenKey is permitted regardless of the state of the latch.
569    /// false = Use of this key is independent of the state of the PersistentLatch.
570    pub persistent_disable: bool,
571
572    /// true = Before this key must be used, a prior authorization using
573    /// the key pointed to by AuthKey must be completed successfully
574    /// prior to cryptographic use of the key.
575    /// Applies to all key types, both public, secret, and private.
576    /// false = No prior authorization is required.
577    pub req_auth: bool,
578
579    /// If true then a random nonce is required for
580    /// GenKey, MAC, CheckMac, Verify, DeriveKey, and GenDig commands.
581    pub req_random: bool,
582
583    /// If true then this slot can be individually locked using the Lock command.
584    pub lockable: bool,
585
586    /// If 'is_private' indicates this slot contains an ECC private key:
587    /// false = The public version of this key can never be generated.
588    /// Use this mode for the highest security.
589    /// true = The public version of this key can always be generated.
590    /// If 'is_private' indicates that this slot does not contain an ECC private key,
591    /// then this bit may be used to control validity of public keys.
592    /// If so configured, the Verify command will only use a stored public key
593    /// to verify a signature if it has been validated.
594    /// The Sign and Info commands are used to report the validity state.
595    /// The public key validity feature is ignored by all other commands
596    /// and applies only to Slots 8 - 15.
597    /// false = The public key in this slot can be used by the Verify command
598    /// without being validated.
599    /// true = The public key in this slot can be used by the Verify command
600    /// only if the public key in the slot has been validated.
601    /// When this slot is written for any reason, the most significant four bits
602    /// of byte 0 of block 0 will be set to 0xA to invalidate the slot.
603    /// The Verify command can be used to write those bits to 0x05 to validate the slot.
604    /// If this slot contains a key of type Data or AES, then the 'pub_info' bit
605    /// controls whether or not the KDF command write data into this slot.
606    /// If true, then writes by KDF are allowed.
607    /// If false, KDF may not write to this slot.
608    pub pub_info: bool,
609}
610
611impl Default for SlotConfig {
612    fn default() -> Self {
613        SlotConfig {
614            write_config: WriteConfig::Rfu,
615            key_type: KeyType::Rfu,
616            read_key: ReadKey::default(),
617            ecc_key_attr: EccKeyAttr::default(),
618            x509id: 0u8,
619            auth_key: 0u8,
620            write_key: 0u8,
621            is_secret: false,
622            limited_use: false,
623            no_mac: false,
624            persistent_disable: false,
625            req_auth: false,
626            req_random: false,
627            lockable: false,
628            pub_info: false,
629        }
630    }
631}
632
633/// Detailed ECC key attributes as stored in slot configuration
634#[derive(Copy, Clone, Debug, Default)]
635pub struct EccKeyAttr {
636    /// true = The key slot contains an ECC private key and
637    /// can be accessed only with the Sign, GenKey, and PrivWrite commands.
638    /// false = The key slot does not contain an ECC private key and
639    /// cannot be accessed with the Sign, GenKey, and PrivWrite commands.
640    /// It may contain an ECC public key, a SHA key, or data.
641    pub is_private: bool,
642
643    /// Slots containing private keys can never be read
644    /// so the fields below are only valid if 'is_private' is true.
645
646    /// false = External signatures of arbitrary messages are not enabled.
647    /// true = External signatures of arbitrary messages are enabled.
648    pub ext_sign: bool,
649
650    /// false = Internal signatures of messages are not enabled.
651    /// true = Internal signatures of messages generated by
652    /// GenDig or GenKey are enabled.
653    pub int_sign: bool,
654
655    /// false = ECDH operation is not permitted for this key.
656    /// true = ECDH operation is permitted for this key.
657    pub ecdh_operation: bool,
658
659    /// false = ECDH master secret will be output in the clear.
660    /// true = Master secret will be written into slot N+1.
661    /// (Can only be set to true for even number slots and
662    /// should always be false for odd number slots)
663    /// This bit is ignored if 'ecdh_operation' is false.
664    pub ecdh_secret_out: bool,
665}
666
667/// Detailed ATECC key slot read attributes
668#[derive(Copy, Clone, Debug, Default)]
669pub struct ReadKey {
670    /// true = Reads from this slot will be encrypted using the procedure
671    /// specified in the Read command using value of 'slot_number'
672    /// to generate the encryption key. No input MAC is required.
673    /// If this bit is true, then 'is_secret'
674    /// from 'SlotConfig' struct must also be set.
675    /// false = Clear text reads may be permitted,
676    /// and the 'slot_number' field is irrelevant.
677    pub encrypt_read: bool,
678
679    /// Valid range from 0 to 15.
680    /// If 0 then this slot can be the source for the CheckMac copy operation.
681    /// Do not use zero as a default. Do not set this field to zero
682    /// unless the CheckMac copy operation is explicitly desired,
683    /// regardless of any other read/write restrictions.
684    pub slot_number: u8,
685}
686
687/// Detailed ATECC key slot write configuration
688#[derive(Copy, Clone, Debug, PartialEq)]
689pub enum WriteConfig {
690    Rfu,    // do not use
691
692    /// Clear text writes are always permitted on this slot.
693    /// Slots set to always should never be used as key storage.
694    /// Either 4 or 32 bytes may be written to this slot.
695    Always,
696
697    /// If a validated public key is stored in the slot, writes are prohibited.
698    /// Use Verify(Invalidate) to invalidate prior to writing.
699    /// Do not use this mode unless slot contains a public key.
700    PubInvalid,
701
702    /// Writes are never permitted on this slot using the Write command.
703    /// Slots set to never can still be used as key storage.
704    Never,
705
706    /// Writes to this slot require a properly computed MAC,
707    /// and the input data must be encrypted by the system with WriteKey
708    /// using the encryption algorithm documented in the Write command description.
709    /// 4-byte writes to this slot are prohibited.
710    Encrypt,
711}
712
713/// ATECC key slot types
714#[derive(Copy, Clone, Debug, PartialEq)]
715pub enum KeyType {
716    /// Do not use (Reserved for Future Use)
717    Rfu,
718    /// Slot may contain ECC key
719    P256EccKey,
720    /// Slot may contain AES key
721    Aes,
722    /// Slot may contain hash value or a raw text
723    ShaOrText,
724}
725
726/// ATECC interface configuration
727#[derive(Copy, Clone)]
728pub struct AtcaIfaceCfg {
729    /// ATECC interface type
730    iface_type: AtcaIfaceType,
731    /// ATECC device type
732    devtype: AtcaDeviceType,
733    /// ATECC interface details (contents depend on interface type).
734    /// Not needed at all for "test-interface"
735    iface: Option<AtcaIface>,
736    wake_delay: u16,
737    rx_retries: i32,
738} // pub struct AtcaIfaceCfg
739
740/// ATECC interface
741// Only one can be instantiated at a time
742#[derive(Copy, Clone)]
743pub union AtcaIface {
744    /// ATECC I2C interface settings
745    pub atcai2c: AtcaIfaceI2c,
746    // pub atcaswi: AtcaIfaceSwi,
747    // pub atcauart: AtcaIfaceUart,
748    // pub atcahid: AtcaIfaceHid,
749} // pub union AtcaIface
750
751/// ATECC I2C interface details
752#[derive(Copy, Clone, Default)]
753pub struct AtcaIfaceI2c {
754    /// ATECC I2C bus address
755    slave_address: u8,
756    /// ATECC I2C bus number
757    bus: u8,
758    /// ATECC I2C bus baud rate
759    baud: u32,
760} // pub struct AtcaIfaceI2c
761
762/// Supported ATECC interfaces
763#[derive(PartialEq, Copy, Clone, Display)]
764pub enum AtcaIfaceType {
765    AtcaI2cIface,
766    AtcaSwiIface,
767    AtcaUartIface,
768    AtcaSpiIface,
769    AtcaHidIface,
770    AtcaCustomIface,
771    AtcaTestIface,
772    AtcaUnknownIface,
773} // pub enum AtcaIfaceType
774
775/// ATECC/ATSHA device types supported by CryptoAuth library
776#[derive(PartialEq, Debug, Display, Copy, Clone)]
777pub enum AtcaDeviceType {
778    ATSHA204A,
779    ATECC108A,
780    ATECC508A,
781    ATECC608A,
782    ATSHA206A,
783    AtcaTestDevFail,
784    AtcaTestDevSuccess,
785    AtcaTestDevNone,
786    AtcaTestDevFailUnimplemented,
787    AtcaDevUnknown,
788} // pub enum AtcaDeviceType
789
790/// Return status for device accessing functions
791#[derive(Debug, Copy, Clone, Display, PartialEq)]
792pub enum AtcaStatus {
793    /// Function succeeded.
794    AtcaSuccess,
795    AtcaConfigZoneLocked,
796    AtcaDataZoneLocked,
797    /// response status byte indicates CheckMac failure (status byte = 0x01)
798    AtcaWakeFailed,
799    /// response status byte indicates CheckMac failure (status byte = 0x01)
800    AtcaCheckMacVerifyFailed,
801    /// response status byte indicates parsing error (status byte = 0x03)
802    AtcaParseError,
803    /// response status byte indicates DEVICE did not receive data properly (status byte = 0xFF)
804    AtcaStatusCrc,
805    /// response status byte is unknown
806    AtcaStatusUnknown,
807    /// response status byte is ECC fault (status byte = 0x05)
808    AtcaStatusEcc,
809    /// response status byte is Self Test Error, chip in failure mode (status byte = 0x07)
810    AtcaStatusSelftestError,
811    /// Function could not execute due to incorrect condition / state.
812    AtcaFuncFail,
813    /// unspecified error
814    AtcaGenFail,
815    /// bad argument (out of range, null pointer, etc.)
816    AtcaBadParam,
817    /// invalid device id, id not set
818    AtcaInvalidId,
819    /// Count value is out of range or greater than buffer size.
820    AtcaInvalidSize,
821    /// CRC error in data received from device
822    AtcaRxCrcError,
823    /// Timed out while waiting for response. Number of bytes received is > 0.
824    AtcaRxFail,
825    /// Not an error while the Command layer is polling for a command response.
826    AtcaRxNoResponse,
827    /// Re-synchronization succeeded, but only after generating a Wake-up
828    AtcaResyncWithWakeup,
829    /// for protocols needing parity
830    AtcaParityError,
831    /// for Microchip PHY protocol, timeout on transmission waiting for master
832    AtcaTxTimeout,
833    /// for Microchip PHY protocol, timeout on receipt waiting for master
834    AtcaRxTimeout,
835    /// Device did not respond too many times during a transmission. Could indicate no device present.
836    AtcaTooManyCommRetries,
837    /// Supplied buffer is too small for data required
838    AtcaSmallBuffer,
839    /// Communication with device failed. Same as in hardware dependent modules.
840    AtcaCommFail,
841    /// Timed out while waiting for response. Number of bytes received is 0.
842    AtcaTimeout,
843    /// opcode is not supported by the device
844    AtcaBadOpcode,
845    /// received proper wake token
846    AtcaWakeSuccess,
847    /// chip was in a state where it could not execute the command, response status byte indicates command execution error (status byte = 0x0F)
848    AtcaExecutionError,
849    /// Function or some element of it hasn't been implemented yet
850    AtcaUnimplemented,
851    /// Code failed run-time consistency check
852    AtcaAssertFailure,
853    /// Failed to write
854    AtcaTxFail,
855    /// required zone was not locked
856    AtcaNotLocked,
857    /// For protocols that support device discovery (kit protocol), no devices were found
858    AtcaNoDevices,
859    /// random number generator health test error
860    AtcaHealthTestError,
861    /// Couldn't allocate required memory
862    AtcaAllocFailure,
863    /// Use flags on the device indicates its consumed fully
864    AtcaUseFlagsConsumed,
865    /// Unknown error occured
866    AtcaUnknown,
867} // pub enum AtcaStatus
868
869#[derive(Debug)]
870struct AtcaIfaceCfgPtrWrapper {
871    ptr: *mut cryptoauthlib_sys::ATCAIfaceCfg,
872}
873
874unsafe impl Send for AtcaIfaceCfgPtrWrapper {}
875unsafe impl Sync for AtcaIfaceCfgPtrWrapper {}