xref: /aosp_15_r20/system/keymint/wire/src/keymint.rs (revision 9860b7637a5f185913c70aa0caabe3ecb78441e4)
1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Local types that are equivalent to those generated for KeyMint HAL interfaces
16 //!
17 //! - Enums are encoded as exhaustive Rust enums backed by `i32`, using Rust naming
18 //!   conventions (CamelCase values).
19 //! - Structs have all fields `pub`, using Rust naming conventions (snake_case fields).
20 //! - Both enums and structs get a `[derive(AsCborValue)]`
21 //!
22 //! Special cases:
23 //! - The `BeginResult` type of the HAL interface is omitted here, as it includes a
24 //!   Binder reference.
25 //! - `Tag` is private to this module, because....
26 //! - `KeyParam` is a Rust `enum` that is used in place of the `KeyParameter` struct, meaning...
27 //! - `KeyParameterValue` is not included here.
28 
29 use crate::{
30     cbor, cbor_type_error, try_from_n, vec_try, AsCborValue, CborError, KeySizeInBits, RsaExponent,
31 };
32 use alloc::format;
33 use alloc::string::{String, ToString};
34 use alloc::vec::Vec;
35 use enumn::N;
36 use kmr_derive::{AsCborValue, FromRawTag};
37 
38 /// Default certificate serial number of 1.
39 pub const DEFAULT_CERT_SERIAL: &[u8] = &[0x01];
40 
41 /// ASN.1 DER encoding of the default certificate subject of 'CN=Android Keystore Key'.
42 pub const DEFAULT_CERT_SUBJECT: &[u8] = &[
43     0x30, 0x1f, // SEQUENCE len 31
44     0x31, 0x1d, // SET len 29
45     0x30, 0x1b, // SEQUENCE len 27
46     0x06, 0x03, // OBJECT IDENTIFIER len 3
47     0x55, 0x04, 0x03, // 2.5.4.3 (commonName)
48     0x0c, 0x14, // UTF8String len 20
49     0x41, 0x6e, 0x64, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x4b, 0x65, 0x79, 0x73, 0x74, 0x6f, 0x72, 0x65,
50     0x20, 0x4b, 0x65, 0x79, // "Android Keystore Key"
51 ];
52 
53 /// Constants to indicate whether or not to include/expect more messages when splitting and then
54 /// assembling the large responses sent from the TA to the HAL.
55 pub const NEXT_MESSAGE_SIGNAL_TRUE: u8 = 0b00000001u8;
56 pub const NEXT_MESSAGE_SIGNAL_FALSE: u8 = 0b00000000u8;
57 
58 /// We use Unix epoch as the start date of an undefined certificate validity period.
59 pub const UNDEFINED_NOT_BEFORE: DateTime = DateTime { ms_since_epoch: 0 };
60 /// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
61 /// 9999-12-31T23:59:59Z.
62 pub const UNDEFINED_NOT_AFTER: DateTime = DateTime { ms_since_epoch: 253402300799000 };
63 
64 /// Possible verified boot state values.
65 #[derive(Clone, Copy, Debug, PartialEq, Eq, N, AsCborValue)]
66 pub enum VerifiedBootState {
67     Verified = 0,
68     SelfSigned = 1,
69     Unverified = 2,
70     Failed = 3,
71 }
72 
73 impl TryFrom<i32> for VerifiedBootState {
74     type Error = CborError;
try_from(v: i32) -> Result<Self, Self::Error>75     fn try_from(v: i32) -> Result<Self, Self::Error> {
76         Self::n(v).ok_or(CborError::OutOfRangeIntegerValue)
77     }
78 }
79 
80 /// Information provided once at start-of-day, normally by the bootloader.
81 ///
82 /// Field order is fixed, to match the CBOR type definition of `RootOfTrust` in `IKeyMintDevice`.
83 #[derive(Clone, Debug, AsCborValue, PartialEq, Eq)]
84 pub struct BootInfo {
85     pub verified_boot_key: Vec<u8>,
86     pub device_boot_locked: bool,
87     pub verified_boot_state: VerifiedBootState,
88     pub verified_boot_hash: Vec<u8>,
89     pub boot_patchlevel: u32, // YYYYMMDD format
90 }
91 
92 // Implement the `coset` CBOR serialization traits in terms of the local `AsCborValue` trait,
93 // in order to get access to tagged versions of serialize/deserialize.
94 impl coset::AsCborValue for BootInfo {
from_cbor_value(value: cbor::value::Value) -> coset::Result<Self>95     fn from_cbor_value(value: cbor::value::Value) -> coset::Result<Self> {
96         <Self as AsCborValue>::from_cbor_value(value).map_err(|e| e.into())
97     }
to_cbor_value(self) -> coset::Result<cbor::value::Value>98     fn to_cbor_value(self) -> coset::Result<cbor::value::Value> {
99         <Self as AsCborValue>::to_cbor_value(self).map_err(|e| e.into())
100     }
101 }
102 
103 impl coset::TaggedCborSerializable for BootInfo {
104     const TAG: u64 = 40001;
105 }
106 
107 /// Representation of a date/time.
108 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
109 pub struct DateTime {
110     pub ms_since_epoch: i64,
111 }
112 
113 impl AsCborValue for DateTime {
from_cbor_value(value: cbor::value::Value) -> Result<Self, CborError>114     fn from_cbor_value(value: cbor::value::Value) -> Result<Self, CborError> {
115         let val = <i64>::from_cbor_value(value)?;
116         Ok(Self { ms_since_epoch: val })
117     }
to_cbor_value(self) -> Result<cbor::value::Value, CborError>118     fn to_cbor_value(self) -> Result<cbor::value::Value, CborError> {
119         self.ms_since_epoch.to_cbor_value()
120     }
cddl_typename() -> Option<String>121     fn cddl_typename() -> Option<String> {
122         Some("DateTime".to_string())
123     }
cddl_schema() -> Option<String>124     fn cddl_schema() -> Option<String> {
125         Some("int".to_string())
126     }
127 }
128 
129 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
130 #[repr(i32)]
131 pub enum Algorithm {
132     Rsa = 1,
133     Ec = 3,
134     Aes = 32,
135     TripleDes = 33,
136     Hmac = 128,
137 }
138 try_from_n!(Algorithm);
139 
140 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
141 pub struct AttestationKey {
142     pub key_blob: Vec<u8>,
143     pub attest_key_params: Vec<KeyParam>,
144     pub issuer_subject_name: Vec<u8>,
145 }
146 
147 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
148 #[repr(i32)]
149 pub enum BlockMode {
150     Ecb = 1,
151     Cbc = 2,
152     Ctr = 3,
153     Gcm = 32,
154 }
155 try_from_n!(BlockMode);
156 
157 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
158 pub struct Certificate {
159     pub encoded_certificate: Vec<u8>,
160 }
161 
162 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
163 #[repr(i32)]
164 pub enum Digest {
165     None = 0,
166     Md5 = 1,
167     Sha1 = 2,
168     Sha224 = 3,
169     Sha256 = 4,
170     Sha384 = 5,
171     Sha512 = 6,
172 }
173 try_from_n!(Digest);
174 
175 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
176 #[repr(i32)]
177 pub enum EcCurve {
178     P224 = 0,
179     P256 = 1,
180     P384 = 2,
181     P521 = 3,
182     #[cfg(feature = "hal_v2")]
183     Curve25519 = 4,
184 }
185 try_from_n!(EcCurve);
186 
187 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
188 #[repr(i32)]
189 pub enum ErrorCode {
190     Ok = 0,
191     RootOfTrustAlreadySet = -1,
192     UnsupportedPurpose = -2,
193     IncompatiblePurpose = -3,
194     UnsupportedAlgorithm = -4,
195     IncompatibleAlgorithm = -5,
196     UnsupportedKeySize = -6,
197     UnsupportedBlockMode = -7,
198     IncompatibleBlockMode = -8,
199     UnsupportedMacLength = -9,
200     UnsupportedPaddingMode = -10,
201     IncompatiblePaddingMode = -11,
202     UnsupportedDigest = -12,
203     IncompatibleDigest = -13,
204     InvalidExpirationTime = -14,
205     InvalidUserId = -15,
206     InvalidAuthorizationTimeout = -16,
207     UnsupportedKeyFormat = -17,
208     IncompatibleKeyFormat = -18,
209     UnsupportedKeyEncryptionAlgorithm = -19,
210     UnsupportedKeyVerificationAlgorithm = -20,
211     InvalidInputLength = -21,
212     KeyExportOptionsInvalid = -22,
213     DelegationNotAllowed = -23,
214     KeyNotYetValid = -24,
215     KeyExpired = -25,
216     KeyUserNotAuthenticated = -26,
217     OutputParameterNull = -27,
218     InvalidOperationHandle = -28,
219     InsufficientBufferSpace = -29,
220     VerificationFailed = -30,
221     TooManyOperations = -31,
222     UnexpectedNullPointer = -32,
223     InvalidKeyBlob = -33,
224     ImportedKeyNotEncrypted = -34,
225     ImportedKeyDecryptionFailed = -35,
226     ImportedKeyNotSigned = -36,
227     ImportedKeyVerificationFailed = -37,
228     InvalidArgument = -38,
229     UnsupportedTag = -39,
230     InvalidTag = -40,
231     MemoryAllocationFailed = -41,
232     ImportParameterMismatch = -44,
233     SecureHwAccessDenied = -45,
234     OperationCancelled = -46,
235     ConcurrentAccessConflict = -47,
236     SecureHwBusy = -48,
237     SecureHwCommunicationFailed = -49,
238     UnsupportedEcField = -50,
239     MissingNonce = -51,
240     InvalidNonce = -52,
241     MissingMacLength = -53,
242     KeyRateLimitExceeded = -54,
243     CallerNonceProhibited = -55,
244     KeyMaxOpsExceeded = -56,
245     InvalidMacLength = -57,
246     MissingMinMacLength = -58,
247     UnsupportedMinMacLength = -59,
248     UnsupportedKdf = -60,
249     UnsupportedEcCurve = -61,
250     KeyRequiresUpgrade = -62,
251     AttestationChallengeMissing = -63,
252     KeymintNotConfigured = -64,
253     AttestationApplicationIdMissing = -65,
254     CannotAttestIds = -66,
255     RollbackResistanceUnavailable = -67,
256     HardwareTypeUnavailable = -68,
257     ProofOfPresenceRequired = -69,
258     ConcurrentProofOfPresenceRequested = -70,
259     NoUserConfirmation = -71,
260     DeviceLocked = -72,
261     EarlyBootEnded = -73,
262     AttestationKeysNotProvisioned = -74,
263     AttestationIdsNotProvisioned = -75,
264     InvalidOperation = -76,
265     StorageKeyUnsupported = -77,
266     IncompatibleMgfDigest = -78,
267     UnsupportedMgfDigest = -79,
268     MissingNotBefore = -80,
269     MissingNotAfter = -81,
270     MissingIssuerSubject = -82,
271     InvalidIssuerSubject = -83,
272     BootLevelExceeded = -84,
273     HardwareNotYetAvailable = -85,
274     ModuleHashAlreadySet = -86,
275     Unimplemented = -100,
276     VersionMismatch = -101,
277     UnknownError = -1000,
278     // Implementer's namespace for error codes starts at -10000.
279     EncodingError = -20000,
280     BoringSslError = -30000,
281 }
282 try_from_n!(ErrorCode);
283 
284 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
285 pub struct HardwareAuthToken {
286     pub challenge: i64,
287     pub user_id: i64,
288     pub authenticator_id: i64,
289     pub authenticator_type: HardwareAuthenticatorType,
290     pub timestamp: super::secureclock::Timestamp,
291     pub mac: Vec<u8>,
292 }
293 
294 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
295 #[repr(i32)]
296 pub enum HardwareAuthenticatorType {
297     None = 0,
298     Password = 1,
299     Fingerprint = 2,
300     Any = -1,
301 }
302 try_from_n!(HardwareAuthenticatorType);
303 
304 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
305 pub struct KeyCharacteristics {
306     pub security_level: SecurityLevel,
307     pub authorizations: Vec<KeyParam>,
308 }
309 
310 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
311 pub struct KeyCreationResult {
312     pub key_blob: Vec<u8>,
313     pub key_characteristics: Vec<KeyCharacteristics>,
314     pub certificate_chain: Vec<Certificate>,
315 }
316 
317 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
318 #[repr(i32)]
319 pub enum KeyFormat {
320     X509 = 0,
321     Pkcs8 = 1,
322     Raw = 3,
323 }
324 try_from_n!(KeyFormat);
325 
326 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
327 pub struct KeyMintHardwareInfo {
328     pub version_number: i32,
329     pub security_level: SecurityLevel,
330     pub key_mint_name: String,
331     pub key_mint_author_name: String,
332     pub timestamp_token_required: bool,
333 }
334 
335 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
336 #[repr(i32)]
337 pub enum KeyOrigin {
338     Generated = 0,
339     Derived = 1,
340     Imported = 2,
341     Reserved = 3,
342     SecurelyImported = 4,
343 }
344 try_from_n!(KeyOrigin);
345 
346 /// Rust exhaustive enum for all key parameters.
347 #[derive(Clone, Debug, PartialEq, Eq)]
348 pub enum KeyParam {
349     Purpose(KeyPurpose),
350     Algorithm(Algorithm),
351     KeySize(KeySizeInBits),
352     BlockMode(BlockMode),
353     Digest(Digest),
354     Padding(PaddingMode),
355     CallerNonce,
356     MinMacLength(u32),
357     EcCurve(EcCurve),
358     RsaPublicExponent(RsaExponent),
359     IncludeUniqueId,
360     RsaOaepMgfDigest(Digest),
361     BootloaderOnly,
362     RollbackResistance,
363     EarlyBootOnly,
364     ActiveDatetime(DateTime),
365     OriginationExpireDatetime(DateTime),
366     UsageExpireDatetime(DateTime),
367     MaxUsesPerBoot(u32),
368     UsageCountLimit(u32),
369     UserId(u32),
370     UserSecureId(u64),
371     NoAuthRequired,
372     UserAuthType(u32),
373     AuthTimeout(u32),
374     AllowWhileOnBody,
375     TrustedUserPresenceRequired,
376     TrustedConfirmationRequired,
377     UnlockedDeviceRequired,
378     ApplicationId(Vec<u8>),
379     ApplicationData(Vec<u8>),
380     CreationDatetime(DateTime),
381     Origin(KeyOrigin),
382     RootOfTrust(Vec<u8>),
383     OsVersion(u32),
384     OsPatchlevel(u32),
385     AttestationChallenge(Vec<u8>),
386     AttestationApplicationId(Vec<u8>),
387     AttestationIdBrand(Vec<u8>),
388     AttestationIdDevice(Vec<u8>),
389     AttestationIdProduct(Vec<u8>),
390     AttestationIdSerial(Vec<u8>),
391     AttestationIdImei(Vec<u8>),
392     #[cfg(feature = "hal_v3")]
393     AttestationIdSecondImei(Vec<u8>),
394     AttestationIdMeid(Vec<u8>),
395     AttestationIdManufacturer(Vec<u8>),
396     AttestationIdModel(Vec<u8>),
397     VendorPatchlevel(u32),
398     BootPatchlevel(u32),
399     DeviceUniqueAttestation,
400     StorageKey,
401     Nonce(Vec<u8>),
402     MacLength(u32),
403     ResetSinceIdRotation,
404     CertificateSerial(Vec<u8>),
405     CertificateSubject(Vec<u8>),
406     CertificateNotBefore(DateTime),
407     CertificateNotAfter(DateTime),
408     MaxBootLevel(u32),
409     #[cfg(feature = "hal_v4")]
410     ModuleHash(Vec<u8>),
411 }
412 
413 impl KeyParam {
tag(&self) -> Tag414     pub fn tag(&self) -> Tag {
415         match self {
416             KeyParam::Algorithm(_) => Tag::Algorithm,
417             KeyParam::BlockMode(_) => Tag::BlockMode,
418             KeyParam::Padding(_) => Tag::Padding,
419             KeyParam::Digest(_) => Tag::Digest,
420             KeyParam::EcCurve(_) => Tag::EcCurve,
421             KeyParam::Origin(_) => Tag::Origin,
422             KeyParam::Purpose(_) => Tag::Purpose,
423             KeyParam::KeySize(_) => Tag::KeySize,
424             KeyParam::CallerNonce => Tag::CallerNonce,
425             KeyParam::MinMacLength(_) => Tag::MinMacLength,
426             KeyParam::RsaPublicExponent(_) => Tag::RsaPublicExponent,
427             KeyParam::IncludeUniqueId => Tag::IncludeUniqueId,
428             KeyParam::RsaOaepMgfDigest(_) => Tag::RsaOaepMgfDigest,
429             KeyParam::BootloaderOnly => Tag::BootloaderOnly,
430             KeyParam::RollbackResistance => Tag::RollbackResistance,
431             KeyParam::EarlyBootOnly => Tag::EarlyBootOnly,
432             KeyParam::ActiveDatetime(_) => Tag::ActiveDatetime,
433             KeyParam::OriginationExpireDatetime(_) => Tag::OriginationExpireDatetime,
434             KeyParam::UsageExpireDatetime(_) => Tag::UsageExpireDatetime,
435             KeyParam::MaxUsesPerBoot(_) => Tag::MaxUsesPerBoot,
436             KeyParam::UsageCountLimit(_) => Tag::UsageCountLimit,
437             KeyParam::UserId(_) => Tag::UserId,
438             KeyParam::UserSecureId(_) => Tag::UserSecureId,
439             KeyParam::NoAuthRequired => Tag::NoAuthRequired,
440             KeyParam::UserAuthType(_) => Tag::UserAuthType,
441             KeyParam::AuthTimeout(_) => Tag::AuthTimeout,
442             KeyParam::AllowWhileOnBody => Tag::AllowWhileOnBody,
443             KeyParam::TrustedUserPresenceRequired => Tag::TrustedUserPresenceRequired,
444             KeyParam::TrustedConfirmationRequired => Tag::TrustedConfirmationRequired,
445             KeyParam::UnlockedDeviceRequired => Tag::UnlockedDeviceRequired,
446             KeyParam::ApplicationId(_) => Tag::ApplicationId,
447             KeyParam::ApplicationData(_) => Tag::ApplicationData,
448             KeyParam::CreationDatetime(_) => Tag::CreationDatetime,
449             KeyParam::RootOfTrust(_) => Tag::RootOfTrust,
450             KeyParam::OsVersion(_) => Tag::OsVersion,
451             KeyParam::OsPatchlevel(_) => Tag::OsPatchlevel,
452             KeyParam::AttestationChallenge(_) => Tag::AttestationChallenge,
453             KeyParam::AttestationApplicationId(_) => Tag::AttestationApplicationId,
454             KeyParam::AttestationIdBrand(_) => Tag::AttestationIdBrand,
455             KeyParam::AttestationIdDevice(_) => Tag::AttestationIdDevice,
456             KeyParam::AttestationIdProduct(_) => Tag::AttestationIdProduct,
457             KeyParam::AttestationIdSerial(_) => Tag::AttestationIdSerial,
458             KeyParam::AttestationIdImei(_) => Tag::AttestationIdImei,
459             #[cfg(feature = "hal_v3")]
460             KeyParam::AttestationIdSecondImei(_) => Tag::AttestationIdSecondImei,
461             KeyParam::AttestationIdMeid(_) => Tag::AttestationIdMeid,
462             KeyParam::AttestationIdManufacturer(_) => Tag::AttestationIdManufacturer,
463             KeyParam::AttestationIdModel(_) => Tag::AttestationIdModel,
464             KeyParam::VendorPatchlevel(_) => Tag::VendorPatchlevel,
465             KeyParam::BootPatchlevel(_) => Tag::BootPatchlevel,
466             KeyParam::DeviceUniqueAttestation => Tag::DeviceUniqueAttestation,
467             KeyParam::StorageKey => Tag::StorageKey,
468             KeyParam::Nonce(_) => Tag::Nonce,
469             KeyParam::MacLength(_) => Tag::MacLength,
470             KeyParam::ResetSinceIdRotation => Tag::ResetSinceIdRotation,
471             KeyParam::CertificateSerial(_) => Tag::CertificateSerial,
472             KeyParam::CertificateSubject(_) => Tag::CertificateSubject,
473             KeyParam::CertificateNotBefore(_) => Tag::CertificateNotBefore,
474             KeyParam::CertificateNotAfter(_) => Tag::CertificateNotAfter,
475             KeyParam::MaxBootLevel(_) => Tag::MaxBootLevel,
476             #[cfg(feature = "hal_v4")]
477             KeyParam::ModuleHash(_) => Tag::ModuleHash,
478         }
479     }
480 }
481 
482 /// Check that a `bool` value is true (false values are represented by the absence of a tag).
check_bool(value: cbor::value::Value) -> Result<(), crate::CborError>483 fn check_bool(value: cbor::value::Value) -> Result<(), crate::CborError> {
484     match value {
485         cbor::value::Value::Bool(true) => Ok(()),
486         cbor::value::Value::Bool(false) => Err(crate::CborError::UnexpectedItem("false", "true")),
487         _ => crate::cbor_type_error(&value, "true"),
488     }
489 }
490 
491 /// Manual implementation of [`crate::AsCborValue`] for the [`KeyParam`] enum that
492 /// matches the serialization of the HAL `Tag` / `KeyParameterValue` types.
493 impl crate::AsCborValue for KeyParam {
from_cbor_value(value: cbor::value::Value) -> Result<Self, crate::CborError>494     fn from_cbor_value(value: cbor::value::Value) -> Result<Self, crate::CborError> {
495         let mut a = match value {
496             cbor::value::Value::Array(a) => a,
497             _ => return crate::cbor_type_error(&value, "arr"),
498         };
499         if a.len() != 2 {
500             return Err(crate::CborError::UnexpectedItem("arr", "arr len 2"));
501         }
502 
503         // Need to know the tag value to completely parse the value.
504         let raw = a.remove(1);
505         let tag = <Tag>::from_cbor_value(a.remove(0))?;
506 
507         Ok(match tag {
508             Tag::Algorithm => KeyParam::Algorithm(<Algorithm>::from_cbor_value(raw)?),
509             Tag::BlockMode => KeyParam::BlockMode(<BlockMode>::from_cbor_value(raw)?),
510             Tag::Padding => KeyParam::Padding(<PaddingMode>::from_cbor_value(raw)?),
511             Tag::Digest => KeyParam::Digest(<Digest>::from_cbor_value(raw)?),
512             Tag::EcCurve => KeyParam::EcCurve(<EcCurve>::from_cbor_value(raw)?),
513             Tag::Origin => KeyParam::Origin(<KeyOrigin>::from_cbor_value(raw)?),
514             Tag::Purpose => KeyParam::Purpose(<KeyPurpose>::from_cbor_value(raw)?),
515             Tag::KeySize => KeyParam::KeySize(<KeySizeInBits>::from_cbor_value(raw)?),
516             Tag::CallerNonce => KeyParam::CallerNonce,
517             Tag::MinMacLength => KeyParam::MinMacLength(<u32>::from_cbor_value(raw)?),
518             Tag::RsaPublicExponent => {
519                 KeyParam::RsaPublicExponent(<RsaExponent>::from_cbor_value(raw)?)
520             }
521             Tag::IncludeUniqueId => {
522                 check_bool(raw)?;
523                 KeyParam::IncludeUniqueId
524             }
525             Tag::RsaOaepMgfDigest => KeyParam::RsaOaepMgfDigest(<Digest>::from_cbor_value(raw)?),
526             Tag::BootloaderOnly => {
527                 check_bool(raw)?;
528                 KeyParam::BootloaderOnly
529             }
530             Tag::RollbackResistance => {
531                 check_bool(raw)?;
532                 KeyParam::RollbackResistance
533             }
534             Tag::EarlyBootOnly => {
535                 check_bool(raw)?;
536                 KeyParam::EarlyBootOnly
537             }
538             Tag::ActiveDatetime => KeyParam::ActiveDatetime(<DateTime>::from_cbor_value(raw)?),
539             Tag::OriginationExpireDatetime => {
540                 KeyParam::OriginationExpireDatetime(<DateTime>::from_cbor_value(raw)?)
541             }
542             Tag::UsageExpireDatetime => {
543                 KeyParam::UsageExpireDatetime(<DateTime>::from_cbor_value(raw)?)
544             }
545             Tag::MaxUsesPerBoot => KeyParam::MaxUsesPerBoot(<u32>::from_cbor_value(raw)?),
546             Tag::UsageCountLimit => KeyParam::UsageCountLimit(<u32>::from_cbor_value(raw)?),
547             Tag::UserId => KeyParam::UserId(<u32>::from_cbor_value(raw)?),
548             Tag::UserSecureId => KeyParam::UserSecureId(<u64>::from_cbor_value(raw)?),
549             Tag::NoAuthRequired => {
550                 check_bool(raw)?;
551                 KeyParam::NoAuthRequired
552             }
553             Tag::UserAuthType => KeyParam::UserAuthType(<u32>::from_cbor_value(raw)?),
554             Tag::AuthTimeout => KeyParam::AuthTimeout(<u32>::from_cbor_value(raw)?),
555             Tag::AllowWhileOnBody => KeyParam::AllowWhileOnBody,
556             Tag::TrustedUserPresenceRequired => {
557                 check_bool(raw)?;
558                 KeyParam::TrustedUserPresenceRequired
559             }
560             Tag::TrustedConfirmationRequired => {
561                 check_bool(raw)?;
562                 KeyParam::TrustedConfirmationRequired
563             }
564             Tag::UnlockedDeviceRequired => {
565                 check_bool(raw)?;
566                 KeyParam::UnlockedDeviceRequired
567             }
568             Tag::ApplicationId => KeyParam::ApplicationId(<Vec<u8>>::from_cbor_value(raw)?),
569             Tag::ApplicationData => KeyParam::ApplicationData(<Vec<u8>>::from_cbor_value(raw)?),
570             Tag::CreationDatetime => KeyParam::CreationDatetime(<DateTime>::from_cbor_value(raw)?),
571             Tag::RootOfTrust => KeyParam::RootOfTrust(<Vec<u8>>::from_cbor_value(raw)?),
572             Tag::OsVersion => KeyParam::OsVersion(<u32>::from_cbor_value(raw)?),
573             Tag::OsPatchlevel => KeyParam::OsPatchlevel(<u32>::from_cbor_value(raw)?),
574             Tag::AttestationChallenge => {
575                 KeyParam::AttestationChallenge(<Vec<u8>>::from_cbor_value(raw)?)
576             }
577             Tag::AttestationApplicationId => {
578                 KeyParam::AttestationApplicationId(<Vec<u8>>::from_cbor_value(raw)?)
579             }
580             Tag::AttestationIdBrand => {
581                 KeyParam::AttestationIdBrand(<Vec<u8>>::from_cbor_value(raw)?)
582             }
583             Tag::AttestationIdDevice => {
584                 KeyParam::AttestationIdDevice(<Vec<u8>>::from_cbor_value(raw)?)
585             }
586             Tag::AttestationIdProduct => {
587                 KeyParam::AttestationIdProduct(<Vec<u8>>::from_cbor_value(raw)?)
588             }
589             Tag::AttestationIdSerial => {
590                 KeyParam::AttestationIdSerial(<Vec<u8>>::from_cbor_value(raw)?)
591             }
592             Tag::AttestationIdImei => KeyParam::AttestationIdImei(<Vec<u8>>::from_cbor_value(raw)?),
593             #[cfg(feature = "hal_v3")]
594             Tag::AttestationIdSecondImei => {
595                 KeyParam::AttestationIdSecondImei(<Vec<u8>>::from_cbor_value(raw)?)
596             }
597             Tag::AttestationIdMeid => KeyParam::AttestationIdMeid(<Vec<u8>>::from_cbor_value(raw)?),
598             Tag::AttestationIdManufacturer => {
599                 KeyParam::AttestationIdManufacturer(<Vec<u8>>::from_cbor_value(raw)?)
600             }
601             Tag::AttestationIdModel => {
602                 KeyParam::AttestationIdModel(<Vec<u8>>::from_cbor_value(raw)?)
603             }
604             Tag::VendorPatchlevel => KeyParam::VendorPatchlevel(<u32>::from_cbor_value(raw)?),
605             Tag::BootPatchlevel => KeyParam::BootPatchlevel(<u32>::from_cbor_value(raw)?),
606             Tag::DeviceUniqueAttestation => {
607                 check_bool(raw)?;
608                 KeyParam::DeviceUniqueAttestation
609             }
610             Tag::StorageKey => KeyParam::StorageKey,
611             Tag::Nonce => KeyParam::Nonce(<Vec<u8>>::from_cbor_value(raw)?),
612             Tag::MacLength => KeyParam::MacLength(<u32>::from_cbor_value(raw)?),
613             Tag::ResetSinceIdRotation => {
614                 check_bool(raw)?;
615                 KeyParam::ResetSinceIdRotation
616             }
617             Tag::CertificateSerial => KeyParam::CertificateSerial(<Vec<u8>>::from_cbor_value(raw)?),
618             Tag::CertificateSubject => {
619                 KeyParam::CertificateSubject(<Vec<u8>>::from_cbor_value(raw)?)
620             }
621             Tag::CertificateNotBefore => {
622                 KeyParam::CertificateNotBefore(<DateTime>::from_cbor_value(raw)?)
623             }
624             Tag::CertificateNotAfter => {
625                 KeyParam::CertificateNotAfter(<DateTime>::from_cbor_value(raw)?)
626             }
627             Tag::MaxBootLevel => KeyParam::MaxBootLevel(<u32>::from_cbor_value(raw)?),
628             #[cfg(feature = "hal_v4")]
629             Tag::ModuleHash => KeyParam::ModuleHash(<Vec<u8>>::from_cbor_value(raw)?),
630 
631             _ => return Err(crate::CborError::UnexpectedItem("tag", "known tag")),
632         })
633     }
to_cbor_value(self) -> Result<cbor::value::Value, crate::CborError>634     fn to_cbor_value(self) -> Result<cbor::value::Value, crate::CborError> {
635         let (tag, val) = match self {
636             KeyParam::Algorithm(v) => (Tag::Algorithm, v.to_cbor_value()?),
637             KeyParam::BlockMode(v) => (Tag::BlockMode, v.to_cbor_value()?),
638             KeyParam::Padding(v) => (Tag::Padding, v.to_cbor_value()?),
639             KeyParam::Digest(v) => (Tag::Digest, v.to_cbor_value()?),
640             KeyParam::EcCurve(v) => (Tag::EcCurve, v.to_cbor_value()?),
641             KeyParam::Origin(v) => (Tag::Origin, v.to_cbor_value()?),
642             KeyParam::Purpose(v) => (Tag::Purpose, v.to_cbor_value()?),
643             KeyParam::KeySize(v) => (Tag::KeySize, v.to_cbor_value()?),
644             KeyParam::CallerNonce => (Tag::CallerNonce, true.to_cbor_value()?),
645             KeyParam::MinMacLength(v) => (Tag::MinMacLength, v.to_cbor_value()?),
646             KeyParam::RsaPublicExponent(v) => (Tag::RsaPublicExponent, v.to_cbor_value()?),
647             KeyParam::IncludeUniqueId => (Tag::IncludeUniqueId, true.to_cbor_value()?),
648             KeyParam::RsaOaepMgfDigest(v) => (Tag::RsaOaepMgfDigest, v.to_cbor_value()?),
649             KeyParam::BootloaderOnly => (Tag::BootloaderOnly, true.to_cbor_value()?),
650             KeyParam::RollbackResistance => (Tag::RollbackResistance, true.to_cbor_value()?),
651             KeyParam::EarlyBootOnly => (Tag::EarlyBootOnly, true.to_cbor_value()?),
652             KeyParam::ActiveDatetime(v) => (Tag::ActiveDatetime, v.to_cbor_value()?),
653             KeyParam::OriginationExpireDatetime(v) => {
654                 (Tag::OriginationExpireDatetime, v.to_cbor_value()?)
655             }
656             KeyParam::UsageExpireDatetime(v) => (Tag::UsageExpireDatetime, v.to_cbor_value()?),
657             KeyParam::MaxUsesPerBoot(v) => (Tag::MaxUsesPerBoot, v.to_cbor_value()?),
658             KeyParam::UsageCountLimit(v) => (Tag::UsageCountLimit, v.to_cbor_value()?),
659             KeyParam::UserId(v) => (Tag::UserId, v.to_cbor_value()?),
660             KeyParam::UserSecureId(v) => (Tag::UserSecureId, v.to_cbor_value()?),
661             KeyParam::NoAuthRequired => (Tag::NoAuthRequired, true.to_cbor_value()?),
662             KeyParam::UserAuthType(v) => (Tag::UserAuthType, v.to_cbor_value()?),
663             KeyParam::AuthTimeout(v) => (Tag::AuthTimeout, v.to_cbor_value()?),
664             KeyParam::AllowWhileOnBody => (Tag::AllowWhileOnBody, true.to_cbor_value()?),
665             KeyParam::TrustedUserPresenceRequired => {
666                 (Tag::TrustedUserPresenceRequired, true.to_cbor_value()?)
667             }
668             KeyParam::TrustedConfirmationRequired => {
669                 (Tag::TrustedConfirmationRequired, true.to_cbor_value()?)
670             }
671             KeyParam::UnlockedDeviceRequired => {
672                 (Tag::UnlockedDeviceRequired, true.to_cbor_value()?)
673             }
674             KeyParam::ApplicationId(v) => (Tag::ApplicationId, v.to_cbor_value()?),
675             KeyParam::ApplicationData(v) => (Tag::ApplicationData, v.to_cbor_value()?),
676             KeyParam::CreationDatetime(v) => (Tag::CreationDatetime, v.to_cbor_value()?),
677             KeyParam::RootOfTrust(v) => (Tag::RootOfTrust, v.to_cbor_value()?),
678             KeyParam::OsVersion(v) => (Tag::OsVersion, v.to_cbor_value()?),
679             KeyParam::OsPatchlevel(v) => (Tag::OsPatchlevel, v.to_cbor_value()?),
680             KeyParam::AttestationChallenge(v) => (Tag::AttestationChallenge, v.to_cbor_value()?),
681             KeyParam::AttestationApplicationId(v) => {
682                 (Tag::AttestationApplicationId, v.to_cbor_value()?)
683             }
684             KeyParam::AttestationIdBrand(v) => (Tag::AttestationIdBrand, v.to_cbor_value()?),
685             KeyParam::AttestationIdDevice(v) => (Tag::AttestationIdDevice, v.to_cbor_value()?),
686             KeyParam::AttestationIdProduct(v) => (Tag::AttestationIdProduct, v.to_cbor_value()?),
687             KeyParam::AttestationIdSerial(v) => (Tag::AttestationIdSerial, v.to_cbor_value()?),
688             KeyParam::AttestationIdImei(v) => (Tag::AttestationIdImei, v.to_cbor_value()?),
689             #[cfg(feature = "hal_v3")]
690             KeyParam::AttestationIdSecondImei(v) => {
691                 (Tag::AttestationIdSecondImei, v.to_cbor_value()?)
692             }
693             KeyParam::AttestationIdMeid(v) => (Tag::AttestationIdMeid, v.to_cbor_value()?),
694             KeyParam::AttestationIdManufacturer(v) => {
695                 (Tag::AttestationIdManufacturer, v.to_cbor_value()?)
696             }
697             KeyParam::AttestationIdModel(v) => (Tag::AttestationIdModel, v.to_cbor_value()?),
698             KeyParam::VendorPatchlevel(v) => (Tag::VendorPatchlevel, v.to_cbor_value()?),
699             KeyParam::BootPatchlevel(v) => (Tag::BootPatchlevel, v.to_cbor_value()?),
700             KeyParam::DeviceUniqueAttestation => {
701                 (Tag::DeviceUniqueAttestation, true.to_cbor_value()?)
702             }
703             KeyParam::StorageKey => (Tag::StorageKey, true.to_cbor_value()?),
704             KeyParam::Nonce(v) => (Tag::Nonce, v.to_cbor_value()?),
705             KeyParam::MacLength(v) => (Tag::MacLength, v.to_cbor_value()?),
706             KeyParam::ResetSinceIdRotation => (Tag::ResetSinceIdRotation, true.to_cbor_value()?),
707             KeyParam::CertificateSerial(v) => (Tag::CertificateSerial, v.to_cbor_value()?),
708             KeyParam::CertificateSubject(v) => (Tag::CertificateSubject, v.to_cbor_value()?),
709             KeyParam::CertificateNotBefore(v) => (Tag::CertificateNotBefore, v.to_cbor_value()?),
710             KeyParam::CertificateNotAfter(v) => (Tag::CertificateNotAfter, v.to_cbor_value()?),
711             KeyParam::MaxBootLevel(v) => (Tag::MaxBootLevel, v.to_cbor_value()?),
712             #[cfg(feature = "hal_v4")]
713             KeyParam::ModuleHash(v) => (Tag::ModuleHash, v.to_cbor_value()?),
714         };
715         Ok(cbor::value::Value::Array(vec_try![tag.to_cbor_value()?, val]?))
716     }
cddl_typename() -> Option<String>717     fn cddl_typename() -> Option<String> {
718         Some("KeyParam".to_string())
719     }
cddl_schema() -> Option<String>720     fn cddl_schema() -> Option<String> {
721         let mut result = "&(\n".to_string();
722 
723         result += &format!(
724             "    [{}, {}], ; {}\n",
725             Tag::Algorithm as i32,
726             Algorithm::cddl_ref(),
727             "Tag_Algorithm"
728         );
729         result += &format!(
730             "    [{}, {}], ; {}\n",
731             Tag::BlockMode as i32,
732             BlockMode::cddl_ref(),
733             "Tag_BlockMode",
734         );
735         result += &format!(
736             "    [{}, {}], ; {}\n",
737             Tag::Padding as i32,
738             PaddingMode::cddl_ref(),
739             "Tag_Padding",
740         );
741         result +=
742             &format!("    [{}, {}], ; {}\n", Tag::Digest as i32, Digest::cddl_ref(), "Tag_Digest",);
743         result += &format!(
744             "    [{}, {}], ; {}\n",
745             Tag::EcCurve as i32,
746             EcCurve::cddl_ref(),
747             "Tag_EcCurve",
748         );
749         result += &format!(
750             "    [{}, {}], ; {}\n",
751             Tag::Origin as i32,
752             KeyOrigin::cddl_ref(),
753             "Tag_Origin",
754         );
755         result += &format!(
756             "    [{}, {}], ; {}\n",
757             Tag::Purpose as i32,
758             KeyPurpose::cddl_ref(),
759             "Tag_Purpose",
760         );
761         result += &format!(
762             "    [{}, {}], ; {}\n",
763             Tag::KeySize as i32,
764             KeySizeInBits::cddl_ref(),
765             "Tag_KeySize",
766         );
767         result += &format!(
768             "    [{}, {}], ; {}\n",
769             Tag::CallerNonce as i32,
770             Vec::<u8>::cddl_ref(),
771             "Tag_CallerNonce",
772         );
773         result += &format!(
774             "    [{}, {}], ; {}\n",
775             Tag::MinMacLength as i32,
776             u32::cddl_ref(),
777             "Tag_MinMacLength",
778         );
779         result += &format!(
780             "    [{}, {}], ; {}\n",
781             Tag::RsaPublicExponent as i32,
782             RsaExponent::cddl_ref(),
783             "Tag_RsaPublicExponent",
784         );
785         result += &format!(
786             "    [{}, {}], ; {}\n",
787             Tag::IncludeUniqueId as i32,
788             "true",
789             "Tag_IncludeUniqueId",
790         );
791         result += &format!(
792             "    [{}, {}], ; {}\n",
793             Tag::RsaOaepMgfDigest as i32,
794             Digest::cddl_ref(),
795             "Tag_RsaOaepMgfDigest",
796         );
797         result += &format!(
798             "    [{}, {}], ; {}\n",
799             Tag::BootloaderOnly as i32,
800             "true",
801             "Tag_BootloaderOnly",
802         );
803         result += &format!(
804             "    [{}, {}], ; {}\n",
805             Tag::RollbackResistance as i32,
806             "true",
807             "Tag_RollbackResistance",
808         );
809         result += &format!(
810             "    [{}, {}], ; {}\n",
811             Tag::EarlyBootOnly as i32,
812             "true",
813             "Tag_EarlyBootOnly",
814         );
815         result += &format!(
816             "    [{}, {}], ; {}\n",
817             Tag::ActiveDatetime as i32,
818             DateTime::cddl_ref(),
819             "Tag_ActiveDatetime",
820         );
821         result += &format!(
822             "    [{}, {}], ; {}\n",
823             Tag::OriginationExpireDatetime as i32,
824             DateTime::cddl_ref(),
825             "Tag_OriginationExpireDatetime",
826         );
827         result += &format!(
828             "    [{}, {}], ; {}\n",
829             Tag::UsageExpireDatetime as i32,
830             DateTime::cddl_ref(),
831             "Tag_UsageExpireDatetime",
832         );
833         result += &format!(
834             "    [{}, {}], ; {}\n",
835             Tag::MaxUsesPerBoot as i32,
836             u32::cddl_ref(),
837             "Tag_MaxUsesPerBoot",
838         );
839         result += &format!(
840             "    [{}, {}], ; {}\n",
841             Tag::UsageCountLimit as i32,
842             u32::cddl_ref(),
843             "Tag_UsageCountLimit",
844         );
845         result +=
846             &format!("    [{}, {}], ; {}\n", Tag::UserId as i32, u32::cddl_ref(), "Tag_UserId",);
847         result += &format!(
848             "    [{}, {}], ; {}\n",
849             Tag::UserSecureId as i32,
850             u64::cddl_ref(),
851             "Tag_UserSecureId",
852         );
853         result += &format!(
854             "    [{}, {}], ; {}\n",
855             Tag::NoAuthRequired as i32,
856             "true",
857             "Tag_NoAuthRequired",
858         );
859         result += &format!(
860             "    [{}, {}], ; {}\n",
861             Tag::UserAuthType as i32,
862             u32::cddl_ref(),
863             "Tag_UserAuthType",
864         );
865         result += &format!(
866             "    [{}, {}], ; {}\n",
867             Tag::AuthTimeout as i32,
868             u32::cddl_ref(),
869             "Tag_AuthTimeout",
870         );
871         result += &format!(
872             "    [{}, {}], ; {}\n",
873             Tag::AllowWhileOnBody as i32,
874             "true",
875             "Tag_AllowWhileOnBody",
876         );
877         result += &format!(
878             "    [{}, {}], ; {}\n",
879             Tag::TrustedUserPresenceRequired as i32,
880             "true",
881             "Tag_TrustedUserPresenceRequired",
882         );
883         result += &format!(
884             "    [{}, {}], ; {}\n",
885             Tag::TrustedConfirmationRequired as i32,
886             "true",
887             "Tag_TrustedConfirmationRequired",
888         );
889         result += &format!(
890             "    [{}, {}], ; {}\n",
891             Tag::UnlockedDeviceRequired as i32,
892             "true",
893             "Tag_UnlockedDeviceRequired",
894         );
895         result += &format!(
896             "    [{}, {}], ; {}\n",
897             Tag::ApplicationId as i32,
898             Vec::<u8>::cddl_ref(),
899             "Tag_ApplicationId",
900         );
901         result += &format!(
902             "    [{}, {}], ; {}\n",
903             Tag::ApplicationData as i32,
904             Vec::<u8>::cddl_ref(),
905             "Tag_ApplicationData",
906         );
907         result += &format!(
908             "    [{}, {}], ; {}\n",
909             Tag::CreationDatetime as i32,
910             DateTime::cddl_ref(),
911             "Tag_CreationDatetime",
912         );
913         result += &format!(
914             "    [{}, {}], ; {}\n",
915             Tag::RootOfTrust as i32,
916             Vec::<u8>::cddl_ref(),
917             "Tag_RootOfTrust",
918         );
919         result += &format!(
920             "    [{}, {}], ; {}\n",
921             Tag::OsVersion as i32,
922             u32::cddl_ref(),
923             "Tag_OsVersion",
924         );
925         result += &format!(
926             "    [{}, {}], ; {}\n",
927             Tag::OsPatchlevel as i32,
928             u32::cddl_ref(),
929             "Tag_OsPatchlevel",
930         );
931         result += &format!(
932             "    [{}, {}], ; {}\n",
933             Tag::AttestationChallenge as i32,
934             Vec::<u8>::cddl_ref(),
935             "Tag_AttestationChallenge",
936         );
937         result += &format!(
938             "    [{}, {}], ; {}\n",
939             Tag::AttestationApplicationId as i32,
940             Vec::<u8>::cddl_ref(),
941             "Tag_AttestationApplicationId",
942         );
943         result += &format!(
944             "    [{}, {}], ; {}\n",
945             Tag::AttestationIdBrand as i32,
946             Vec::<u8>::cddl_ref(),
947             "Tag_AttestationIdBrand",
948         );
949         result += &format!(
950             "    [{}, {}], ; {}\n",
951             Tag::AttestationIdDevice as i32,
952             Vec::<u8>::cddl_ref(),
953             "Tag_AttestationIdDevice",
954         );
955         result += &format!(
956             "    [{}, {}], ; {}\n",
957             Tag::AttestationIdProduct as i32,
958             Vec::<u8>::cddl_ref(),
959             "Tag_AttestationIdProduct",
960         );
961         result += &format!(
962             "    [{}, {}], ; {}\n",
963             Tag::AttestationIdSerial as i32,
964             Vec::<u8>::cddl_ref(),
965             "Tag_AttestationIdSerial",
966         );
967         result += &format!(
968             "    [{}, {}], ; {}\n",
969             Tag::AttestationIdImei as i32,
970             Vec::<u8>::cddl_ref(),
971             "Tag_AttestationIdImei",
972         );
973         #[cfg(feature = "hal_v3")]
974         {
975             result += &format!(
976                 "    [{}, {}], ; {}\n",
977                 Tag::AttestationIdSecondImei as i32,
978                 Vec::<u8>::cddl_ref(),
979                 "Tag_AttestationIdSecondImei",
980             );
981         }
982         result += &format!(
983             "    [{}, {}], ; {}\n",
984             Tag::AttestationIdMeid as i32,
985             Vec::<u8>::cddl_ref(),
986             "Tag_AttestationIdMeid",
987         );
988         result += &format!(
989             "    [{}, {}], ; {}\n",
990             Tag::AttestationIdManufacturer as i32,
991             Vec::<u8>::cddl_ref(),
992             "Tag_AttestationIdManufacturer",
993         );
994         result += &format!(
995             "    [{}, {}], ; {}\n",
996             Tag::AttestationIdModel as i32,
997             Vec::<u8>::cddl_ref(),
998             "Tag_AttestationIdModel",
999         );
1000         result += &format!(
1001             "    [{}, {}], ; {}\n",
1002             Tag::VendorPatchlevel as i32,
1003             u32::cddl_ref(),
1004             "Tag_VendorPatchlevel",
1005         );
1006         result += &format!(
1007             "    [{}, {}], ; {}\n",
1008             Tag::BootPatchlevel as i32,
1009             u32::cddl_ref(),
1010             "Tag_BootPatchlevel",
1011         );
1012         result += &format!(
1013             "    [{}, {}], ; {}\n",
1014             Tag::DeviceUniqueAttestation as i32,
1015             "true",
1016             "Tag_DeviceUniqueAttestation",
1017         );
1018         result +=
1019             &format!("    [{}, {}], ; {}\n", Tag::StorageKey as i32, "true", "Tag_StorageKey",);
1020         result += &format!(
1021             "    [{}, {}], ; {}\n",
1022             Tag::Nonce as i32,
1023             Vec::<u8>::cddl_ref(),
1024             "Tag_Nonce",
1025         );
1026         result += &format!(
1027             "    [{}, {}], ; {}\n",
1028             Tag::MacLength as i32,
1029             u32::cddl_ref(),
1030             "Tag_MacLength",
1031         );
1032         result += &format!(
1033             "    [{}, {}], ; {}\n",
1034             Tag::ResetSinceIdRotation as i32,
1035             "true",
1036             "Tag_ResetSinceIdRotation",
1037         );
1038         result += &format!(
1039             "    [{}, {}], ; {}\n",
1040             Tag::CertificateSerial as i32,
1041             Vec::<u8>::cddl_ref(),
1042             "Tag_CertificateSerial",
1043         );
1044         result += &format!(
1045             "    [{}, {}], ; {}\n",
1046             Tag::CertificateSubject as i32,
1047             Vec::<u8>::cddl_ref(),
1048             "Tag_CertificateSubject",
1049         );
1050         result += &format!(
1051             "    [{}, {}], ; {}\n",
1052             Tag::CertificateNotBefore as i32,
1053             DateTime::cddl_ref(),
1054             "Tag_CertificateNotBefore",
1055         );
1056         result += &format!(
1057             "    [{}, {}], ; {}\n",
1058             Tag::CertificateNotAfter as i32,
1059             DateTime::cddl_ref(),
1060             "Tag_CertificateNotAfter",
1061         );
1062         result += &format!(
1063             "    [{}, {}], ; {}\n",
1064             Tag::MaxBootLevel as i32,
1065             u32::cddl_ref(),
1066             "Tag_MaxBootLevel",
1067         );
1068         #[cfg(feature = "hal_v4")]
1069         {
1070             result += &format!(
1071                 "    [{}, {}], ; {}\n",
1072                 Tag::ModuleHash as i32,
1073                 Vec::<u8>::cddl_ref(),
1074                 "Tag_ModuleHash",
1075             );
1076         }
1077         result += ")";
1078         Some(result)
1079     }
1080 }
1081 
1082 /// Determine the tag type for a tag, based on the top 4 bits of the tag number.
tag_type(tag: Tag) -> TagType1083 pub fn tag_type(tag: Tag) -> TagType {
1084     match ((tag as u32) & 0xf0000000u32) as i32 {
1085         x if x == TagType::Enum as i32 => TagType::Enum,
1086         x if x == TagType::EnumRep as i32 => TagType::EnumRep,
1087         x if x == TagType::Uint as i32 => TagType::Uint,
1088         x if x == TagType::UintRep as i32 => TagType::UintRep,
1089         x if x == TagType::Ulong as i32 => TagType::Ulong,
1090         x if x == TagType::Date as i32 => TagType::Date,
1091         x if x == TagType::Bool as i32 => TagType::Bool,
1092         x if x == TagType::Bignum as i32 => TagType::Bignum,
1093         x if x == TagType::Bytes as i32 => TagType::Bytes,
1094         x if x == TagType::UlongRep as i32 => TagType::UlongRep,
1095         _ => TagType::Invalid,
1096     }
1097 }
1098 
1099 /// Determine the raw tag value with tag type information stripped out.
raw_tag_value(tag: Tag) -> u321100 pub fn raw_tag_value(tag: Tag) -> u32 {
1101     (tag as u32) & 0x0fffffffu32
1102 }
1103 
1104 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1105 #[repr(i32)]
1106 pub enum KeyPurpose {
1107     Encrypt = 0,
1108     Decrypt = 1,
1109     Sign = 2,
1110     Verify = 3,
1111     WrapKey = 5,
1112     AgreeKey = 6,
1113     AttestKey = 7,
1114 }
1115 try_from_n!(KeyPurpose);
1116 
1117 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1118 #[repr(i32)]
1119 pub enum PaddingMode {
1120     None = 1,
1121     RsaOaep = 2,
1122     RsaPss = 3,
1123     RsaPkcs115Encrypt = 4,
1124     RsaPkcs115Sign = 5,
1125     Pkcs7 = 64,
1126 }
1127 try_from_n!(PaddingMode);
1128 
1129 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1130 #[repr(i32)]
1131 pub enum SecurityLevel {
1132     Software = 0,
1133     TrustedEnvironment = 1,
1134     Strongbox = 2,
1135     Keystore = 100,
1136 }
1137 try_from_n!(SecurityLevel);
1138 
1139 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, FromRawTag, N)]
1140 #[repr(i32)]
1141 pub enum Tag {
1142     Invalid = 0,
1143     Purpose = 536870913,
1144     Algorithm = 268435458,
1145     KeySize = 805306371,
1146     BlockMode = 536870916,
1147     Digest = 536870917,
1148     Padding = 536870918,
1149     CallerNonce = 1879048199,
1150     MinMacLength = 805306376,
1151     EcCurve = 268435466,
1152     RsaPublicExponent = 1342177480,
1153     IncludeUniqueId = 1879048394,
1154     RsaOaepMgfDigest = 536871115,
1155     BootloaderOnly = 1879048494,
1156     RollbackResistance = 1879048495,
1157     HardwareType = 268435760,
1158     EarlyBootOnly = 1879048497,
1159     ActiveDatetime = 1610613136,
1160     OriginationExpireDatetime = 1610613137,
1161     UsageExpireDatetime = 1610613138,
1162     MinSecondsBetweenOps = 805306771,
1163     MaxUsesPerBoot = 805306772,
1164     UsageCountLimit = 805306773,
1165     UserId = 805306869,
1166     UserSecureId = -1610612234,
1167     NoAuthRequired = 1879048695,
1168     UserAuthType = 268435960,
1169     AuthTimeout = 805306873,
1170     AllowWhileOnBody = 1879048698,
1171     TrustedUserPresenceRequired = 1879048699,
1172     TrustedConfirmationRequired = 1879048700,
1173     UnlockedDeviceRequired = 1879048701,
1174     ApplicationId = -1879047591,
1175     ApplicationData = -1879047492,
1176     CreationDatetime = 1610613437,
1177     Origin = 268436158,
1178     RootOfTrust = -1879047488,
1179     OsVersion = 805307073,
1180     OsPatchlevel = 805307074,
1181     UniqueId = -1879047485,
1182     AttestationChallenge = -1879047484,
1183     AttestationApplicationId = -1879047483,
1184     AttestationIdBrand = -1879047482,
1185     AttestationIdDevice = -1879047481,
1186     AttestationIdProduct = -1879047480,
1187     AttestationIdSerial = -1879047479,
1188     AttestationIdImei = -1879047478,
1189     AttestationIdMeid = -1879047477,
1190     AttestationIdManufacturer = -1879047476,
1191     AttestationIdModel = -1879047475,
1192     VendorPatchlevel = 805307086,
1193     BootPatchlevel = 805307087,
1194     DeviceUniqueAttestation = 1879048912,
1195     IdentityCredentialKey = 1879048913,
1196     StorageKey = 1879048914,
1197     #[cfg(feature = "hal_v3")]
1198     AttestationIdSecondImei = -1879047469,
1199     AssociatedData = -1879047192,
1200     Nonce = -1879047191,
1201     MacLength = 805307371,
1202     ResetSinceIdRotation = 1879049196,
1203     ConfirmationToken = -1879047187,
1204     CertificateSerial = -2147482642,
1205     CertificateSubject = -1879047185,
1206     CertificateNotBefore = 1610613744,
1207     CertificateNotAfter = 1610613745,
1208     MaxBootLevel = 805307378,
1209     #[cfg(feature = "hal_v4")]
1210     ModuleHash = -1879047468,
1211 }
1212 try_from_n!(Tag);
1213 
1214 #[derive(Clone, Copy, Debug, PartialEq, Eq, AsCborValue, N)]
1215 #[repr(i32)]
1216 pub enum TagType {
1217     Invalid = 0,
1218     Enum = 268435456,
1219     EnumRep = 536870912,
1220     Uint = 805306368,
1221     UintRep = 1073741824,
1222     Ulong = 1342177280,
1223     Date = 1610612736,
1224     Bool = 1879048192,
1225     Bignum = -2147483648,
1226     Bytes = -1879048192,
1227     UlongRep = -1610612736,
1228 }
1229 try_from_n!(TagType);
1230