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     Unimplemented = -100,
275     VersionMismatch = -101,
276     UnknownError = -1000,
277     // Implementer's namespace for error codes starts at -10000.
278     EncodingError = -20000,
279     BoringSslError = -30000,
280 }
281 try_from_n!(ErrorCode);
282 
283 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
284 pub struct HardwareAuthToken {
285     pub challenge: i64,
286     pub user_id: i64,
287     pub authenticator_id: i64,
288     pub authenticator_type: HardwareAuthenticatorType,
289     pub timestamp: super::secureclock::Timestamp,
290     pub mac: Vec<u8>,
291 }
292 
293 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
294 #[repr(i32)]
295 pub enum HardwareAuthenticatorType {
296     None = 0,
297     Password = 1,
298     Fingerprint = 2,
299     Any = -1,
300 }
301 try_from_n!(HardwareAuthenticatorType);
302 
303 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
304 pub struct KeyCharacteristics {
305     pub security_level: SecurityLevel,
306     pub authorizations: Vec<KeyParam>,
307 }
308 
309 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
310 pub struct KeyCreationResult {
311     pub key_blob: Vec<u8>,
312     pub key_characteristics: Vec<KeyCharacteristics>,
313     pub certificate_chain: Vec<Certificate>,
314 }
315 
316 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
317 #[repr(i32)]
318 pub enum KeyFormat {
319     X509 = 0,
320     Pkcs8 = 1,
321     Raw = 3,
322 }
323 try_from_n!(KeyFormat);
324 
325 #[derive(Clone, Debug, Eq, PartialEq, AsCborValue)]
326 pub struct KeyMintHardwareInfo {
327     pub version_number: i32,
328     pub security_level: SecurityLevel,
329     pub key_mint_name: String,
330     pub key_mint_author_name: String,
331     pub timestamp_token_required: bool,
332 }
333 
334 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
335 #[repr(i32)]
336 pub enum KeyOrigin {
337     Generated = 0,
338     Derived = 1,
339     Imported = 2,
340     Reserved = 3,
341     SecurelyImported = 4,
342 }
343 try_from_n!(KeyOrigin);
344 
345 /// Rust exhaustive enum for all key parameters.
346 #[derive(Clone, Debug, PartialEq, Eq)]
347 pub enum KeyParam {
348     Purpose(KeyPurpose),
349     Algorithm(Algorithm),
350     KeySize(KeySizeInBits),
351     BlockMode(BlockMode),
352     Digest(Digest),
353     Padding(PaddingMode),
354     CallerNonce,
355     MinMacLength(u32),
356     EcCurve(EcCurve),
357     RsaPublicExponent(RsaExponent),
358     IncludeUniqueId,
359     RsaOaepMgfDigest(Digest),
360     BootloaderOnly,
361     RollbackResistance,
362     EarlyBootOnly,
363     ActiveDatetime(DateTime),
364     OriginationExpireDatetime(DateTime),
365     UsageExpireDatetime(DateTime),
366     MaxUsesPerBoot(u32),
367     UsageCountLimit(u32),
368     UserId(u32),
369     UserSecureId(u64),
370     NoAuthRequired,
371     UserAuthType(u32),
372     AuthTimeout(u32),
373     AllowWhileOnBody,
374     TrustedUserPresenceRequired,
375     TrustedConfirmationRequired,
376     UnlockedDeviceRequired,
377     ApplicationId(Vec<u8>),
378     ApplicationData(Vec<u8>),
379     CreationDatetime(DateTime),
380     Origin(KeyOrigin),
381     RootOfTrust(Vec<u8>),
382     OsVersion(u32),
383     OsPatchlevel(u32),
384     AttestationChallenge(Vec<u8>),
385     AttestationApplicationId(Vec<u8>),
386     AttestationIdBrand(Vec<u8>),
387     AttestationIdDevice(Vec<u8>),
388     AttestationIdProduct(Vec<u8>),
389     AttestationIdSerial(Vec<u8>),
390     AttestationIdImei(Vec<u8>),
391     #[cfg(feature = "hal_v3")]
392     AttestationIdSecondImei(Vec<u8>),
393     AttestationIdMeid(Vec<u8>),
394     AttestationIdManufacturer(Vec<u8>),
395     AttestationIdModel(Vec<u8>),
396     VendorPatchlevel(u32),
397     BootPatchlevel(u32),
398     DeviceUniqueAttestation,
399     StorageKey,
400     Nonce(Vec<u8>),
401     MacLength(u32),
402     ResetSinceIdRotation,
403     CertificateSerial(Vec<u8>),
404     CertificateSubject(Vec<u8>),
405     CertificateNotBefore(DateTime),
406     CertificateNotAfter(DateTime),
407     MaxBootLevel(u32),
408 }
409 
410 impl KeyParam {
tag(&self) -> Tag411     pub fn tag(&self) -> Tag {
412         match self {
413             KeyParam::Algorithm(_) => Tag::Algorithm,
414             KeyParam::BlockMode(_) => Tag::BlockMode,
415             KeyParam::Padding(_) => Tag::Padding,
416             KeyParam::Digest(_) => Tag::Digest,
417             KeyParam::EcCurve(_) => Tag::EcCurve,
418             KeyParam::Origin(_) => Tag::Origin,
419             KeyParam::Purpose(_) => Tag::Purpose,
420             KeyParam::KeySize(_) => Tag::KeySize,
421             KeyParam::CallerNonce => Tag::CallerNonce,
422             KeyParam::MinMacLength(_) => Tag::MinMacLength,
423             KeyParam::RsaPublicExponent(_) => Tag::RsaPublicExponent,
424             KeyParam::IncludeUniqueId => Tag::IncludeUniqueId,
425             KeyParam::RsaOaepMgfDigest(_) => Tag::RsaOaepMgfDigest,
426             KeyParam::BootloaderOnly => Tag::BootloaderOnly,
427             KeyParam::RollbackResistance => Tag::RollbackResistance,
428             KeyParam::EarlyBootOnly => Tag::EarlyBootOnly,
429             KeyParam::ActiveDatetime(_) => Tag::ActiveDatetime,
430             KeyParam::OriginationExpireDatetime(_) => Tag::OriginationExpireDatetime,
431             KeyParam::UsageExpireDatetime(_) => Tag::UsageExpireDatetime,
432             KeyParam::MaxUsesPerBoot(_) => Tag::MaxUsesPerBoot,
433             KeyParam::UsageCountLimit(_) => Tag::UsageCountLimit,
434             KeyParam::UserId(_) => Tag::UserId,
435             KeyParam::UserSecureId(_) => Tag::UserSecureId,
436             KeyParam::NoAuthRequired => Tag::NoAuthRequired,
437             KeyParam::UserAuthType(_) => Tag::UserAuthType,
438             KeyParam::AuthTimeout(_) => Tag::AuthTimeout,
439             KeyParam::AllowWhileOnBody => Tag::AllowWhileOnBody,
440             KeyParam::TrustedUserPresenceRequired => Tag::TrustedUserPresenceRequired,
441             KeyParam::TrustedConfirmationRequired => Tag::TrustedConfirmationRequired,
442             KeyParam::UnlockedDeviceRequired => Tag::UnlockedDeviceRequired,
443             KeyParam::ApplicationId(_) => Tag::ApplicationId,
444             KeyParam::ApplicationData(_) => Tag::ApplicationData,
445             KeyParam::CreationDatetime(_) => Tag::CreationDatetime,
446             KeyParam::RootOfTrust(_) => Tag::RootOfTrust,
447             KeyParam::OsVersion(_) => Tag::OsVersion,
448             KeyParam::OsPatchlevel(_) => Tag::OsPatchlevel,
449             KeyParam::AttestationChallenge(_) => Tag::AttestationChallenge,
450             KeyParam::AttestationApplicationId(_) => Tag::AttestationApplicationId,
451             KeyParam::AttestationIdBrand(_) => Tag::AttestationIdBrand,
452             KeyParam::AttestationIdDevice(_) => Tag::AttestationIdDevice,
453             KeyParam::AttestationIdProduct(_) => Tag::AttestationIdProduct,
454             KeyParam::AttestationIdSerial(_) => Tag::AttestationIdSerial,
455             KeyParam::AttestationIdImei(_) => Tag::AttestationIdImei,
456             #[cfg(feature = "hal_v3")]
457             KeyParam::AttestationIdSecondImei(_) => Tag::AttestationIdSecondImei,
458             KeyParam::AttestationIdMeid(_) => Tag::AttestationIdMeid,
459             KeyParam::AttestationIdManufacturer(_) => Tag::AttestationIdManufacturer,
460             KeyParam::AttestationIdModel(_) => Tag::AttestationIdModel,
461             KeyParam::VendorPatchlevel(_) => Tag::VendorPatchlevel,
462             KeyParam::BootPatchlevel(_) => Tag::BootPatchlevel,
463             KeyParam::DeviceUniqueAttestation => Tag::DeviceUniqueAttestation,
464             KeyParam::StorageKey => Tag::StorageKey,
465             KeyParam::Nonce(_) => Tag::Nonce,
466             KeyParam::MacLength(_) => Tag::MacLength,
467             KeyParam::ResetSinceIdRotation => Tag::ResetSinceIdRotation,
468             KeyParam::CertificateSerial(_) => Tag::CertificateSerial,
469             KeyParam::CertificateSubject(_) => Tag::CertificateSubject,
470             KeyParam::CertificateNotBefore(_) => Tag::CertificateNotBefore,
471             KeyParam::CertificateNotAfter(_) => Tag::CertificateNotAfter,
472             KeyParam::MaxBootLevel(_) => Tag::MaxBootLevel,
473         }
474     }
475 }
476 
477 /// 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>478 fn check_bool(value: cbor::value::Value) -> Result<(), crate::CborError> {
479     match value {
480         cbor::value::Value::Bool(true) => Ok(()),
481         cbor::value::Value::Bool(false) => Err(crate::CborError::UnexpectedItem("false", "true")),
482         _ => crate::cbor_type_error(&value, "true"),
483     }
484 }
485 
486 /// Manual implementation of [`crate::AsCborValue`] for the [`KeyParam`] enum that
487 /// matches the serialization of the HAL `Tag` / `KeyParameterValue` types.
488 impl crate::AsCborValue for KeyParam {
from_cbor_value(value: cbor::value::Value) -> Result<Self, crate::CborError>489     fn from_cbor_value(value: cbor::value::Value) -> Result<Self, crate::CborError> {
490         let mut a = match value {
491             cbor::value::Value::Array(a) => a,
492             _ => return crate::cbor_type_error(&value, "arr"),
493         };
494         if a.len() != 2 {
495             return Err(crate::CborError::UnexpectedItem("arr", "arr len 2"));
496         }
497 
498         // Need to know the tag value to completely parse the value.
499         let raw = a.remove(1);
500         let tag = <Tag>::from_cbor_value(a.remove(0))?;
501 
502         Ok(match tag {
503             Tag::Algorithm => KeyParam::Algorithm(<Algorithm>::from_cbor_value(raw)?),
504             Tag::BlockMode => KeyParam::BlockMode(<BlockMode>::from_cbor_value(raw)?),
505             Tag::Padding => KeyParam::Padding(<PaddingMode>::from_cbor_value(raw)?),
506             Tag::Digest => KeyParam::Digest(<Digest>::from_cbor_value(raw)?),
507             Tag::EcCurve => KeyParam::EcCurve(<EcCurve>::from_cbor_value(raw)?),
508             Tag::Origin => KeyParam::Origin(<KeyOrigin>::from_cbor_value(raw)?),
509             Tag::Purpose => KeyParam::Purpose(<KeyPurpose>::from_cbor_value(raw)?),
510             Tag::KeySize => KeyParam::KeySize(<KeySizeInBits>::from_cbor_value(raw)?),
511             Tag::CallerNonce => KeyParam::CallerNonce,
512             Tag::MinMacLength => KeyParam::MinMacLength(<u32>::from_cbor_value(raw)?),
513             Tag::RsaPublicExponent => {
514                 KeyParam::RsaPublicExponent(<RsaExponent>::from_cbor_value(raw)?)
515             }
516             Tag::IncludeUniqueId => {
517                 check_bool(raw)?;
518                 KeyParam::IncludeUniqueId
519             }
520             Tag::RsaOaepMgfDigest => KeyParam::RsaOaepMgfDigest(<Digest>::from_cbor_value(raw)?),
521             Tag::BootloaderOnly => {
522                 check_bool(raw)?;
523                 KeyParam::BootloaderOnly
524             }
525             Tag::RollbackResistance => {
526                 check_bool(raw)?;
527                 KeyParam::RollbackResistance
528             }
529             Tag::EarlyBootOnly => {
530                 check_bool(raw)?;
531                 KeyParam::EarlyBootOnly
532             }
533             Tag::ActiveDatetime => KeyParam::ActiveDatetime(<DateTime>::from_cbor_value(raw)?),
534             Tag::OriginationExpireDatetime => {
535                 KeyParam::OriginationExpireDatetime(<DateTime>::from_cbor_value(raw)?)
536             }
537             Tag::UsageExpireDatetime => {
538                 KeyParam::UsageExpireDatetime(<DateTime>::from_cbor_value(raw)?)
539             }
540             Tag::MaxUsesPerBoot => KeyParam::MaxUsesPerBoot(<u32>::from_cbor_value(raw)?),
541             Tag::UsageCountLimit => KeyParam::UsageCountLimit(<u32>::from_cbor_value(raw)?),
542             Tag::UserId => KeyParam::UserId(<u32>::from_cbor_value(raw)?),
543             Tag::UserSecureId => KeyParam::UserSecureId(<u64>::from_cbor_value(raw)?),
544             Tag::NoAuthRequired => {
545                 check_bool(raw)?;
546                 KeyParam::NoAuthRequired
547             }
548             Tag::UserAuthType => KeyParam::UserAuthType(<u32>::from_cbor_value(raw)?),
549             Tag::AuthTimeout => KeyParam::AuthTimeout(<u32>::from_cbor_value(raw)?),
550             Tag::AllowWhileOnBody => KeyParam::AllowWhileOnBody,
551             Tag::TrustedUserPresenceRequired => {
552                 check_bool(raw)?;
553                 KeyParam::TrustedUserPresenceRequired
554             }
555             Tag::TrustedConfirmationRequired => {
556                 check_bool(raw)?;
557                 KeyParam::TrustedConfirmationRequired
558             }
559             Tag::UnlockedDeviceRequired => {
560                 check_bool(raw)?;
561                 KeyParam::UnlockedDeviceRequired
562             }
563             Tag::ApplicationId => KeyParam::ApplicationId(<Vec<u8>>::from_cbor_value(raw)?),
564             Tag::ApplicationData => KeyParam::ApplicationData(<Vec<u8>>::from_cbor_value(raw)?),
565             Tag::CreationDatetime => KeyParam::CreationDatetime(<DateTime>::from_cbor_value(raw)?),
566             Tag::RootOfTrust => KeyParam::RootOfTrust(<Vec<u8>>::from_cbor_value(raw)?),
567             Tag::OsVersion => KeyParam::OsVersion(<u32>::from_cbor_value(raw)?),
568             Tag::OsPatchlevel => KeyParam::OsPatchlevel(<u32>::from_cbor_value(raw)?),
569             Tag::AttestationChallenge => {
570                 KeyParam::AttestationChallenge(<Vec<u8>>::from_cbor_value(raw)?)
571             }
572             Tag::AttestationApplicationId => {
573                 KeyParam::AttestationApplicationId(<Vec<u8>>::from_cbor_value(raw)?)
574             }
575             Tag::AttestationIdBrand => {
576                 KeyParam::AttestationIdBrand(<Vec<u8>>::from_cbor_value(raw)?)
577             }
578             Tag::AttestationIdDevice => {
579                 KeyParam::AttestationIdDevice(<Vec<u8>>::from_cbor_value(raw)?)
580             }
581             Tag::AttestationIdProduct => {
582                 KeyParam::AttestationIdProduct(<Vec<u8>>::from_cbor_value(raw)?)
583             }
584             Tag::AttestationIdSerial => {
585                 KeyParam::AttestationIdSerial(<Vec<u8>>::from_cbor_value(raw)?)
586             }
587             Tag::AttestationIdImei => KeyParam::AttestationIdImei(<Vec<u8>>::from_cbor_value(raw)?),
588             #[cfg(feature = "hal_v3")]
589             Tag::AttestationIdSecondImei => {
590                 KeyParam::AttestationIdSecondImei(<Vec<u8>>::from_cbor_value(raw)?)
591             }
592             Tag::AttestationIdMeid => KeyParam::AttestationIdMeid(<Vec<u8>>::from_cbor_value(raw)?),
593             Tag::AttestationIdManufacturer => {
594                 KeyParam::AttestationIdManufacturer(<Vec<u8>>::from_cbor_value(raw)?)
595             }
596             Tag::AttestationIdModel => {
597                 KeyParam::AttestationIdModel(<Vec<u8>>::from_cbor_value(raw)?)
598             }
599             Tag::VendorPatchlevel => KeyParam::VendorPatchlevel(<u32>::from_cbor_value(raw)?),
600             Tag::BootPatchlevel => KeyParam::BootPatchlevel(<u32>::from_cbor_value(raw)?),
601             Tag::DeviceUniqueAttestation => {
602                 check_bool(raw)?;
603                 KeyParam::DeviceUniqueAttestation
604             }
605             Tag::StorageKey => KeyParam::StorageKey,
606             Tag::Nonce => KeyParam::Nonce(<Vec<u8>>::from_cbor_value(raw)?),
607             Tag::MacLength => KeyParam::MacLength(<u32>::from_cbor_value(raw)?),
608             Tag::ResetSinceIdRotation => {
609                 check_bool(raw)?;
610                 KeyParam::ResetSinceIdRotation
611             }
612             Tag::CertificateSerial => KeyParam::CertificateSerial(<Vec<u8>>::from_cbor_value(raw)?),
613             Tag::CertificateSubject => {
614                 KeyParam::CertificateSubject(<Vec<u8>>::from_cbor_value(raw)?)
615             }
616             Tag::CertificateNotBefore => {
617                 KeyParam::CertificateNotBefore(<DateTime>::from_cbor_value(raw)?)
618             }
619             Tag::CertificateNotAfter => {
620                 KeyParam::CertificateNotAfter(<DateTime>::from_cbor_value(raw)?)
621             }
622             Tag::MaxBootLevel => KeyParam::MaxBootLevel(<u32>::from_cbor_value(raw)?),
623 
624             _ => return Err(crate::CborError::UnexpectedItem("tag", "known tag")),
625         })
626     }
to_cbor_value(self) -> Result<cbor::value::Value, crate::CborError>627     fn to_cbor_value(self) -> Result<cbor::value::Value, crate::CborError> {
628         let (tag, val) = match self {
629             KeyParam::Algorithm(v) => (Tag::Algorithm, v.to_cbor_value()?),
630             KeyParam::BlockMode(v) => (Tag::BlockMode, v.to_cbor_value()?),
631             KeyParam::Padding(v) => (Tag::Padding, v.to_cbor_value()?),
632             KeyParam::Digest(v) => (Tag::Digest, v.to_cbor_value()?),
633             KeyParam::EcCurve(v) => (Tag::EcCurve, v.to_cbor_value()?),
634             KeyParam::Origin(v) => (Tag::Origin, v.to_cbor_value()?),
635             KeyParam::Purpose(v) => (Tag::Purpose, v.to_cbor_value()?),
636             KeyParam::KeySize(v) => (Tag::KeySize, v.to_cbor_value()?),
637             KeyParam::CallerNonce => (Tag::CallerNonce, true.to_cbor_value()?),
638             KeyParam::MinMacLength(v) => (Tag::MinMacLength, v.to_cbor_value()?),
639             KeyParam::RsaPublicExponent(v) => (Tag::RsaPublicExponent, v.to_cbor_value()?),
640             KeyParam::IncludeUniqueId => (Tag::IncludeUniqueId, true.to_cbor_value()?),
641             KeyParam::RsaOaepMgfDigest(v) => (Tag::RsaOaepMgfDigest, v.to_cbor_value()?),
642             KeyParam::BootloaderOnly => (Tag::BootloaderOnly, true.to_cbor_value()?),
643             KeyParam::RollbackResistance => (Tag::RollbackResistance, true.to_cbor_value()?),
644             KeyParam::EarlyBootOnly => (Tag::EarlyBootOnly, true.to_cbor_value()?),
645             KeyParam::ActiveDatetime(v) => (Tag::ActiveDatetime, v.to_cbor_value()?),
646             KeyParam::OriginationExpireDatetime(v) => {
647                 (Tag::OriginationExpireDatetime, v.to_cbor_value()?)
648             }
649             KeyParam::UsageExpireDatetime(v) => (Tag::UsageExpireDatetime, v.to_cbor_value()?),
650             KeyParam::MaxUsesPerBoot(v) => (Tag::MaxUsesPerBoot, v.to_cbor_value()?),
651             KeyParam::UsageCountLimit(v) => (Tag::UsageCountLimit, v.to_cbor_value()?),
652             KeyParam::UserId(v) => (Tag::UserId, v.to_cbor_value()?),
653             KeyParam::UserSecureId(v) => (Tag::UserSecureId, v.to_cbor_value()?),
654             KeyParam::NoAuthRequired => (Tag::NoAuthRequired, true.to_cbor_value()?),
655             KeyParam::UserAuthType(v) => (Tag::UserAuthType, v.to_cbor_value()?),
656             KeyParam::AuthTimeout(v) => (Tag::AuthTimeout, v.to_cbor_value()?),
657             KeyParam::AllowWhileOnBody => (Tag::AllowWhileOnBody, true.to_cbor_value()?),
658             KeyParam::TrustedUserPresenceRequired => {
659                 (Tag::TrustedUserPresenceRequired, true.to_cbor_value()?)
660             }
661             KeyParam::TrustedConfirmationRequired => {
662                 (Tag::TrustedConfirmationRequired, true.to_cbor_value()?)
663             }
664             KeyParam::UnlockedDeviceRequired => {
665                 (Tag::UnlockedDeviceRequired, true.to_cbor_value()?)
666             }
667             KeyParam::ApplicationId(v) => (Tag::ApplicationId, v.to_cbor_value()?),
668             KeyParam::ApplicationData(v) => (Tag::ApplicationData, v.to_cbor_value()?),
669             KeyParam::CreationDatetime(v) => (Tag::CreationDatetime, v.to_cbor_value()?),
670             KeyParam::RootOfTrust(v) => (Tag::RootOfTrust, v.to_cbor_value()?),
671             KeyParam::OsVersion(v) => (Tag::OsVersion, v.to_cbor_value()?),
672             KeyParam::OsPatchlevel(v) => (Tag::OsPatchlevel, v.to_cbor_value()?),
673             KeyParam::AttestationChallenge(v) => (Tag::AttestationChallenge, v.to_cbor_value()?),
674             KeyParam::AttestationApplicationId(v) => {
675                 (Tag::AttestationApplicationId, v.to_cbor_value()?)
676             }
677             KeyParam::AttestationIdBrand(v) => (Tag::AttestationIdBrand, v.to_cbor_value()?),
678             KeyParam::AttestationIdDevice(v) => (Tag::AttestationIdDevice, v.to_cbor_value()?),
679             KeyParam::AttestationIdProduct(v) => (Tag::AttestationIdProduct, v.to_cbor_value()?),
680             KeyParam::AttestationIdSerial(v) => (Tag::AttestationIdSerial, v.to_cbor_value()?),
681             KeyParam::AttestationIdImei(v) => (Tag::AttestationIdImei, v.to_cbor_value()?),
682             #[cfg(feature = "hal_v3")]
683             KeyParam::AttestationIdSecondImei(v) => {
684                 (Tag::AttestationIdSecondImei, v.to_cbor_value()?)
685             }
686             KeyParam::AttestationIdMeid(v) => (Tag::AttestationIdMeid, v.to_cbor_value()?),
687             KeyParam::AttestationIdManufacturer(v) => {
688                 (Tag::AttestationIdManufacturer, v.to_cbor_value()?)
689             }
690             KeyParam::AttestationIdModel(v) => (Tag::AttestationIdModel, v.to_cbor_value()?),
691             KeyParam::VendorPatchlevel(v) => (Tag::VendorPatchlevel, v.to_cbor_value()?),
692             KeyParam::BootPatchlevel(v) => (Tag::BootPatchlevel, v.to_cbor_value()?),
693             KeyParam::DeviceUniqueAttestation => {
694                 (Tag::DeviceUniqueAttestation, true.to_cbor_value()?)
695             }
696             KeyParam::StorageKey => (Tag::StorageKey, true.to_cbor_value()?),
697             KeyParam::Nonce(v) => (Tag::Nonce, v.to_cbor_value()?),
698             KeyParam::MacLength(v) => (Tag::MacLength, v.to_cbor_value()?),
699             KeyParam::ResetSinceIdRotation => (Tag::ResetSinceIdRotation, true.to_cbor_value()?),
700             KeyParam::CertificateSerial(v) => (Tag::CertificateSerial, v.to_cbor_value()?),
701             KeyParam::CertificateSubject(v) => (Tag::CertificateSubject, v.to_cbor_value()?),
702             KeyParam::CertificateNotBefore(v) => (Tag::CertificateNotBefore, v.to_cbor_value()?),
703             KeyParam::CertificateNotAfter(v) => (Tag::CertificateNotAfter, v.to_cbor_value()?),
704             KeyParam::MaxBootLevel(v) => (Tag::MaxBootLevel, v.to_cbor_value()?),
705         };
706         Ok(cbor::value::Value::Array(vec_try![tag.to_cbor_value()?, val]?))
707     }
cddl_typename() -> Option<String>708     fn cddl_typename() -> Option<String> {
709         Some("KeyParam".to_string())
710     }
cddl_schema() -> Option<String>711     fn cddl_schema() -> Option<String> {
712         let mut result = "&(\n".to_string();
713 
714         result += &format!(
715             "    [{}, {}], ; {}\n",
716             Tag::Algorithm as i32,
717             Algorithm::cddl_ref(),
718             "Tag_Algorithm"
719         );
720         result += &format!(
721             "    [{}, {}], ; {}\n",
722             Tag::BlockMode as i32,
723             BlockMode::cddl_ref(),
724             "Tag_BlockMode",
725         );
726         result += &format!(
727             "    [{}, {}], ; {}\n",
728             Tag::Padding as i32,
729             PaddingMode::cddl_ref(),
730             "Tag_Padding",
731         );
732         result +=
733             &format!("    [{}, {}], ; {}\n", Tag::Digest as i32, Digest::cddl_ref(), "Tag_Digest",);
734         result += &format!(
735             "    [{}, {}], ; {}\n",
736             Tag::EcCurve as i32,
737             EcCurve::cddl_ref(),
738             "Tag_EcCurve",
739         );
740         result += &format!(
741             "    [{}, {}], ; {}\n",
742             Tag::Origin as i32,
743             KeyOrigin::cddl_ref(),
744             "Tag_Origin",
745         );
746         result += &format!(
747             "    [{}, {}], ; {}\n",
748             Tag::Purpose as i32,
749             KeyPurpose::cddl_ref(),
750             "Tag_Purpose",
751         );
752         result += &format!(
753             "    [{}, {}], ; {}\n",
754             Tag::KeySize as i32,
755             KeySizeInBits::cddl_ref(),
756             "Tag_KeySize",
757         );
758         result += &format!(
759             "    [{}, {}], ; {}\n",
760             Tag::CallerNonce as i32,
761             Vec::<u8>::cddl_ref(),
762             "Tag_CallerNonce",
763         );
764         result += &format!(
765             "    [{}, {}], ; {}\n",
766             Tag::MinMacLength as i32,
767             u32::cddl_ref(),
768             "Tag_MinMacLength",
769         );
770         result += &format!(
771             "    [{}, {}], ; {}\n",
772             Tag::RsaPublicExponent as i32,
773             RsaExponent::cddl_ref(),
774             "Tag_RsaPublicExponent",
775         );
776         result += &format!(
777             "    [{}, {}], ; {}\n",
778             Tag::IncludeUniqueId as i32,
779             "true",
780             "Tag_IncludeUniqueId",
781         );
782         result += &format!(
783             "    [{}, {}], ; {}\n",
784             Tag::RsaOaepMgfDigest as i32,
785             Digest::cddl_ref(),
786             "Tag_RsaOaepMgfDigest",
787         );
788         result += &format!(
789             "    [{}, {}], ; {}\n",
790             Tag::BootloaderOnly as i32,
791             "true",
792             "Tag_BootloaderOnly",
793         );
794         result += &format!(
795             "    [{}, {}], ; {}\n",
796             Tag::RollbackResistance as i32,
797             "true",
798             "Tag_RollbackResistance",
799         );
800         result += &format!(
801             "    [{}, {}], ; {}\n",
802             Tag::EarlyBootOnly as i32,
803             "true",
804             "Tag_EarlyBootOnly",
805         );
806         result += &format!(
807             "    [{}, {}], ; {}\n",
808             Tag::ActiveDatetime as i32,
809             DateTime::cddl_ref(),
810             "Tag_ActiveDatetime",
811         );
812         result += &format!(
813             "    [{}, {}], ; {}\n",
814             Tag::OriginationExpireDatetime as i32,
815             DateTime::cddl_ref(),
816             "Tag_OriginationExpireDatetime",
817         );
818         result += &format!(
819             "    [{}, {}], ; {}\n",
820             Tag::UsageExpireDatetime as i32,
821             DateTime::cddl_ref(),
822             "Tag_UsageExpireDatetime",
823         );
824         result += &format!(
825             "    [{}, {}], ; {}\n",
826             Tag::MaxUsesPerBoot as i32,
827             u32::cddl_ref(),
828             "Tag_MaxUsesPerBoot",
829         );
830         result += &format!(
831             "    [{}, {}], ; {}\n",
832             Tag::UsageCountLimit as i32,
833             u32::cddl_ref(),
834             "Tag_UsageCountLimit",
835         );
836         result +=
837             &format!("    [{}, {}], ; {}\n", Tag::UserId as i32, u32::cddl_ref(), "Tag_UserId",);
838         result += &format!(
839             "    [{}, {}], ; {}\n",
840             Tag::UserSecureId as i32,
841             u64::cddl_ref(),
842             "Tag_UserSecureId",
843         );
844         result += &format!(
845             "    [{}, {}], ; {}\n",
846             Tag::NoAuthRequired as i32,
847             "true",
848             "Tag_NoAuthRequired",
849         );
850         result += &format!(
851             "    [{}, {}], ; {}\n",
852             Tag::UserAuthType as i32,
853             u32::cddl_ref(),
854             "Tag_UserAuthType",
855         );
856         result += &format!(
857             "    [{}, {}], ; {}\n",
858             Tag::AuthTimeout as i32,
859             u32::cddl_ref(),
860             "Tag_AuthTimeout",
861         );
862         result += &format!(
863             "    [{}, {}], ; {}\n",
864             Tag::AllowWhileOnBody as i32,
865             "true",
866             "Tag_AllowWhileOnBody",
867         );
868         result += &format!(
869             "    [{}, {}], ; {}\n",
870             Tag::TrustedUserPresenceRequired as i32,
871             "true",
872             "Tag_TrustedUserPresenceRequired",
873         );
874         result += &format!(
875             "    [{}, {}], ; {}\n",
876             Tag::TrustedConfirmationRequired as i32,
877             "true",
878             "Tag_TrustedConfirmationRequired",
879         );
880         result += &format!(
881             "    [{}, {}], ; {}\n",
882             Tag::UnlockedDeviceRequired as i32,
883             "true",
884             "Tag_UnlockedDeviceRequired",
885         );
886         result += &format!(
887             "    [{}, {}], ; {}\n",
888             Tag::ApplicationId as i32,
889             Vec::<u8>::cddl_ref(),
890             "Tag_ApplicationId",
891         );
892         result += &format!(
893             "    [{}, {}], ; {}\n",
894             Tag::ApplicationData as i32,
895             Vec::<u8>::cddl_ref(),
896             "Tag_ApplicationData",
897         );
898         result += &format!(
899             "    [{}, {}], ; {}\n",
900             Tag::CreationDatetime as i32,
901             DateTime::cddl_ref(),
902             "Tag_CreationDatetime",
903         );
904         result += &format!(
905             "    [{}, {}], ; {}\n",
906             Tag::RootOfTrust as i32,
907             Vec::<u8>::cddl_ref(),
908             "Tag_RootOfTrust",
909         );
910         result += &format!(
911             "    [{}, {}], ; {}\n",
912             Tag::OsVersion as i32,
913             u32::cddl_ref(),
914             "Tag_OsVersion",
915         );
916         result += &format!(
917             "    [{}, {}], ; {}\n",
918             Tag::OsPatchlevel as i32,
919             u32::cddl_ref(),
920             "Tag_OsPatchlevel",
921         );
922         result += &format!(
923             "    [{}, {}], ; {}\n",
924             Tag::AttestationChallenge as i32,
925             Vec::<u8>::cddl_ref(),
926             "Tag_AttestationChallenge",
927         );
928         result += &format!(
929             "    [{}, {}], ; {}\n",
930             Tag::AttestationApplicationId as i32,
931             Vec::<u8>::cddl_ref(),
932             "Tag_AttestationApplicationId",
933         );
934         result += &format!(
935             "    [{}, {}], ; {}\n",
936             Tag::AttestationIdBrand as i32,
937             Vec::<u8>::cddl_ref(),
938             "Tag_AttestationIdBrand",
939         );
940         result += &format!(
941             "    [{}, {}], ; {}\n",
942             Tag::AttestationIdDevice as i32,
943             Vec::<u8>::cddl_ref(),
944             "Tag_AttestationIdDevice",
945         );
946         result += &format!(
947             "    [{}, {}], ; {}\n",
948             Tag::AttestationIdProduct as i32,
949             Vec::<u8>::cddl_ref(),
950             "Tag_AttestationIdProduct",
951         );
952         result += &format!(
953             "    [{}, {}], ; {}\n",
954             Tag::AttestationIdSerial as i32,
955             Vec::<u8>::cddl_ref(),
956             "Tag_AttestationIdSerial",
957         );
958         result += &format!(
959             "    [{}, {}], ; {}\n",
960             Tag::AttestationIdImei as i32,
961             Vec::<u8>::cddl_ref(),
962             "Tag_AttestationIdImei",
963         );
964         #[cfg(feature = "hal_v3")]
965         {
966             result += &format!(
967                 "    [{}, {}], ; {}\n",
968                 Tag::AttestationIdSecondImei as i32,
969                 Vec::<u8>::cddl_ref(),
970                 "Tag_AttestationIdSecondImei",
971             );
972         }
973         result += &format!(
974             "    [{}, {}], ; {}\n",
975             Tag::AttestationIdMeid as i32,
976             Vec::<u8>::cddl_ref(),
977             "Tag_AttestationIdMeid",
978         );
979         result += &format!(
980             "    [{}, {}], ; {}\n",
981             Tag::AttestationIdManufacturer as i32,
982             Vec::<u8>::cddl_ref(),
983             "Tag_AttestationIdManufacturer",
984         );
985         result += &format!(
986             "    [{}, {}], ; {}\n",
987             Tag::AttestationIdModel as i32,
988             Vec::<u8>::cddl_ref(),
989             "Tag_AttestationIdModel",
990         );
991         result += &format!(
992             "    [{}, {}], ; {}\n",
993             Tag::VendorPatchlevel as i32,
994             u32::cddl_ref(),
995             "Tag_VendorPatchlevel",
996         );
997         result += &format!(
998             "    [{}, {}], ; {}\n",
999             Tag::BootPatchlevel as i32,
1000             u32::cddl_ref(),
1001             "Tag_BootPatchlevel",
1002         );
1003         result += &format!(
1004             "    [{}, {}], ; {}\n",
1005             Tag::DeviceUniqueAttestation as i32,
1006             "true",
1007             "Tag_DeviceUniqueAttestation",
1008         );
1009         result +=
1010             &format!("    [{}, {}], ; {}\n", Tag::StorageKey as i32, "true", "Tag_StorageKey",);
1011         result += &format!(
1012             "    [{}, {}], ; {}\n",
1013             Tag::Nonce as i32,
1014             Vec::<u8>::cddl_ref(),
1015             "Tag_Nonce",
1016         );
1017         result += &format!(
1018             "    [{}, {}], ; {}\n",
1019             Tag::MacLength as i32,
1020             u32::cddl_ref(),
1021             "Tag_MacLength",
1022         );
1023         result += &format!(
1024             "    [{}, {}], ; {}\n",
1025             Tag::ResetSinceIdRotation as i32,
1026             "true",
1027             "Tag_ResetSinceIdRotation",
1028         );
1029         result += &format!(
1030             "    [{}, {}], ; {}\n",
1031             Tag::CertificateSerial as i32,
1032             Vec::<u8>::cddl_ref(),
1033             "Tag_CertificateSerial",
1034         );
1035         result += &format!(
1036             "    [{}, {}], ; {}\n",
1037             Tag::CertificateSubject as i32,
1038             Vec::<u8>::cddl_ref(),
1039             "Tag_CertificateSubject",
1040         );
1041         result += &format!(
1042             "    [{}, {}], ; {}\n",
1043             Tag::CertificateNotBefore as i32,
1044             DateTime::cddl_ref(),
1045             "Tag_CertificateNotBefore",
1046         );
1047         result += &format!(
1048             "    [{}, {}], ; {}\n",
1049             Tag::CertificateNotAfter as i32,
1050             DateTime::cddl_ref(),
1051             "Tag_CertificateNotAfter",
1052         );
1053         result += &format!(
1054             "    [{}, {}], ; {}\n",
1055             Tag::MaxBootLevel as i32,
1056             u32::cddl_ref(),
1057             "Tag_MaxBootLevel",
1058         );
1059         result += ")";
1060         Some(result)
1061     }
1062 }
1063 
1064 /// Determine the tag type for a tag, based on the top 4 bits of the tag number.
tag_type(tag: Tag) -> TagType1065 pub fn tag_type(tag: Tag) -> TagType {
1066     match ((tag as u32) & 0xf0000000u32) as i32 {
1067         x if x == TagType::Enum as i32 => TagType::Enum,
1068         x if x == TagType::EnumRep as i32 => TagType::EnumRep,
1069         x if x == TagType::Uint as i32 => TagType::Uint,
1070         x if x == TagType::UintRep as i32 => TagType::UintRep,
1071         x if x == TagType::Ulong as i32 => TagType::Ulong,
1072         x if x == TagType::Date as i32 => TagType::Date,
1073         x if x == TagType::Bool as i32 => TagType::Bool,
1074         x if x == TagType::Bignum as i32 => TagType::Bignum,
1075         x if x == TagType::Bytes as i32 => TagType::Bytes,
1076         x if x == TagType::UlongRep as i32 => TagType::UlongRep,
1077         _ => TagType::Invalid,
1078     }
1079 }
1080 
1081 /// Determine the raw tag value with tag type information stripped out.
raw_tag_value(tag: Tag) -> u321082 pub fn raw_tag_value(tag: Tag) -> u32 {
1083     (tag as u32) & 0x0fffffffu32
1084 }
1085 
1086 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1087 #[repr(i32)]
1088 pub enum KeyPurpose {
1089     Encrypt = 0,
1090     Decrypt = 1,
1091     Sign = 2,
1092     Verify = 3,
1093     WrapKey = 5,
1094     AgreeKey = 6,
1095     AttestKey = 7,
1096 }
1097 try_from_n!(KeyPurpose);
1098 
1099 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1100 #[repr(i32)]
1101 pub enum PaddingMode {
1102     None = 1,
1103     RsaOaep = 2,
1104     RsaPss = 3,
1105     RsaPkcs115Encrypt = 4,
1106     RsaPkcs115Sign = 5,
1107     Pkcs7 = 64,
1108 }
1109 try_from_n!(PaddingMode);
1110 
1111 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, N)]
1112 #[repr(i32)]
1113 pub enum SecurityLevel {
1114     Software = 0,
1115     TrustedEnvironment = 1,
1116     Strongbox = 2,
1117     Keystore = 100,
1118 }
1119 try_from_n!(SecurityLevel);
1120 
1121 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsCborValue, FromRawTag, N)]
1122 #[repr(i32)]
1123 pub enum Tag {
1124     Invalid = 0,
1125     Purpose = 536870913,
1126     Algorithm = 268435458,
1127     KeySize = 805306371,
1128     BlockMode = 536870916,
1129     Digest = 536870917,
1130     Padding = 536870918,
1131     CallerNonce = 1879048199,
1132     MinMacLength = 805306376,
1133     EcCurve = 268435466,
1134     RsaPublicExponent = 1342177480,
1135     IncludeUniqueId = 1879048394,
1136     RsaOaepMgfDigest = 536871115,
1137     BootloaderOnly = 1879048494,
1138     RollbackResistance = 1879048495,
1139     HardwareType = 268435760,
1140     EarlyBootOnly = 1879048497,
1141     ActiveDatetime = 1610613136,
1142     OriginationExpireDatetime = 1610613137,
1143     UsageExpireDatetime = 1610613138,
1144     MinSecondsBetweenOps = 805306771,
1145     MaxUsesPerBoot = 805306772,
1146     UsageCountLimit = 805306773,
1147     UserId = 805306869,
1148     UserSecureId = -1610612234,
1149     NoAuthRequired = 1879048695,
1150     UserAuthType = 268435960,
1151     AuthTimeout = 805306873,
1152     AllowWhileOnBody = 1879048698,
1153     TrustedUserPresenceRequired = 1879048699,
1154     TrustedConfirmationRequired = 1879048700,
1155     UnlockedDeviceRequired = 1879048701,
1156     ApplicationId = -1879047591,
1157     ApplicationData = -1879047492,
1158     CreationDatetime = 1610613437,
1159     Origin = 268436158,
1160     RootOfTrust = -1879047488,
1161     OsVersion = 805307073,
1162     OsPatchlevel = 805307074,
1163     UniqueId = -1879047485,
1164     AttestationChallenge = -1879047484,
1165     AttestationApplicationId = -1879047483,
1166     AttestationIdBrand = -1879047482,
1167     AttestationIdDevice = -1879047481,
1168     AttestationIdProduct = -1879047480,
1169     AttestationIdSerial = -1879047479,
1170     AttestationIdImei = -1879047478,
1171     AttestationIdMeid = -1879047477,
1172     AttestationIdManufacturer = -1879047476,
1173     AttestationIdModel = -1879047475,
1174     VendorPatchlevel = 805307086,
1175     BootPatchlevel = 805307087,
1176     DeviceUniqueAttestation = 1879048912,
1177     IdentityCredentialKey = 1879048913,
1178     StorageKey = 1879048914,
1179     #[cfg(feature = "hal_v3")]
1180     AttestationIdSecondImei = -1879047469,
1181     AssociatedData = -1879047192,
1182     Nonce = -1879047191,
1183     MacLength = 805307371,
1184     ResetSinceIdRotation = 1879049196,
1185     ConfirmationToken = -1879047187,
1186     CertificateSerial = -2147482642,
1187     CertificateSubject = -1879047185,
1188     CertificateNotBefore = 1610613744,
1189     CertificateNotAfter = 1610613745,
1190     MaxBootLevel = 805307378,
1191 }
1192 try_from_n!(Tag);
1193 
1194 #[derive(Clone, Copy, Debug, PartialEq, Eq, AsCborValue, N)]
1195 #[repr(i32)]
1196 pub enum TagType {
1197     Invalid = 0,
1198     Enum = 268435456,
1199     EnumRep = 536870912,
1200     Uint = 805306368,
1201     UintRep = 1073741824,
1202     Ulong = 1342177280,
1203     Date = 1610612736,
1204     Bool = 1879048192,
1205     Bignum = -2147483648,
1206     Bytes = -1879048192,
1207     UlongRep = -1610612736,
1208 }
1209 try_from_n!(TagType);
1210