cryptoki/
object.rs

1// Copyright 2021 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3//! Object types (including Attributes)
4
5use crate::error::{Error, Result};
6use crate::mechanism::MechanismType;
7use crate::types::{Date, Ulong, Version};
8use cryptoki_sys::*;
9use log::error;
10use std::convert::TryFrom;
11use std::convert::TryInto;
12use std::ffi::c_void;
13use std::fmt::Formatter;
14use std::mem::size_of;
15use std::ops::Deref;
16
17/// Helper macro to convert a Vec to a pointer, returning NULL if the Vec is empty.
18///
19/// This is useful for CK_ATTRIBUTE pValue fields, to avoid dangling pointers present
20/// in empty vectors to be converted as e.g. 0x01 for the C layer, which may lead to issues,
21/// as 0x01 is arguably no longer NULL and could be dereferenced.
22///
23/// See Vec::as_ptr() documentation for more details on the issue.
24#[macro_export]
25macro_rules! as_cptr {
26    ($vec:expr) => {
27        if $vec.is_empty() {
28            std::ptr::null_mut()
29        } else {
30            $vec.as_ptr() as *mut ::std::ffi::c_void
31        }
32    };
33}
34
35#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
36#[non_exhaustive]
37/// Type of an attribute
38pub enum AttributeType {
39    /// DER-encoding of the attribute certificate's issuer
40    AcIssuer,
41    /// List of mechanisms allowed to be used with the key
42    AllowedMechanisms,
43    /// Indicates that the user has to supply the PIN for each use with the key
44    AlwaysAuthenticate,
45    /// Indicates if the key has always had the Sensitive attribute set to true
46    AlwaysSensitive,
47    /// Description of the application that manages the object
48    Application,
49    /// BER-encoding of a sequence of object identifier values
50    AttrTypes,
51    /// Base number value of a key
52    Base,
53    /// Type of certificate
54    CertificateType,
55    /// Checksum
56    CheckValue,
57    /// Type of an object
58    Class,
59    /// The CRT coefficient `iqmp` of an RSA private key
60    Coefficient,
61    /// Determines if an object can be copied
62    Copyable,
63    /// Determines if a key supports key decapsulation
64    Decapsulate,
65    /// Determines if a key supports decryption
66    Decrypt,
67    /// Determines if it is possible to derive other keys from the key
68    Derive,
69    /// Determines if it is possible to destroy an object
70    Destroyable,
71    /// Parameters defining an elliptic curve
72    EcParams,
73    /// DER-encoded Elliptic Curve point
74    EcPoint,
75    /// Determines if a key supports key encapsulation
76    Encapsulate,
77    /// Determines if a key supports encryption
78    Encrypt,
79    /// The end date for the object
80    EndDate,
81    /// The private exponent `dmp1` of an RSA private key
82    Exponent1,
83    /// The private exponent `dmq1` of an RSA private key
84    Exponent2,
85    /// Determines if a key is extractable and can be wrapped
86    Extractable,
87    /// Hash of issuer public key
88    HashOfIssuerPublicKey,
89    /// Hash of subject public key
90    HashOfSubjectPublicKey,
91    /// Key identifier for key
92    Id,
93    /// DER-encoding of the certificate issuer name
94    Issuer,
95    /// Identifier of the mechanism used to generate the key material
96    KeyGenMechanism,
97    /// Type of a key
98    KeyType,
99    /// Description of the object
100    Label,
101    /// Indicates if the key was generated locally or copied from a locally created object
102    Local,
103    /// Determines if the object can be modified
104    Modifiable,
105    /// Modulus value of a key
106    Modulus,
107    /// Length in bits of the modulus of a key
108    ModulusBits,
109    /// Indicates if the key has never had the Extractable attribute set to true
110    NeverExtractable,
111    /// Object ID
112    ObjectId,
113    /// Object Validation flags
114    ObjectValidationFlags,
115    /// DER encoding of the attribute certificate's subject field
116    Owner,
117    /// Algorithm-specific parameter set
118    ParameterSet,
119    /// Prime number value of a key
120    Prime,
121    /// The prime `p` of an RSA private key
122    Prime1,
123    /// The prime `q` of an RSA private key
124    Prime2,
125    /// Determines if the object is private
126    Private,
127    /// Private exponent `d`
128    PrivateExponent,
129    /// Public exponent value of a key
130    PublicExponent,
131    /// DER-encoding of the SubjectPublicKeyInfo
132    PublicKeyInfo,
133    /// Profile ID
134    ProfileId,
135    /// Seed to derive private key
136    Seed,
137    /// Determines if the key is sensitive
138    Sensitive,
139    /// DER encoding of the certificate serial number
140    SerialNumber,
141    /// Determines if a key supports signing
142    Sign,
143    /// Determines if a key supports signing where the data can be recovered from the signature
144    SignRecover,
145    /// The start date of the object
146    StartDate,
147    /// DER-encoding of certificate subject name
148    Subject,
149    /// Determines if the object is a token object
150    Token,
151    /// Determines if the object is trusted
152    Trusted,
153    /// Unique Object Id
154    UniqueId,
155    /// Determines if a key supports unwrapping
156    Unwrap,
157    /// Gives the URL where the complete certificate can be obtained
158    Url,
159    /// Identifier indicating the validation type
160    ValidationType,
161    /// Version of the validation standard or specification
162    ValidationVersion,
163    /// Validation level, Meaning is Validation type specific
164    ValidationLevel,
165    /// How the module is identified in the validation documentation
166    ValidationModuleId,
167    /// Flags identifying this validation in sessions and objects
168    ValidationFlag,
169    /// Identifies the authority that issues the validation
170    ValidationAuthorityType,
171    /// 2 letter ISO country code
172    ValidationCountry,
173    /// Identifier of the validation certificate
174    ValidationCertificateIdentifier,
175    /// Validation authority URI from which information related to the validation is available.
176    /// If the Validation Certificate URI is not provided, the validation object SHOULD include
177    /// a Validation Vendor URI.
178    ValidationCertificateUri,
179    /// Validation Vendor URI from which information related to the validation is available.
180    ValidationVendorUri,
181    /// Profile used for validation
182    ValidationProfile,
183    /// Value of the object
184    Value,
185    /// Length in bytes of the value
186    ValueLen,
187    /// Vendor defined attribute
188    VendorDefined(CK_ATTRIBUTE_TYPE),
189    /// Determines if a key supports verifying
190    Verify,
191    /// Determines if a key supports verifying where the data can be recovered from the signature
192    VerifyRecover,
193    /// Determines if a key supports wrapping
194    Wrap,
195    /// Indicates that the key can only be wrapped with a wrapping key that has the Trusted attribute
196    WrapWithTrusted,
197}
198
199impl AttributeType {
200    pub(crate) fn stringify(val: CK_ATTRIBUTE_TYPE) -> String {
201        match val {
202            CKA_CLASS => String::from(stringify!(CKA_CLASS)),
203            CKA_TOKEN => String::from(stringify!(CKA_TOKEN)),
204            CKA_PRIVATE => String::from(stringify!(CKA_PRIVATE)),
205            CKA_LABEL => String::from(stringify!(CKA_LABEL)),
206            CKA_APPLICATION => String::from(stringify!(CKA_APPLICATION)),
207            CKA_VALUE => String::from(stringify!(CKA_VALUE)),
208            CKA_OBJECT_ID => String::from(stringify!(CKA_OBJECT_ID)),
209            CKA_CERTIFICATE_TYPE => String::from(stringify!(CKA_CERTIFICATE_TYPE)),
210            CKA_ISSUER => String::from(stringify!(CKA_ISSUER)),
211            CKA_SERIAL_NUMBER => String::from(stringify!(CKA_SERIAL_NUMBER)),
212            CKA_AC_ISSUER => String::from(stringify!(CKA_AC_ISSUER)),
213            CKA_OWNER => String::from(stringify!(CKA_OWNER)),
214            CKA_ATTR_TYPES => String::from(stringify!(CKA_ATTR_TYPES)),
215            CKA_TRUSTED => String::from(stringify!(CKA_TRUSTED)),
216            CKA_CERTIFICATE_CATEGORY => String::from(stringify!(CKA_CERTIFICATE_CATEGORY)),
217            CKA_JAVA_MIDP_SECURITY_DOMAIN => {
218                String::from(stringify!(CKA_JAVA_MIDP_SECURITY_DOMAIN))
219            }
220            CKA_URL => String::from(stringify!(CKA_URL)),
221            CKA_HASH_OF_SUBJECT_PUBLIC_KEY => {
222                String::from(stringify!(CKA_HASH_OF_SUBJECT_PUBLIC_KEY))
223            }
224            CKA_HASH_OF_ISSUER_PUBLIC_KEY => {
225                String::from(stringify!(CKA_HASH_OF_ISSUER_PUBLIC_KEY))
226            }
227            CKA_NAME_HASH_ALGORITHM => String::from(stringify!(CKA_NAME_HASH_ALGORITHM)),
228            CKA_CHECK_VALUE => String::from(stringify!(CKA_CHECK_VALUE)),
229            CKA_KEY_TYPE => String::from(stringify!(CKA_KEY_TYPE)),
230            CKA_SUBJECT => String::from(stringify!(CKA_SUBJECT)),
231            CKA_ID => String::from(stringify!(CKA_ID)),
232            CKA_SENSITIVE => String::from(stringify!(CKA_SENSITIVE)),
233            CKA_ENCRYPT => String::from(stringify!(CKA_ENCRYPT)),
234            CKA_DECRYPT => String::from(stringify!(CKA_DECRYPT)),
235            CKA_WRAP => String::from(stringify!(CKA_WRAP)),
236            CKA_UNWRAP => String::from(stringify!(CKA_UNWRAP)),
237            CKA_SIGN => String::from(stringify!(CKA_SIGN)),
238            CKA_SIGN_RECOVER => String::from(stringify!(CKA_SIGN_RECOVER)),
239            CKA_VERIFY => String::from(stringify!(CKA_VERIFY)),
240            CKA_VERIFY_RECOVER => String::from(stringify!(CKA_VERIFY_RECOVER)),
241            CKA_DERIVE => String::from(stringify!(CKA_DERIVE)),
242            CKA_START_DATE => String::from(stringify!(CKA_START_DATE)),
243            CKA_END_DATE => String::from(stringify!(CKA_END_DATE)),
244            CKA_MODULUS => String::from(stringify!(CKA_MODULUS)),
245            CKA_MODULUS_BITS => String::from(stringify!(CKA_MODULUS_BITS)),
246            CKA_PUBLIC_EXPONENT => String::from(stringify!(CKA_PUBLIC_EXPONENT)),
247            CKA_PRIVATE_EXPONENT => String::from(stringify!(CKA_PRIVATE_EXPONENT)),
248            CKA_PRIME_1 => String::from(stringify!(CKA_PRIME_1)),
249            CKA_PRIME_2 => String::from(stringify!(CKA_PRIME_2)),
250            CKA_EXPONENT_1 => String::from(stringify!(CKA_EXPONENT_1)),
251            CKA_EXPONENT_2 => String::from(stringify!(CKA_EXPONENT_2)),
252            CKA_COEFFICIENT => String::from(stringify!(CKA_COEFFICIENT)),
253            CKA_PUBLIC_KEY_INFO => String::from(stringify!(CKA_PUBLIC_KEY_INFO)),
254            CKA_PRIME => String::from(stringify!(CKA_PRIME)),
255            CKA_SUBPRIME => String::from(stringify!(CKA_SUBPRIME)),
256            CKA_BASE => String::from(stringify!(CKA_BASE)),
257            CKA_PRIME_BITS => String::from(stringify!(CKA_PRIME_BITS)),
258            CKA_SUB_PRIME_BITS => String::from(stringify!(CKA_SUB_PRIME_BITS)),
259            CKA_VALUE_BITS => String::from(stringify!(CKA_VALUE_BITS)),
260            CKA_VALUE_LEN => String::from(stringify!(CKA_VALUE_LEN)),
261            CKA_EXTRACTABLE => String::from(stringify!(CKA_EXTRACTABLE)),
262            CKA_LOCAL => String::from(stringify!(CKA_LOCAL)),
263            CKA_NEVER_EXTRACTABLE => String::from(stringify!(CKA_NEVER_EXTRACTABLE)),
264            CKA_ALWAYS_SENSITIVE => String::from(stringify!(CKA_ALWAYS_SENSITIVE)),
265            CKA_KEY_GEN_MECHANISM => String::from(stringify!(CKA_KEY_GEN_MECHANISM)),
266            CKA_MODIFIABLE => String::from(stringify!(CKA_MODIFIABLE)),
267            CKA_COPYABLE => String::from(stringify!(CKA_COPYABLE)),
268            CKA_DESTROYABLE => String::from(stringify!(CKA_DESTROYABLE)),
269            CKA_EC_PARAMS => String::from(stringify!(CKA_EC_PARAMS)),
270            CKA_EC_POINT => String::from(stringify!(CKA_EC_POINT)),
271            CKA_SECONDARY_AUTH => String::from(stringify!(CKA_SECONDARY_AUTH)),
272            CKA_AUTH_PIN_FLAGS => String::from(stringify!(CKA_AUTH_PIN_FLAGS)),
273            CKA_ALWAYS_AUTHENTICATE => String::from(stringify!(CKA_ALWAYS_AUTHENTICATE)),
274            CKA_WRAP_WITH_TRUSTED => String::from(stringify!(CKA_WRAP_WITH_TRUSTED)),
275            CKA_OTP_FORMAT => String::from(stringify!(CKA_OTP_FORMAT)),
276            CKA_OTP_LENGTH => String::from(stringify!(CKA_OTP_LENGTH)),
277            CKA_OTP_TIME_INTERVAL => String::from(stringify!(CKA_OTP_TIME_INTERVAL)),
278            CKA_OTP_USER_FRIENDLY_MODE => String::from(stringify!(CKA_OTP_USER_FRIENDLY_MODE)),
279            CKA_OTP_CHALLENGE_REQUIREMENT => {
280                String::from(stringify!(CKA_OTP_CHALLENGE_REQUIREMENT))
281            }
282            CKA_OTP_TIME_REQUIREMENT => String::from(stringify!(CKA_OTP_TIME_REQUIREMENT)),
283            CKA_OTP_COUNTER_REQUIREMENT => String::from(stringify!(CKA_OTP_COUNTER_REQUIREMENT)),
284            CKA_OTP_PIN_REQUIREMENT => String::from(stringify!(CKA_OTP_PIN_REQUIREMENT)),
285            CKA_OTP_USER_IDENTIFIER => String::from(stringify!(CKA_OTP_USER_IDENTIFIER)),
286            CKA_OTP_SERVICE_IDENTIFIER => String::from(stringify!(CKA_OTP_SERVICE_IDENTIFIER)),
287            CKA_OTP_SERVICE_LOGO => String::from(stringify!(CKA_OTP_SERVICE_LOGO)),
288            CKA_OTP_SERVICE_LOGO_TYPE => String::from(stringify!(CKA_OTP_SERVICE_LOGO_TYPE)),
289            CKA_OTP_COUNTER => String::from(stringify!(CKA_OTP_COUNTER)),
290            CKA_OTP_TIME => String::from(stringify!(CKA_OTP_TIME)),
291            CKA_GOSTR3410_PARAMS => String::from(stringify!(CKA_GOSTR3410_PARAMS)),
292            CKA_GOSTR3411_PARAMS => String::from(stringify!(CKA_GOSTR3411_PARAMS)),
293            CKA_GOST28147_PARAMS => String::from(stringify!(CKA_GOST28147_PARAMS)),
294            CKA_HW_FEATURE_TYPE => String::from(stringify!(CKA_HW_FEATURE_TYPE)),
295            CKA_RESET_ON_INIT => String::from(stringify!(CKA_RESET_ON_INIT)),
296            CKA_HAS_RESET => String::from(stringify!(CKA_HAS_RESET)),
297            CKA_PIXEL_X => String::from(stringify!(CKA_PIXEL_X)),
298            CKA_PIXEL_Y => String::from(stringify!(CKA_PIXEL_Y)),
299            CKA_RESOLUTION => String::from(stringify!(CKA_RESOLUTION)),
300            CKA_CHAR_ROWS => String::from(stringify!(CKA_CHAR_ROWS)),
301            CKA_CHAR_COLUMNS => String::from(stringify!(CKA_CHAR_COLUMNS)),
302            CKA_COLOR => String::from(stringify!(CKA_COLOR)),
303            CKA_BITS_PER_PIXEL => String::from(stringify!(CKA_BITS_PER_PIXEL)),
304            CKA_CHAR_SETS => String::from(stringify!(CKA_CHAR_SETS)),
305            CKA_ENCODING_METHODS => String::from(stringify!(CKA_ENCODING_METHODS)),
306            CKA_MIME_TYPES => String::from(stringify!(CKA_MIME_TYPES)),
307            CKA_MECHANISM_TYPE => String::from(stringify!(CKA_MECHANISM_TYPE)),
308            CKA_REQUIRED_CMS_ATTRIBUTES => String::from(stringify!(CKA_REQUIRED_CMS_ATTRIBUTES)),
309            CKA_DEFAULT_CMS_ATTRIBUTES => String::from(stringify!(CKA_DEFAULT_CMS_ATTRIBUTES)),
310            CKA_SUPPORTED_CMS_ATTRIBUTES => String::from(stringify!(CKA_SUPPORTED_CMS_ATTRIBUTES)),
311            CKA_WRAP_TEMPLATE => String::from(stringify!(CKA_WRAP_TEMPLATE)),
312            CKA_UNWRAP_TEMPLATE => String::from(stringify!(CKA_UNWRAP_TEMPLATE)),
313            CKA_DERIVE_TEMPLATE => String::from(stringify!(CKA_DERIVE_TEMPLATE)),
314            CKA_ALLOWED_MECHANISMS => String::from(stringify!(CKA_ALLOWED_MECHANISMS)),
315            CKA_UNIQUE_ID => String::from(stringify!(CKA_UNIQUE_ID)),
316            CKA_SEED => String::from(stringify!(CKA_SEED)),
317            CKA_PARAMETER_SET => String::from(stringify!(CKA_PARAMETER_SET)),
318            CKA_PROFILE_ID => String::from(stringify!(CKA_PROFILE_ID)),
319            CKA_OBJECT_VALIDATION_FLAGS => String::from(stringify!(CKA_OBJECT_VALIDATION_FLAGS)),
320            CKA_VALIDATION_TYPE => String::from(stringify!(CKA_VALIDATION_TYPE)),
321            CKA_VALIDATION_VERSION => String::from(stringify!(CKA_VALIDATION_VERSION)),
322            CKA_VALIDATION_LEVEL => String::from(stringify!(CKA_VALIDATION_LEVEL)),
323            CKA_VALIDATION_MODULE_ID => String::from(stringify!(CKA_VALIDATION_MODULE_ID)),
324            CKA_VALIDATION_FLAG => String::from(stringify!(CKA_VALIDATION_FLAG)),
325            CKA_VALIDATION_AUTHORITY_TYPE => {
326                String::from(stringify!(CKA_VALIDATION_AUTHORITY_TYPE))
327            }
328            CKA_VALIDATION_COUNTRY => String::from(stringify!(CKA_VALIDATION_COUNTRY)),
329            CKA_VALIDATION_CERTIFICATE_IDENTIFIER => {
330                String::from(stringify!(CKA_VALIDATION_CERTIFICATE_IDENTIFIER))
331            }
332            CKA_VALIDATION_CERTIFICATE_URI => {
333                String::from(stringify!(CKA_VALIDATION_CERTIFICATE_URI))
334            }
335            CKA_VALIDATION_VENDOR_URI => String::from(stringify!(CKA_VALIDATION_VENDOR_URI)),
336            CKA_VALIDATION_PROFILE => String::from(stringify!(CKA_VALIDATION_PROFILE)),
337            CKA_VENDOR_DEFINED..=CK_ULONG::MAX => {
338                format!("{}_{}", stringify!(CKA_VENDOR_DEFINED), val)
339            }
340            _ => format!("unknown ({val:08x})"),
341        }
342    }
343
344    /// Returns the fixed size of an attribute type if known.
345    ///
346    /// This method returns `Some(size)` for attributes with a known fixed size,
347    /// and `None` for variable-length attributes. This is useful for optimizing
348    /// attribute retrieval by pre-allocating buffers of the correct size.
349    ///
350    /// # Returns
351    ///
352    /// * `Some(usize)` - The fixed size in bytes for attributes with known fixed size
353    /// * `None` - For variable-length attributes (e.g., Label, Modulus, Value, etc.)
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// use cryptoki::object::AttributeType;
359    /// use std::mem::size_of;
360    /// use cryptoki_sys::{CK_ULONG, CK_BBOOL};
361    ///
362    /// // Fixed-size attributes
363    /// assert_eq!(AttributeType::Class.fixed_size(), Some(size_of::<CK_ULONG>()));
364    /// assert_eq!(AttributeType::Token.fixed_size(), Some(size_of::<CK_BBOOL>()));
365    ///
366    /// // Variable-length attributes
367    /// assert_eq!(AttributeType::Label.fixed_size(), None);
368    /// assert_eq!(AttributeType::Modulus.fixed_size(), None);
369    /// ```
370    pub fn fixed_size(&self) -> Option<usize> {
371        match self {
372            // CK_BBOOL
373            AttributeType::Token
374            | AttributeType::Private
375            | AttributeType::Modifiable
376            | AttributeType::Copyable
377            | AttributeType::Destroyable
378            | AttributeType::Sensitive
379            | AttributeType::Encrypt
380            | AttributeType::Decrypt
381            | AttributeType::Wrap
382            | AttributeType::Unwrap
383            | AttributeType::Sign
384            | AttributeType::SignRecover
385            | AttributeType::Verify
386            | AttributeType::VerifyRecover
387            | AttributeType::Derive
388            | AttributeType::Extractable
389            | AttributeType::Local
390            | AttributeType::NeverExtractable
391            | AttributeType::AlwaysSensitive
392            | AttributeType::WrapWithTrusted
393            | AttributeType::Trusted
394            | AttributeType::AlwaysAuthenticate
395            | AttributeType::Encapsulate
396            | AttributeType::Decapsulate => Some(size_of::<CK_BBOOL>()),
397
398            // CK_ULONG or aliases (CK_OBJECT_CLASS, CK_KEY_TYPE, CK_CERTIFICATE_TYPE, etc.)
399            AttributeType::Class
400            | AttributeType::KeyType
401            | AttributeType::CertificateType
402            | AttributeType::ModulusBits
403            | AttributeType::ValueLen
404            | AttributeType::ObjectValidationFlags
405            | AttributeType::ParameterSet
406            | AttributeType::ValidationFlag
407            | AttributeType::ValidationType
408            | AttributeType::ValidationLevel
409            | AttributeType::ValidationAuthorityType
410            | AttributeType::ProfileId
411            | AttributeType::KeyGenMechanism => Some(size_of::<CK_ULONG>()),
412
413            // CK_DATE (8 bytes: year[4] + month[2] + day[2])
414            AttributeType::StartDate | AttributeType::EndDate => Some(size_of::<CK_DATE>()),
415
416            // CK_VERSION (2 bytes: major + minor)
417            AttributeType::ValidationVersion => Some(size_of::<CK_VERSION>()),
418
419            // CK_VALIDATION_COUNTRY (2 CK_UTF8CHAR, typically 2 bytes for ISO country code)
420            AttributeType::ValidationCountry => Some(size_of::<[CK_UTF8CHAR; 2]>()),
421
422            // Variable-length attributes
423            AttributeType::AcIssuer
424            | AttributeType::AllowedMechanisms
425            | AttributeType::Application
426            | AttributeType::AttrTypes
427            | AttributeType::Base
428            | AttributeType::CheckValue
429            | AttributeType::Coefficient
430            | AttributeType::EcParams
431            | AttributeType::EcPoint
432            | AttributeType::Exponent1
433            | AttributeType::Exponent2
434            | AttributeType::HashOfIssuerPublicKey
435            | AttributeType::HashOfSubjectPublicKey
436            | AttributeType::Id
437            | AttributeType::Issuer
438            | AttributeType::Label
439            | AttributeType::Modulus
440            | AttributeType::ObjectId
441            | AttributeType::Owner
442            | AttributeType::Prime
443            | AttributeType::Prime1
444            | AttributeType::Prime2
445            | AttributeType::PrivateExponent
446            | AttributeType::PublicExponent
447            | AttributeType::PublicKeyInfo
448            | AttributeType::Seed
449            | AttributeType::SerialNumber
450            | AttributeType::Subject
451            | AttributeType::UniqueId
452            | AttributeType::Url
453            | AttributeType::ValidationModuleId
454            | AttributeType::ValidationCertificateIdentifier
455            | AttributeType::ValidationCertificateUri
456            | AttributeType::ValidationVendorUri
457            | AttributeType::ValidationProfile
458            | AttributeType::Value
459            | AttributeType::VendorDefined(_) => None,
460        }
461    }
462}
463
464impl std::fmt::Display for AttributeType {
465    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
466        let attrib: CK_ATTRIBUTE_TYPE = (*self).into();
467        write!(f, "{}", AttributeType::stringify(attrib))
468    }
469}
470
471impl From<AttributeType> for CK_ATTRIBUTE_TYPE {
472    fn from(attribute_type: AttributeType) -> Self {
473        match attribute_type {
474            AttributeType::AcIssuer => CKA_AC_ISSUER,
475            AttributeType::AllowedMechanisms => CKA_ALLOWED_MECHANISMS,
476            AttributeType::AlwaysAuthenticate => CKA_ALWAYS_AUTHENTICATE,
477            AttributeType::AlwaysSensitive => CKA_ALWAYS_SENSITIVE,
478            AttributeType::Application => CKA_APPLICATION,
479            AttributeType::AttrTypes => CKA_ATTR_TYPES,
480            AttributeType::Base => CKA_BASE,
481            AttributeType::CertificateType => CKA_CERTIFICATE_TYPE,
482            AttributeType::CheckValue => CKA_CHECK_VALUE,
483            AttributeType::Class => CKA_CLASS,
484            AttributeType::Coefficient => CKA_COEFFICIENT,
485            AttributeType::Copyable => CKA_COPYABLE,
486            AttributeType::Decapsulate => CKA_DECAPSULATE,
487            AttributeType::Decrypt => CKA_DECRYPT,
488            AttributeType::Derive => CKA_DERIVE,
489            AttributeType::Destroyable => CKA_DESTROYABLE,
490            AttributeType::EcParams => CKA_EC_PARAMS,
491            AttributeType::EcPoint => CKA_EC_POINT,
492            AttributeType::Encapsulate => CKA_ENCAPSULATE,
493            AttributeType::Encrypt => CKA_ENCRYPT,
494            AttributeType::EndDate => CKA_END_DATE,
495            AttributeType::Exponent1 => CKA_EXPONENT_1,
496            AttributeType::Exponent2 => CKA_EXPONENT_2,
497            AttributeType::Extractable => CKA_EXTRACTABLE,
498            AttributeType::HashOfIssuerPublicKey => CKA_HASH_OF_ISSUER_PUBLIC_KEY,
499            AttributeType::HashOfSubjectPublicKey => CKA_HASH_OF_SUBJECT_PUBLIC_KEY,
500            AttributeType::Id => CKA_ID,
501            AttributeType::Issuer => CKA_ISSUER,
502            AttributeType::KeyGenMechanism => CKA_KEY_GEN_MECHANISM,
503            AttributeType::KeyType => CKA_KEY_TYPE,
504            AttributeType::Label => CKA_LABEL,
505            AttributeType::Local => CKA_LOCAL,
506            AttributeType::Modifiable => CKA_MODIFIABLE,
507            AttributeType::Modulus => CKA_MODULUS,
508            AttributeType::ModulusBits => CKA_MODULUS_BITS,
509            AttributeType::NeverExtractable => CKA_NEVER_EXTRACTABLE,
510            AttributeType::ObjectValidationFlags => CKA_OBJECT_VALIDATION_FLAGS,
511            AttributeType::ObjectId => CKA_OBJECT_ID,
512            AttributeType::Owner => CKA_OWNER,
513            AttributeType::ParameterSet => CKA_PARAMETER_SET,
514            AttributeType::Prime => CKA_PRIME,
515            AttributeType::Prime1 => CKA_PRIME_1,
516            AttributeType::Prime2 => CKA_PRIME_2,
517            AttributeType::Private => CKA_PRIVATE,
518            AttributeType::PrivateExponent => CKA_PRIVATE_EXPONENT,
519            AttributeType::ProfileId => CKA_PROFILE_ID,
520            AttributeType::PublicExponent => CKA_PUBLIC_EXPONENT,
521            AttributeType::PublicKeyInfo => CKA_PUBLIC_KEY_INFO,
522            AttributeType::Seed => CKA_SEED,
523            AttributeType::Sensitive => CKA_SENSITIVE,
524            AttributeType::SerialNumber => CKA_SERIAL_NUMBER,
525            AttributeType::Sign => CKA_SIGN,
526            AttributeType::SignRecover => CKA_SIGN_RECOVER,
527            AttributeType::StartDate => CKA_START_DATE,
528            AttributeType::Subject => CKA_SUBJECT,
529            AttributeType::Token => CKA_TOKEN,
530            AttributeType::Trusted => CKA_TRUSTED,
531            AttributeType::UniqueId => CKA_UNIQUE_ID,
532            AttributeType::Unwrap => CKA_UNWRAP,
533            AttributeType::Url => CKA_URL,
534            AttributeType::ValidationType => CKA_VALIDATION_TYPE,
535            AttributeType::ValidationVersion => CKA_VALIDATION_VERSION,
536            AttributeType::ValidationLevel => CKA_VALIDATION_LEVEL,
537            AttributeType::ValidationModuleId => CKA_VALIDATION_MODULE_ID,
538            AttributeType::ValidationFlag => CKA_VALIDATION_FLAG,
539            AttributeType::ValidationAuthorityType => CKA_VALIDATION_AUTHORITY_TYPE,
540            AttributeType::ValidationCountry => CKA_VALIDATION_COUNTRY,
541            AttributeType::ValidationCertificateIdentifier => CKA_VALIDATION_CERTIFICATE_IDENTIFIER,
542            AttributeType::ValidationCertificateUri => CKA_VALIDATION_CERTIFICATE_URI,
543            AttributeType::ValidationVendorUri => CKA_VALIDATION_VENDOR_URI,
544            AttributeType::ValidationProfile => CKA_VALIDATION_PROFILE,
545            AttributeType::Value => CKA_VALUE,
546            AttributeType::ValueLen => CKA_VALUE_LEN,
547            AttributeType::VendorDefined(val) => val,
548            AttributeType::Verify => CKA_VERIFY,
549            AttributeType::VerifyRecover => CKA_VERIFY_RECOVER,
550            AttributeType::Wrap => CKA_WRAP,
551            AttributeType::WrapWithTrusted => CKA_WRAP_WITH_TRUSTED,
552        }
553    }
554}
555
556impl TryFrom<CK_ATTRIBUTE_TYPE> for AttributeType {
557    type Error = Error;
558
559    fn try_from(attribute_type: CK_ATTRIBUTE_TYPE) -> Result<Self> {
560        match attribute_type {
561            CKA_AC_ISSUER => Ok(AttributeType::AcIssuer),
562            CKA_ALLOWED_MECHANISMS => Ok(AttributeType::AllowedMechanisms),
563            CKA_ALWAYS_AUTHENTICATE => Ok(AttributeType::AlwaysAuthenticate),
564            CKA_ALWAYS_SENSITIVE => Ok(AttributeType::AlwaysSensitive),
565            CKA_APPLICATION => Ok(AttributeType::Application),
566            CKA_ATTR_TYPES => Ok(AttributeType::AttrTypes),
567            CKA_BASE => Ok(AttributeType::Base),
568            CKA_CERTIFICATE_TYPE => Ok(AttributeType::CertificateType),
569            CKA_CHECK_VALUE => Ok(AttributeType::CheckValue),
570            CKA_CLASS => Ok(AttributeType::Class),
571            CKA_COEFFICIENT => Ok(AttributeType::Coefficient),
572            CKA_COPYABLE => Ok(AttributeType::Copyable),
573            CKA_DECAPSULATE => Ok(AttributeType::Decapsulate),
574            CKA_DECRYPT => Ok(AttributeType::Decrypt),
575            CKA_DERIVE => Ok(AttributeType::Derive),
576            CKA_DESTROYABLE => Ok(AttributeType::Destroyable),
577            CKA_EC_PARAMS => Ok(AttributeType::EcParams),
578            CKA_EC_POINT => Ok(AttributeType::EcPoint),
579            CKA_ENCAPSULATE => Ok(AttributeType::Encapsulate),
580            CKA_ENCRYPT => Ok(AttributeType::Encrypt),
581            CKA_END_DATE => Ok(AttributeType::EndDate),
582            CKA_EXPONENT_1 => Ok(AttributeType::Exponent1),
583            CKA_EXPONENT_2 => Ok(AttributeType::Exponent2),
584            CKA_EXTRACTABLE => Ok(AttributeType::Extractable),
585            CKA_HASH_OF_ISSUER_PUBLIC_KEY => Ok(AttributeType::HashOfIssuerPublicKey),
586            CKA_HASH_OF_SUBJECT_PUBLIC_KEY => Ok(AttributeType::HashOfSubjectPublicKey),
587            CKA_ID => Ok(AttributeType::Id),
588            CKA_ISSUER => Ok(AttributeType::Issuer),
589            CKA_KEY_GEN_MECHANISM => Ok(AttributeType::KeyGenMechanism),
590            CKA_KEY_TYPE => Ok(AttributeType::KeyType),
591            CKA_LABEL => Ok(AttributeType::Label),
592            CKA_LOCAL => Ok(AttributeType::Local),
593            CKA_MODIFIABLE => Ok(AttributeType::Modifiable),
594            CKA_MODULUS => Ok(AttributeType::Modulus),
595            CKA_MODULUS_BITS => Ok(AttributeType::ModulusBits),
596            CKA_NEVER_EXTRACTABLE => Ok(AttributeType::NeverExtractable),
597            CKA_OBJECT_VALIDATION_FLAGS => Ok(AttributeType::ObjectValidationFlags),
598            CKA_OBJECT_ID => Ok(AttributeType::ObjectId),
599            CKA_OWNER => Ok(AttributeType::Owner),
600            CKA_PARAMETER_SET => Ok(AttributeType::ParameterSet),
601            CKA_PRIME => Ok(AttributeType::Prime),
602            CKA_PRIME_1 => Ok(AttributeType::Prime1),
603            CKA_PRIME_2 => Ok(AttributeType::Prime2),
604            CKA_PRIVATE => Ok(AttributeType::Private),
605            CKA_PRIVATE_EXPONENT => Ok(AttributeType::PrivateExponent),
606            CKA_PROFILE_ID => Ok(AttributeType::ProfileId),
607            CKA_PUBLIC_EXPONENT => Ok(AttributeType::PublicExponent),
608            CKA_PUBLIC_KEY_INFO => Ok(AttributeType::PublicKeyInfo),
609            CKA_SEED => Ok(AttributeType::Seed),
610            CKA_SENSITIVE => Ok(AttributeType::Sensitive),
611            CKA_SERIAL_NUMBER => Ok(AttributeType::SerialNumber),
612            CKA_SIGN => Ok(AttributeType::Sign),
613            CKA_SIGN_RECOVER => Ok(AttributeType::SignRecover),
614            CKA_START_DATE => Ok(AttributeType::StartDate),
615            CKA_SUBJECT => Ok(AttributeType::Subject),
616            CKA_TOKEN => Ok(AttributeType::Token),
617            CKA_TRUSTED => Ok(AttributeType::Trusted),
618            CKA_UNIQUE_ID => Ok(AttributeType::UniqueId),
619            CKA_UNWRAP => Ok(AttributeType::Unwrap),
620            CKA_URL => Ok(AttributeType::Url),
621            CKA_VALIDATION_TYPE => Ok(AttributeType::ValidationType),
622            CKA_VALIDATION_VERSION => Ok(AttributeType::ValidationVersion),
623            CKA_VALIDATION_LEVEL => Ok(AttributeType::ValidationLevel),
624            CKA_VALIDATION_MODULE_ID => Ok(AttributeType::ValidationModuleId),
625            CKA_VALIDATION_FLAG => Ok(AttributeType::ValidationFlag),
626            CKA_VALIDATION_AUTHORITY_TYPE => Ok(AttributeType::ValidationAuthorityType),
627            CKA_VALIDATION_COUNTRY => Ok(AttributeType::ValidationCountry),
628            CKA_VALIDATION_CERTIFICATE_IDENTIFIER => {
629                Ok(AttributeType::ValidationCertificateIdentifier)
630            }
631            CKA_VALIDATION_CERTIFICATE_URI => Ok(AttributeType::ValidationCertificateUri),
632            CKA_VALIDATION_PROFILE => Ok(AttributeType::ValidationProfile),
633            CKA_VALUE => Ok(AttributeType::Value),
634            CKA_VALUE_LEN => Ok(AttributeType::ValueLen),
635            CKA_VERIFY => Ok(AttributeType::Verify),
636            CKA_VERIFY_RECOVER => Ok(AttributeType::VerifyRecover),
637            CKA_WRAP => Ok(AttributeType::Wrap),
638            CKA_WRAP_WITH_TRUSTED => Ok(AttributeType::WrapWithTrusted),
639            CKA_VENDOR_DEFINED..=CK_ULONG::MAX => Ok(AttributeType::VendorDefined(attribute_type)),
640            attr_type => {
641                error!("Attribute type {attr_type} not supported.");
642                Err(Error::NotSupported)
643            }
644        }
645    }
646}
647
648#[derive(Debug, Clone, PartialEq, Eq)]
649#[non_exhaustive]
650/// Attribute value
651pub enum Attribute {
652    /// DER-encoding of the attribute certificate's issuer
653    AcIssuer(Vec<u8>),
654    /// List of mechanisms allowed to be used with the key
655    AllowedMechanisms(Vec<MechanismType>),
656    /// Indicates that the user has to supply the PIN for each use with the key
657    AlwaysAuthenticate(bool),
658    /// Indicates if the key has always had the Sensitive attribute set to true
659    AlwaysSensitive(bool),
660    /// Description of the application that manages the object
661    Application(Vec<u8>),
662    /// BER-encoding of a sequence of object identifier values
663    AttrTypes(Vec<u8>),
664    /// Base number value of a key
665    Base(Vec<u8>),
666    /// Type of certificate
667    CertificateType(CertificateType),
668    /// Checksum
669    CheckValue(Vec<u8>),
670    /// Type of an object
671    Class(ObjectClass),
672    /// The CRT coefficient `iqmp` of an RSA private key
673    Coefficient(Vec<u8>),
674    /// Determines if an object can be copied
675    Copyable(bool),
676    /// Determines if a key supports key decapsulation
677    Decapsulate(bool),
678    /// Determines if a key supports decryption
679    Decrypt(bool),
680    /// Determines if it is possible to derive other keys from the key
681    Derive(bool),
682    /// Determines if it is possible to destroy an object
683    Destroyable(bool),
684    /// Parameters describing an elliptic curve
685    EcParams(Vec<u8>),
686    /// Elliptic Curve point
687    EcPoint(Vec<u8>),
688    /// Determines if a key supports key encapsulation
689    Encapsulate(bool),
690    /// Determines if a key supports encryption
691    Encrypt(bool),
692    /// The end date of the object
693    EndDate(Date),
694    /// The private exponent `dmp1` of an RSA private key
695    Exponent1(Vec<u8>),
696    /// The private exponent `dmq1` of an RSA private key
697    Exponent2(Vec<u8>),
698    /// Determines if a key is extractable and can be wrapped
699    Extractable(bool),
700    /// Hash of issuer public key
701    HashOfIssuerPublicKey(Vec<u8>),
702    /// Hash of subject public key
703    HashOfSubjectPublicKey(Vec<u8>),
704    /// Key identifier for key
705    Id(Vec<u8>),
706    /// DER-encoding of the certificate issuer name
707    Issuer(Vec<u8>),
708    /// Identifier of the mechanism used to generate the key material
709    KeyGenMechanism(MechanismType),
710    /// Type of a key
711    KeyType(KeyType),
712    /// Description of the object
713    Label(Vec<u8>),
714    /// Indicates if the key was generated locally or copied from a locally created object
715    Local(bool),
716    /// Determines if the object can be modified
717    Modifiable(bool),
718    /// Modulus value of a key
719    Modulus(Vec<u8>),
720    /// Length in bits of the modulus of a key
721    ModulusBits(Ulong),
722    /// Indicates if the key has never had the Extractable attribute set to true
723    NeverExtractable(bool),
724    /// Object Validation Flags
725    ObjectValidationFlags(Ulong),
726    /// Object ID
727    ObjectId(Vec<u8>),
728    /// DER encoding of the attribute certificate's subject field
729    Owner(Vec<u8>),
730    /// Algorithm specific parameter set, now used for ML-DSA and ML-KEM algorithms
731    ParameterSet(ParameterSetType),
732    /// Prime number value of a key
733    Prime(Vec<u8>),
734    /// The prime `p` of an RSA private key
735    Prime1(Vec<u8>),
736    /// The prime `q` of an RSA private key
737    Prime2(Vec<u8>),
738    /// Determines if the object is private
739    Private(bool),
740    /// The private exponent `d`
741    PrivateExponent(Vec<u8>),
742    /// The Profile ID
743    ProfileId(ProfileIdType),
744    /// Public exponent value of a key
745    PublicExponent(Vec<u8>),
746    /// DER-encoding of the SubjectPublicKeyInfo
747    PublicKeyInfo(Vec<u8>),
748    /// Seed to derive private key
749    Seed(Vec<u8>),
750    /// Determines if the key is sensitive
751    Sensitive(bool),
752    /// DER encoding of the certificate serial number
753    SerialNumber(Vec<u8>),
754    /// Determines if a key supports signing
755    Sign(bool),
756    /// Determines if a key supports signing where the data can be recovered from the signature
757    SignRecover(bool),
758    /// The start date of the object
759    StartDate(Date),
760    /// DER-encoding of certificate subject name
761    Subject(Vec<u8>),
762    /// Determines if the object is a token object
763    Token(bool),
764    /// Determines if an object is trusted
765    Trusted(bool),
766    /// Unique Object Id
767    UniqueId(Vec<u8>),
768    /// Determines if a key supports unwrapping
769    Unwrap(bool),
770    /// Gives the URL where the complete certificate can ber obtained
771    Url(Vec<u8>),
772    /// Identifier indicating the validation type
773    ValidationType(ValidationType),
774    /// Version of the validation standard or specification
775    ValidationVersion(Version),
776    /// Validation level, Meaning is Validation type specific
777    ValidationLevel(Ulong),
778    /// How the module is identified in the validation documentation
779    ValidationModuleId(Vec<u8>),
780    /// Flags identifying this validation in sessions and objects
781    ValidationFlag(Ulong),
782    /// Identifies the authority that issues the validation
783    ValidationAuthorityType(ValidationAuthorityType),
784    /// 2 letter ISO country code
785    ValidationCountry(Vec<u8>),
786    /// Identifier of the validation certificate
787    ValidationCertificateIdentifier(Vec<u8>),
788    /// Validation authority URI from which information related to the validation is available. If the Validation
789    /// Certificate URI is not provided, the validation object SHOULD include a Validation Vendor URI.
790    ValidationCertificateUri(Vec<u8>),
791    /// Validation Vendor URI from which information related to the validation is available.
792    ValidationVendorUri(Vec<u8>),
793    /// Profile used for validation
794    ValidationProfile(Vec<u8>),
795    /// Value of the object
796    Value(Vec<u8>),
797    /// Length in bytes of the value
798    ValueLen(Ulong),
799    /// Vendor defined value
800    VendorDefined((AttributeType, Vec<u8>)),
801    /// Determines if a key supports verifying
802    Verify(bool),
803    /// Determines if a key supports verifying where the data can be recovered from the signature
804    VerifyRecover(bool),
805    /// Determines if a key supports wrapping
806    Wrap(bool),
807    /// Indicates that the key can only be wrapped with a wrapping key that has the Trusted attribute
808    WrapWithTrusted(bool),
809}
810
811impl Attribute {
812    /// Get the type of an attribute
813    pub fn attribute_type(&self) -> AttributeType {
814        match self {
815            Attribute::AcIssuer(_) => AttributeType::AcIssuer,
816            Attribute::AllowedMechanisms(_) => AttributeType::AllowedMechanisms,
817            Attribute::AlwaysAuthenticate(_) => AttributeType::AlwaysAuthenticate,
818            Attribute::AlwaysSensitive(_) => AttributeType::AlwaysSensitive,
819            Attribute::Application(_) => AttributeType::Application,
820            Attribute::AttrTypes(_) => AttributeType::AttrTypes,
821            Attribute::Base(_) => AttributeType::Base,
822            Attribute::CertificateType(_) => AttributeType::CertificateType,
823            Attribute::CheckValue(_) => AttributeType::CheckValue,
824            Attribute::Class(_) => AttributeType::Class,
825            Attribute::Coefficient(_) => AttributeType::Coefficient,
826            Attribute::Copyable(_) => AttributeType::Copyable,
827            Attribute::Decapsulate(_) => AttributeType::Decapsulate,
828            Attribute::Decrypt(_) => AttributeType::Decrypt,
829            Attribute::Derive(_) => AttributeType::Derive,
830            Attribute::Destroyable(_) => AttributeType::Destroyable,
831            Attribute::EcParams(_) => AttributeType::EcParams,
832            Attribute::EcPoint(_) => AttributeType::EcPoint,
833            Attribute::Encapsulate(_) => AttributeType::Encapsulate,
834            Attribute::Encrypt(_) => AttributeType::Encrypt,
835            Attribute::EndDate(_) => AttributeType::EndDate,
836            Attribute::Exponent1(_) => AttributeType::Exponent1,
837            Attribute::Exponent2(_) => AttributeType::Exponent2,
838            Attribute::Extractable(_) => AttributeType::Extractable,
839            Attribute::HashOfIssuerPublicKey(_) => AttributeType::HashOfIssuerPublicKey,
840            Attribute::HashOfSubjectPublicKey(_) => AttributeType::HashOfSubjectPublicKey,
841            Attribute::Id(_) => AttributeType::Id,
842            Attribute::Issuer(_) => AttributeType::Issuer,
843            Attribute::KeyGenMechanism(_) => AttributeType::KeyGenMechanism,
844            Attribute::KeyType(_) => AttributeType::KeyType,
845            Attribute::Label(_) => AttributeType::Label,
846            Attribute::Local(_) => AttributeType::Local,
847            Attribute::Modifiable(_) => AttributeType::Modifiable,
848            Attribute::Modulus(_) => AttributeType::Modulus,
849            Attribute::ModulusBits(_) => AttributeType::ModulusBits,
850            Attribute::NeverExtractable(_) => AttributeType::NeverExtractable,
851            Attribute::ObjectValidationFlags(_) => AttributeType::ObjectValidationFlags,
852            Attribute::ObjectId(_) => AttributeType::ObjectId,
853            Attribute::Owner(_) => AttributeType::Owner,
854            Attribute::ParameterSet(_) => AttributeType::ParameterSet,
855            Attribute::Prime(_) => AttributeType::Prime,
856            Attribute::Prime1(_) => AttributeType::Prime1,
857            Attribute::Prime2(_) => AttributeType::Prime2,
858            Attribute::Private(_) => AttributeType::Private,
859            Attribute::PrivateExponent(_) => AttributeType::PrivateExponent,
860            Attribute::ProfileId(_) => AttributeType::ProfileId,
861            Attribute::PublicExponent(_) => AttributeType::PublicExponent,
862            Attribute::PublicKeyInfo(_) => AttributeType::PublicKeyInfo,
863            Attribute::Seed(_) => AttributeType::Seed,
864            Attribute::Sensitive(_) => AttributeType::Sensitive,
865            Attribute::SerialNumber(_) => AttributeType::SerialNumber,
866            Attribute::Sign(_) => AttributeType::Sign,
867            Attribute::SignRecover(_) => AttributeType::SignRecover,
868            Attribute::StartDate(_) => AttributeType::StartDate,
869            Attribute::Subject(_) => AttributeType::Subject,
870            Attribute::Token(_) => AttributeType::Token,
871            Attribute::Trusted(_) => AttributeType::Trusted,
872            Attribute::UniqueId(_) => AttributeType::UniqueId,
873            Attribute::Unwrap(_) => AttributeType::Unwrap,
874            Attribute::Url(_) => AttributeType::Url,
875            Attribute::ValidationType(_) => AttributeType::ValidationType,
876            Attribute::ValidationVersion(_) => AttributeType::ValidationVersion,
877            Attribute::ValidationLevel(_) => AttributeType::ValidationLevel,
878            Attribute::ValidationModuleId(_) => AttributeType::ValidationModuleId,
879            Attribute::ValidationFlag(_) => AttributeType::ValidationFlag,
880            Attribute::ValidationAuthorityType(_) => AttributeType::ValidationAuthorityType,
881            Attribute::ValidationCountry(_) => AttributeType::ValidationCountry,
882            Attribute::ValidationCertificateIdentifier(_) => {
883                AttributeType::ValidationCertificateIdentifier
884            }
885            Attribute::ValidationCertificateUri(_) => AttributeType::ValidationCertificateUri,
886            Attribute::ValidationVendorUri(_) => AttributeType::ValidationVendorUri,
887            Attribute::ValidationProfile(_) => AttributeType::ValidationProfile,
888            Attribute::Value(_) => AttributeType::Value,
889            Attribute::ValueLen(_) => AttributeType::ValueLen,
890            Attribute::VendorDefined((num, _)) => *num,
891            Attribute::Verify(_) => AttributeType::Verify,
892            Attribute::VerifyRecover(_) => AttributeType::VerifyRecover,
893            Attribute::Wrap(_) => AttributeType::Wrap,
894            Attribute::WrapWithTrusted(_) => AttributeType::WrapWithTrusted,
895        }
896    }
897
898    /// Returns the length in bytes of the objects contained by this CkAttribute.
899    fn len(&self) -> usize {
900        match self {
901            Attribute::AlwaysAuthenticate(_)
902            | Attribute::AlwaysSensitive(_)
903            | Attribute::Copyable(_)
904            | Attribute::Decapsulate(_)
905            | Attribute::Decrypt(_)
906            | Attribute::Derive(_)
907            | Attribute::Destroyable(_)
908            | Attribute::Encapsulate(_)
909            | Attribute::Encrypt(_)
910            | Attribute::Extractable(_)
911            | Attribute::Local(_)
912            | Attribute::Modifiable(_)
913            | Attribute::NeverExtractable(_)
914            | Attribute::Private(_)
915            | Attribute::Sensitive(_)
916            | Attribute::Sign(_)
917            | Attribute::SignRecover(_)
918            | Attribute::Token(_)
919            | Attribute::Trusted(_)
920            | Attribute::Unwrap(_)
921            | Attribute::Verify(_)
922            | Attribute::VerifyRecover(_)
923            | Attribute::Wrap(_)
924            | Attribute::WrapWithTrusted(_) => size_of::<bool>(),
925            Attribute::Base(_) => 1,
926            Attribute::Application(bytes)
927            | Attribute::Label(bytes)
928            | Attribute::Url(bytes)
929            | Attribute::ValidationModuleId(bytes)
930            | Attribute::ValidationCountry(bytes)
931            | Attribute::ValidationCertificateIdentifier(bytes)
932            | Attribute::ValidationCertificateUri(bytes)
933            | Attribute::ValidationVendorUri(bytes)
934            | Attribute::ValidationProfile(bytes) => size_of::<CK_UTF8CHAR>() * bytes.len(),
935            Attribute::AcIssuer(bytes) => bytes.len(),
936            Attribute::AttrTypes(bytes) => bytes.len(),
937            Attribute::CertificateType(_) => size_of::<CK_CERTIFICATE_TYPE>(),
938            Attribute::CheckValue(bytes) => bytes.len(),
939            Attribute::Class(_) => size_of::<CK_OBJECT_CLASS>(),
940            Attribute::Coefficient(bytes) => bytes.len(),
941            Attribute::EcParams(bytes) => bytes.len(),
942            Attribute::EcPoint(bytes) => bytes.len(),
943            Attribute::Exponent1(bytes) => bytes.len(),
944            Attribute::Exponent2(bytes) => bytes.len(),
945            Attribute::HashOfIssuerPublicKey(bytes) => bytes.len(),
946            Attribute::HashOfSubjectPublicKey(bytes) => bytes.len(),
947            Attribute::Id(bytes) => bytes.len(),
948            Attribute::Issuer(bytes) => bytes.len(),
949            Attribute::KeyGenMechanism(_) => size_of::<CK_MECHANISM_TYPE>(),
950            Attribute::KeyType(_) => size_of::<CK_KEY_TYPE>(),
951            Attribute::Modulus(bytes) => bytes.len(),
952            Attribute::ModulusBits(_) => size_of::<CK_ULONG>(),
953            Attribute::ObjectValidationFlags(_) => size_of::<CK_ULONG>(),
954            Attribute::ObjectId(bytes) => bytes.len(),
955            Attribute::Owner(bytes) => bytes.len(),
956            Attribute::ParameterSet(_) => size_of::<CK_ULONG>(),
957            Attribute::Prime(bytes) => bytes.len(),
958            Attribute::Prime1(bytes) => bytes.len(),
959            Attribute::Prime2(bytes) => bytes.len(),
960            Attribute::PrivateExponent(bytes) => bytes.len(),
961            Attribute::ProfileId(_) => size_of::<CK_PROFILE_ID>(),
962            Attribute::PublicExponent(bytes) => bytes.len(),
963            Attribute::PublicKeyInfo(bytes) => bytes.len(),
964            Attribute::Seed(bytes) => bytes.len(),
965            Attribute::SerialNumber(bytes) => bytes.len(),
966            Attribute::Subject(bytes) => bytes.len(),
967            Attribute::UniqueId(bytes) => bytes.len(),
968            Attribute::ValidationFlag(_) => size_of::<CK_FLAGS>(),
969            Attribute::ValidationType(_) => size_of::<CK_VALIDATION_TYPE>(),
970            Attribute::ValidationVersion(_) => size_of::<CK_VERSION>(),
971            Attribute::ValidationLevel(_) => size_of::<CK_ULONG>(),
972            Attribute::ValidationAuthorityType(_) => size_of::<CK_VALIDATION_AUTHORITY_TYPE>(),
973            Attribute::Value(bytes) => bytes.len(),
974            Attribute::ValueLen(_) => size_of::<CK_ULONG>(),
975            Attribute::EndDate(_) | Attribute::StartDate(_) => size_of::<CK_DATE>(),
976
977            Attribute::AllowedMechanisms(mechanisms) => {
978                size_of::<CK_MECHANISM_TYPE>() * mechanisms.len()
979            }
980            Attribute::VendorDefined((_, bytes)) => bytes.len(),
981        }
982    }
983
984    /// Returns a CK_VOID_PTR pointing to the object contained by this CkAttribute.
985    ///
986    /// Casting from an immutable reference to a mutable pointer is kind of unsafe but the
987    /// Attribute structure will only be used with PKCS11 functions that do not modify the template
988    /// given.
989    /// The C_GetAttributeValue function, which is the only one that modifies the template given,
990    /// will not use Attribute parameters but return them
991    /// directly to the caller.
992    fn ptr(&self) -> *mut c_void {
993        // Note: bools in Rust are guaranteed to occupy a byte, so
994        // &mut bool as a raw pointer will provide the same space
995        // needed for CK_BBOOL types. See also:
996        // https://doc.rust-lang.org/reference/type-layout.html#primitive-data-layout
997        match self {
998            // CK_BBOOL
999            Attribute::AlwaysAuthenticate(b)
1000            | Attribute::AlwaysSensitive(b)
1001            | Attribute::Copyable(b)
1002            | Attribute::Decapsulate(b)
1003            | Attribute::Decrypt(b)
1004            | Attribute::Derive(b)
1005            | Attribute::Destroyable(b)
1006            | Attribute::Encapsulate(b)
1007            | Attribute::Encrypt(b)
1008            | Attribute::Extractable(b)
1009            | Attribute::Local(b)
1010            | Attribute::Modifiable(b)
1011            | Attribute::NeverExtractable(b)
1012            | Attribute::Private(b)
1013            | Attribute::Sensitive(b)
1014            | Attribute::Sign(b)
1015            | Attribute::SignRecover(b)
1016            | Attribute::Token(b)
1017            | Attribute::Trusted(b)
1018            | Attribute::Unwrap(b)
1019            | Attribute::Verify(b)
1020            | Attribute::VerifyRecover(b)
1021            | Attribute::Wrap(b)
1022            | Attribute::WrapWithTrusted(b) => b as *const _ as *mut c_void,
1023            // CK_ULONG
1024            Attribute::ModulusBits(val)
1025            | Attribute::ValueLen(val)
1026            | Attribute::ObjectValidationFlags(val)
1027            | Attribute::ValidationLevel(val) => val as *const _ as *mut c_void,
1028            // Vec<u8>
1029            Attribute::AcIssuer(bytes)
1030            | Attribute::Application(bytes)
1031            | Attribute::AttrTypes(bytes)
1032            | Attribute::Base(bytes)
1033            | Attribute::CheckValue(bytes)
1034            | Attribute::Coefficient(bytes)
1035            | Attribute::EcParams(bytes)
1036            | Attribute::EcPoint(bytes)
1037            | Attribute::Exponent1(bytes)
1038            | Attribute::Exponent2(bytes)
1039            | Attribute::HashOfIssuerPublicKey(bytes)
1040            | Attribute::HashOfSubjectPublicKey(bytes)
1041            | Attribute::Issuer(bytes)
1042            | Attribute::Label(bytes)
1043            | Attribute::ObjectId(bytes)
1044            | Attribute::Prime(bytes)
1045            | Attribute::Prime1(bytes)
1046            | Attribute::Prime2(bytes)
1047            | Attribute::PrivateExponent(bytes)
1048            | Attribute::PublicExponent(bytes)
1049            | Attribute::PublicKeyInfo(bytes)
1050            | Attribute::Modulus(bytes)
1051            | Attribute::Owner(bytes)
1052            | Attribute::Seed(bytes)
1053            | Attribute::SerialNumber(bytes)
1054            | Attribute::Subject(bytes)
1055            | Attribute::UniqueId(bytes)
1056            | Attribute::Url(bytes)
1057            | Attribute::Value(bytes)
1058            | Attribute::ValidationModuleId(bytes)
1059            | Attribute::ValidationCountry(bytes)
1060            | Attribute::ValidationCertificateIdentifier(bytes)
1061            | Attribute::ValidationCertificateUri(bytes)
1062            | Attribute::ValidationVendorUri(bytes)
1063            | Attribute::ValidationProfile(bytes)
1064            | Attribute::VendorDefined((_, bytes))
1065            | Attribute::Id(bytes) => as_cptr!(bytes),
1066            // Unique types
1067            Attribute::ParameterSet(val) => val as *const _ as *mut c_void,
1068            Attribute::ProfileId(val) => val as *const _ as *mut c_void,
1069            Attribute::CertificateType(certificate_type) => {
1070                certificate_type as *const _ as *mut c_void
1071            }
1072            Attribute::Class(object_class) => object_class as *const _ as *mut c_void,
1073            Attribute::KeyGenMechanism(mech) => mech as *const _ as *mut c_void,
1074            Attribute::KeyType(key_type) => key_type as *const _ as *mut c_void,
1075            Attribute::ValidationFlag(flag) => flag as *const _ as *mut c_void,
1076            Attribute::ValidationType(validation_type) => {
1077                validation_type as *const _ as *mut c_void
1078            }
1079            Attribute::ValidationVersion(version) => version as *const _ as *mut c_void,
1080            Attribute::ValidationAuthorityType(authority_type) => {
1081                authority_type as *const _ as *mut c_void
1082            }
1083            Attribute::AllowedMechanisms(mechanisms) => as_cptr!(mechanisms),
1084            Attribute::EndDate(date) | Attribute::StartDate(date) => {
1085                date as *const _ as *mut c_void
1086            }
1087        }
1088    }
1089}
1090
1091impl From<&Attribute> for CK_ATTRIBUTE {
1092    fn from(attribute: &Attribute) -> Self {
1093        Self {
1094            type_: attribute.attribute_type().into(),
1095            pValue: attribute.ptr(),
1096            // The panic should only happen if there is a bug.
1097            ulValueLen: attribute
1098                .len()
1099                .try_into()
1100                .expect("Can not convert the attribute length value (usize) to a CK_ULONG."),
1101        }
1102    }
1103}
1104
1105/// Private function standing in for `TryInto<bool>` for `&[u8]`
1106/// which can't be implemented through the actual trait because
1107/// it and both types are external to this crate.
1108/// NB from the specification: "In Cryptoki, the CK_BBOOL data type
1109/// is a Boolean type that can be true or false. A zero value means
1110/// false, and a nonzero value means true." so there is no invalid
1111/// byte value.
1112fn try_u8_into_bool(slice: &[u8]) -> Result<bool> {
1113    let as_array: [u8; size_of::<CK_BBOOL>()] = slice.try_into()?;
1114    let as_byte = CK_BBOOL::from_ne_bytes(as_array);
1115    Ok(!matches!(as_byte, 0u8))
1116}
1117
1118impl TryFrom<CK_ATTRIBUTE> for Attribute {
1119    type Error = Error;
1120
1121    fn try_from(attribute: CK_ATTRIBUTE) -> Result<Self> {
1122        let attr_type = AttributeType::try_from(attribute.type_)?;
1123        let val = if attribute.pValue.is_null() {
1124            // if pValue is null, return an empty slice - attribute has no value
1125            &[]
1126        } else {
1127            // Cast from c_void to u8
1128            unsafe {
1129                std::slice::from_raw_parts(
1130                    attribute.pValue as *const u8,
1131                    attribute.ulValueLen.try_into()?,
1132                )
1133            }
1134        };
1135        match attr_type {
1136            // CK_BBOOL
1137            AttributeType::AlwaysAuthenticate => {
1138                Ok(Attribute::AlwaysAuthenticate(try_u8_into_bool(val)?))
1139            }
1140            AttributeType::AlwaysSensitive => {
1141                Ok(Attribute::AlwaysSensitive(try_u8_into_bool(val)?))
1142            }
1143            AttributeType::Copyable => Ok(Attribute::Copyable(try_u8_into_bool(val)?)),
1144            AttributeType::Decapsulate => Ok(Attribute::Decapsulate(try_u8_into_bool(val)?)),
1145            AttributeType::Decrypt => Ok(Attribute::Decrypt(try_u8_into_bool(val)?)),
1146            AttributeType::Derive => Ok(Attribute::Derive(try_u8_into_bool(val)?)),
1147            AttributeType::Destroyable => Ok(Attribute::Destroyable(try_u8_into_bool(val)?)),
1148            AttributeType::Encapsulate => Ok(Attribute::Encapsulate(try_u8_into_bool(val)?)),
1149            AttributeType::Encrypt => Ok(Attribute::Encrypt(try_u8_into_bool(val)?)),
1150            AttributeType::Extractable => Ok(Attribute::Extractable(try_u8_into_bool(val)?)),
1151            AttributeType::Local => Ok(Attribute::Local(try_u8_into_bool(val)?)),
1152            AttributeType::Modifiable => Ok(Attribute::Modifiable(try_u8_into_bool(val)?)),
1153            AttributeType::NeverExtractable => {
1154                Ok(Attribute::NeverExtractable(try_u8_into_bool(val)?))
1155            }
1156            AttributeType::Private => Ok(Attribute::Private(try_u8_into_bool(val)?)),
1157            AttributeType::Sensitive => Ok(Attribute::Sensitive(try_u8_into_bool(val)?)),
1158            AttributeType::Sign => Ok(Attribute::Sign(try_u8_into_bool(val)?)),
1159            AttributeType::SignRecover => Ok(Attribute::SignRecover(try_u8_into_bool(val)?)),
1160            AttributeType::Token => Ok(Attribute::Token(try_u8_into_bool(val)?)),
1161            AttributeType::Trusted => Ok(Attribute::Trusted(try_u8_into_bool(val)?)),
1162            AttributeType::Unwrap => Ok(Attribute::Unwrap(try_u8_into_bool(val)?)),
1163            AttributeType::Verify => Ok(Attribute::Verify(try_u8_into_bool(val)?)),
1164            AttributeType::VerifyRecover => Ok(Attribute::VerifyRecover(try_u8_into_bool(val)?)),
1165            AttributeType::Wrap => Ok(Attribute::Wrap(try_u8_into_bool(val)?)),
1166            AttributeType::WrapWithTrusted => {
1167                Ok(Attribute::WrapWithTrusted(try_u8_into_bool(val)?))
1168            }
1169            // CK_ULONG
1170            AttributeType::ModulusBits => Ok(Attribute::ModulusBits(
1171                CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1172            )),
1173            AttributeType::ValueLen => Ok(Attribute::ValueLen(
1174                CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1175            )),
1176            AttributeType::ObjectValidationFlags => Ok(Attribute::ObjectValidationFlags(
1177                CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1178            )),
1179            AttributeType::ValidationLevel => Ok(Attribute::ValidationLevel(
1180                CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1181            )),
1182            AttributeType::ValidationFlag => Ok(Attribute::ValidationFlag(
1183                CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1184            )),
1185            // Vec<u8>
1186            AttributeType::AcIssuer => Ok(Attribute::AcIssuer(val.to_vec())),
1187            AttributeType::Application => Ok(Attribute::Application(val.to_vec())),
1188            AttributeType::AttrTypes => Ok(Attribute::AttrTypes(val.to_vec())),
1189            AttributeType::Base => Ok(Attribute::Base(val.to_vec())),
1190            AttributeType::CheckValue => Ok(Attribute::CheckValue(val.to_vec())),
1191            AttributeType::Coefficient => Ok(Attribute::Coefficient(val.to_vec())),
1192            AttributeType::EcParams => Ok(Attribute::EcParams(val.to_vec())),
1193            AttributeType::EcPoint => Ok(Attribute::EcPoint(val.to_vec())),
1194            AttributeType::Exponent1 => Ok(Attribute::Exponent1(val.to_vec())),
1195            AttributeType::Exponent2 => Ok(Attribute::Exponent2(val.to_vec())),
1196            AttributeType::HashOfIssuerPublicKey => {
1197                Ok(Attribute::HashOfIssuerPublicKey(val.to_vec()))
1198            }
1199            AttributeType::HashOfSubjectPublicKey => {
1200                Ok(Attribute::HashOfSubjectPublicKey(val.to_vec()))
1201            }
1202            AttributeType::Issuer => Ok(Attribute::Issuer(val.to_vec())),
1203            AttributeType::Label => Ok(Attribute::Label(val.to_vec())),
1204            AttributeType::Prime => Ok(Attribute::Prime(val.to_vec())),
1205            AttributeType::Prime1 => Ok(Attribute::Prime1(val.to_vec())),
1206            AttributeType::Prime2 => Ok(Attribute::Prime2(val.to_vec())),
1207            AttributeType::PrivateExponent => Ok(Attribute::PrivateExponent(val.to_vec())),
1208            AttributeType::PublicExponent => Ok(Attribute::PublicExponent(val.to_vec())),
1209            AttributeType::PublicKeyInfo => Ok(Attribute::PublicKeyInfo(val.to_vec())),
1210            AttributeType::Modulus => Ok(Attribute::Modulus(val.to_vec())),
1211            AttributeType::ObjectId => Ok(Attribute::ObjectId(val.to_vec())),
1212            AttributeType::Owner => Ok(Attribute::Owner(val.to_vec())),
1213            AttributeType::Seed => Ok(Attribute::Seed(val.to_vec())),
1214            AttributeType::SerialNumber => Ok(Attribute::SerialNumber(val.to_vec())),
1215            AttributeType::Subject => Ok(Attribute::Subject(val.to_vec())),
1216            AttributeType::UniqueId => Ok(Attribute::UniqueId(val.to_vec())),
1217            AttributeType::Url => Ok(Attribute::Url(val.to_vec())),
1218            AttributeType::ValidationModuleId => Ok(Attribute::ValidationModuleId(val.to_vec())),
1219            AttributeType::ValidationCountry => Ok(Attribute::ValidationCountry(val.to_vec())),
1220            AttributeType::ValidationCertificateIdentifier => {
1221                Ok(Attribute::ValidationCertificateIdentifier(val.to_vec()))
1222            }
1223            AttributeType::ValidationCertificateUri => {
1224                Ok(Attribute::ValidationCertificateUri(val.to_vec()))
1225            }
1226            AttributeType::ValidationVendorUri => Ok(Attribute::ValidationVendorUri(val.to_vec())),
1227            AttributeType::ValidationProfile => Ok(Attribute::ValidationProfile(val.to_vec())),
1228            AttributeType::Value => Ok(Attribute::Value(val.to_vec())),
1229            AttributeType::Id => Ok(Attribute::Id(val.to_vec())),
1230            // Unique types
1231            AttributeType::ProfileId => Ok(Attribute::ProfileId(ProfileIdType {
1232                val: CK_ULONG::from_ne_bytes(val.try_into()?),
1233            })),
1234            AttributeType::ParameterSet => Ok(Attribute::ParameterSet(ParameterSetType {
1235                val: CK_ULONG::from_ne_bytes(val.try_into()?).into(),
1236            })),
1237            AttributeType::CertificateType => Ok(Attribute::CertificateType(
1238                CK_CERTIFICATE_TYPE::from_ne_bytes(val.try_into()?).try_into()?,
1239            )),
1240            AttributeType::Class => Ok(Attribute::Class(
1241                CK_OBJECT_CLASS::from_ne_bytes(val.try_into()?).try_into()?,
1242            )),
1243            AttributeType::KeyGenMechanism => Ok(Attribute::KeyGenMechanism(
1244                CK_MECHANISM_TYPE::from_ne_bytes(val.try_into()?).try_into()?,
1245            )),
1246            AttributeType::KeyType => Ok(Attribute::KeyType(
1247                CK_KEY_TYPE::from_ne_bytes(val.try_into()?).try_into()?,
1248            )),
1249            AttributeType::ValidationType => Ok(Attribute::ValidationType(
1250                CK_VALIDATION_TYPE::from_ne_bytes(val.try_into()?).try_into()?,
1251            )),
1252            AttributeType::ValidationAuthorityType => Ok(Attribute::ValidationAuthorityType(
1253                CK_VALIDATION_AUTHORITY_TYPE::from_ne_bytes(val.try_into()?).try_into()?,
1254            )),
1255            AttributeType::ValidationVersion => {
1256                Ok(Attribute::ValidationVersion(Version::new(val[0], val[1])))
1257            }
1258            AttributeType::AllowedMechanisms => {
1259                if attribute.ulValueLen == 0 {
1260                    /* For zero-length attributes we are getting pointer to static
1261                     * buffer of length zero, which can not be used to create slices.
1262                     * Short-circuit here to avoid crash (#324) */
1263                    Ok(Attribute::AllowedMechanisms(Vec::new()))
1264                } else {
1265                    let val = unsafe {
1266                        std::slice::from_raw_parts(
1267                            attribute.pValue as *const CK_MECHANISM_TYPE,
1268                            attribute.ulValueLen.try_into()?,
1269                        )
1270                    };
1271                    let types = val
1272                        .iter()
1273                        .copied()
1274                        .map(|t| t.try_into())
1275                        .collect::<Result<Vec<_>>>()?;
1276                    Ok(Attribute::AllowedMechanisms(types))
1277                }
1278            }
1279            AttributeType::EndDate => {
1280                if val.is_empty() {
1281                    Ok(Attribute::EndDate(Date::new_empty()))
1282                } else {
1283                    let date = val.as_ptr() as *const CK_DATE;
1284                    unsafe {
1285                        let year = String::from_utf8_lossy(Vec::from((*date).year).as_slice())
1286                            .trim_end()
1287                            .to_string();
1288                        let month = String::from_utf8_lossy(Vec::from((*date).month).as_slice())
1289                            .trim_end()
1290                            .to_string();
1291                        let day = String::from_utf8_lossy(Vec::from((*date).day).as_slice())
1292                            .trim_end()
1293                            .to_string();
1294                        Ok(Attribute::EndDate(Date::new_from_str_slice(
1295                            year.as_str(),
1296                            month.as_str(),
1297                            day.as_str(),
1298                        )?))
1299                    }
1300                }
1301            }
1302            AttributeType::StartDate => {
1303                if val.is_empty() {
1304                    Ok(Attribute::StartDate(Date::new_empty()))
1305                } else {
1306                    let date = val.as_ptr() as *const CK_DATE;
1307                    unsafe {
1308                        let year = String::from_utf8_lossy(Vec::from((*date).year).as_slice())
1309                            .trim_end()
1310                            .to_string();
1311                        let month = String::from_utf8_lossy(Vec::from((*date).month).as_slice())
1312                            .trim_end()
1313                            .to_string();
1314                        let day = String::from_utf8_lossy(Vec::from((*date).day).as_slice())
1315                            .trim_end()
1316                            .to_string();
1317                        Ok(Attribute::StartDate(Date::new_from_str_slice(
1318                            year.as_str(),
1319                            month.as_str(),
1320                            day.as_str(),
1321                        )?))
1322                    }
1323                }
1324            }
1325            AttributeType::VendorDefined(t) => Ok(Attribute::VendorDefined((
1326                AttributeType::VendorDefined(t),
1327                val.to_vec(),
1328            ))),
1329        }
1330    }
1331}
1332
1333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1334#[repr(transparent)]
1335/// Token specific identifier for an object
1336pub struct ObjectHandle {
1337    handle: CK_OBJECT_HANDLE,
1338}
1339
1340impl ObjectHandle {
1341    pub(crate) fn new(handle: CK_OBJECT_HANDLE) -> Self {
1342        ObjectHandle { handle }
1343    }
1344
1345    /// Create a new object handle from a raw handle.
1346    /// # Safety
1347    /// Considered unsafe due to ability for client to arbitrarily create object handles.
1348    pub unsafe fn new_from_raw(handle: CK_OBJECT_HANDLE) -> Self {
1349        ObjectHandle { handle }
1350    }
1351
1352    /// Get the raw handle of the object.
1353    pub fn handle(&self) -> CK_OBJECT_HANDLE {
1354        self.handle
1355    }
1356}
1357
1358impl std::fmt::Display for ObjectHandle {
1359    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1360        write!(f, "{}", self.handle)
1361    }
1362}
1363
1364impl std::fmt::LowerHex for ObjectHandle {
1365    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1366        write!(f, "{:08x}", self.handle)
1367    }
1368}
1369
1370impl std::fmt::UpperHex for ObjectHandle {
1371    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1372        write!(f, "{:08X}", self.handle)
1373    }
1374}
1375
1376#[derive(Copy, Debug, Clone, PartialEq, Eq)]
1377#[repr(transparent)]
1378/// Generic parameter set
1379pub struct ParameterSetType {
1380    val: Ulong,
1381}
1382
1383impl ParameterSetType {
1384    pub(crate) fn stringify(val: Ulong) -> String {
1385        format!("unknown ({:08x})", *val)
1386    }
1387}
1388
1389impl std::fmt::Display for ParameterSetType {
1390    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1391        write!(f, "{}", ParameterSetType::stringify(self.val))
1392    }
1393}
1394
1395impl Deref for ParameterSetType {
1396    type Target = Ulong;
1397
1398    fn deref(&self) -> &Self::Target {
1399        &self.val
1400    }
1401}
1402
1403impl From<ParameterSetType> for Ulong {
1404    fn from(val: ParameterSetType) -> Self {
1405        *val
1406    }
1407}
1408
1409impl TryFrom<Ulong> for ParameterSetType {
1410    type Error = Error;
1411
1412    fn try_from(val: Ulong) -> Result<Self> {
1413        Ok(ParameterSetType { val })
1414    }
1415}
1416
1417impl From<MlKemParameterSetType> for ParameterSetType {
1418    fn from(val: MlKemParameterSetType) -> Self {
1419        ParameterSetType {
1420            val: Ulong::new(*val.as_ref()),
1421        }
1422    }
1423}
1424
1425impl From<MlDsaParameterSetType> for ParameterSetType {
1426    fn from(val: MlDsaParameterSetType) -> Self {
1427        ParameterSetType {
1428            val: Ulong::new(*val.as_ref()),
1429        }
1430    }
1431}
1432
1433impl From<SlhDsaParameterSetType> for ParameterSetType {
1434    fn from(val: SlhDsaParameterSetType) -> Self {
1435        ParameterSetType {
1436            val: Ulong::new(*val.as_ref()),
1437        }
1438    }
1439}
1440
1441#[derive(Copy, Debug, Clone, PartialEq, Eq)]
1442#[repr(transparent)]
1443/// Identifier of the ML-KEM parameter set
1444pub struct MlKemParameterSetType {
1445    val: CK_ML_KEM_PARAMETER_SET_TYPE,
1446}
1447
1448impl MlKemParameterSetType {
1449    /// ML-KEM 512
1450    pub const ML_KEM_512: MlKemParameterSetType = MlKemParameterSetType {
1451        val: CKP_ML_KEM_512,
1452    };
1453    /// ML-KEM 768
1454    pub const ML_KEM_768: MlKemParameterSetType = MlKemParameterSetType {
1455        val: CKP_ML_KEM_768,
1456    };
1457    /// ML-KEM 1024
1458    pub const ML_KEM_1024: MlKemParameterSetType = MlKemParameterSetType {
1459        val: CKP_ML_KEM_1024,
1460    };
1461
1462    pub(crate) fn stringify(val: CK_ML_KEM_PARAMETER_SET_TYPE) -> String {
1463        match val {
1464            CKP_ML_KEM_512 => String::from(stringify!(CKP_ML_KEM_512)),
1465            CKP_ML_KEM_768 => String::from(stringify!(CKP_ML_KEM_768)),
1466            CKP_ML_KEM_1024 => String::from(stringify!(CKP_ML_KEM_1024)),
1467            _ => format!("unknown ({val:08x})"),
1468        }
1469    }
1470}
1471
1472impl std::fmt::Display for MlKemParameterSetType {
1473    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1474        write!(f, "{}", MlKemParameterSetType::stringify(self.val))
1475    }
1476}
1477
1478impl AsRef<CK_ML_KEM_PARAMETER_SET_TYPE> for MlKemParameterSetType {
1479    fn as_ref(&self) -> &CK_ML_KEM_PARAMETER_SET_TYPE {
1480        &self.val
1481    }
1482}
1483
1484impl From<MlKemParameterSetType> for CK_ML_KEM_PARAMETER_SET_TYPE {
1485    fn from(val: MlKemParameterSetType) -> Self {
1486        *val.as_ref()
1487    }
1488}
1489
1490impl TryFrom<CK_ML_KEM_PARAMETER_SET_TYPE> for MlKemParameterSetType {
1491    type Error = Error;
1492
1493    fn try_from(val: CK_ML_KEM_PARAMETER_SET_TYPE) -> Result<Self> {
1494        match val {
1495            CKP_ML_KEM_512 => Ok(MlKemParameterSetType::ML_KEM_512),
1496            CKP_ML_KEM_768 => Ok(MlKemParameterSetType::ML_KEM_768),
1497            CKP_ML_KEM_1024 => Ok(MlKemParameterSetType::ML_KEM_1024),
1498            _ => {
1499                error!("ML-KEM parameter set {val} is not supported.");
1500                Err(Error::NotSupported)
1501            }
1502        }
1503    }
1504}
1505
1506impl From<ParameterSetType> for MlKemParameterSetType {
1507    fn from(val: ParameterSetType) -> Self {
1508        MlKemParameterSetType {
1509            val: CK_ULONG::from(*val),
1510        }
1511    }
1512}
1513
1514#[derive(Copy, Debug, Clone, PartialEq, Eq)]
1515#[repr(transparent)]
1516/// Identifier of the ML-DSA parameter set
1517pub struct MlDsaParameterSetType {
1518    val: CK_ML_DSA_PARAMETER_SET_TYPE,
1519}
1520
1521impl MlDsaParameterSetType {
1522    /// ML-DSA 44
1523    pub const ML_DSA_44: MlDsaParameterSetType = MlDsaParameterSetType { val: CKP_ML_DSA_44 };
1524    /// ML-DSA 65
1525    pub const ML_DSA_65: MlDsaParameterSetType = MlDsaParameterSetType { val: CKP_ML_DSA_65 };
1526    /// ML-DSA 87
1527    pub const ML_DSA_87: MlDsaParameterSetType = MlDsaParameterSetType { val: CKP_ML_DSA_87 };
1528
1529    pub(crate) fn stringify(val: CK_ML_DSA_PARAMETER_SET_TYPE) -> String {
1530        match val {
1531            CKP_ML_DSA_44 => String::from(stringify!(CKP_ML_DSA_44)),
1532            CKP_ML_DSA_65 => String::from(stringify!(CKP_ML_DSA_65)),
1533            CKP_ML_DSA_87 => String::from(stringify!(CKP_ML_DSA_87)),
1534            _ => format!("unknown ({val:08x})"),
1535        }
1536    }
1537}
1538
1539impl std::fmt::Display for MlDsaParameterSetType {
1540    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1541        write!(f, "{}", MlDsaParameterSetType::stringify(self.val))
1542    }
1543}
1544
1545impl AsRef<CK_ML_DSA_PARAMETER_SET_TYPE> for MlDsaParameterSetType {
1546    fn as_ref(&self) -> &CK_ML_DSA_PARAMETER_SET_TYPE {
1547        &self.val
1548    }
1549}
1550
1551impl From<MlDsaParameterSetType> for CK_ML_DSA_PARAMETER_SET_TYPE {
1552    fn from(val: MlDsaParameterSetType) -> Self {
1553        *val.as_ref()
1554    }
1555}
1556
1557impl TryFrom<CK_ML_DSA_PARAMETER_SET_TYPE> for MlDsaParameterSetType {
1558    type Error = Error;
1559
1560    fn try_from(val: CK_ML_DSA_PARAMETER_SET_TYPE) -> Result<Self> {
1561        match val {
1562            CKP_ML_DSA_44 => Ok(MlDsaParameterSetType::ML_DSA_44),
1563            CKP_ML_DSA_65 => Ok(MlDsaParameterSetType::ML_DSA_65),
1564            CKP_ML_DSA_87 => Ok(MlDsaParameterSetType::ML_DSA_87),
1565            _ => {
1566                error!("ML-DSA parameter set {val} is not supported.");
1567                Err(Error::NotSupported)
1568            }
1569        }
1570    }
1571}
1572
1573impl From<ParameterSetType> for MlDsaParameterSetType {
1574    fn from(val: ParameterSetType) -> Self {
1575        MlDsaParameterSetType {
1576            val: CK_ULONG::from(*val),
1577        }
1578    }
1579}
1580
1581#[derive(Copy, Debug, Clone, PartialEq, Eq)]
1582#[repr(transparent)]
1583/// Identifier of the SLH-DSA parameter set
1584pub struct SlhDsaParameterSetType {
1585    val: CK_SLH_DSA_PARAMETER_SET_TYPE,
1586}
1587
1588impl SlhDsaParameterSetType {
1589    /// SLH-DSA-SHA2-128s
1590    pub const SHA2_128S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1591        val: CKP_SLH_DSA_SHA2_128S,
1592    };
1593    /// SLH-DSA-SHAKE-128s
1594    pub const SHAKE_128S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1595        val: CKP_SLH_DSA_SHAKE_128S,
1596    };
1597    /// SLH-DSA-SHA2-128f
1598    pub const SHA2_128F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1599        val: CKP_SLH_DSA_SHA2_128F,
1600    };
1601    /// SLH-DSA-SHAKE-128f
1602    pub const SHAKE_128F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1603        val: CKP_SLH_DSA_SHAKE_128F,
1604    };
1605    /// SLH-DSA-SHA2-192s
1606    pub const SHA2_192S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1607        val: CKP_SLH_DSA_SHA2_192S,
1608    };
1609    /// SLH-DSA-SHAKE-192s
1610    pub const SHAKE_192S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1611        val: CKP_SLH_DSA_SHAKE_192S,
1612    };
1613    /// SLH-DSA-SHA2-192f
1614    pub const SHA2_192F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1615        val: CKP_SLH_DSA_SHA2_192F,
1616    };
1617    /// SLH-DSA-SHAKE-192f
1618    pub const SHAKE_192F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1619        val: CKP_SLH_DSA_SHAKE_192F,
1620    };
1621    /// SLH-DSA-SHA2-256s
1622    pub const SHA2_256S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1623        val: CKP_SLH_DSA_SHA2_256S,
1624    };
1625    /// SLH-DSA-SHAKE-256s
1626    pub const SHAKE_256S: SlhDsaParameterSetType = SlhDsaParameterSetType {
1627        val: CKP_SLH_DSA_SHAKE_256S,
1628    };
1629    /// SLH-DSA-SHA2-256f
1630    pub const SHA2_256F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1631        val: CKP_SLH_DSA_SHA2_256F,
1632    };
1633    /// SLH-DSA-SHAKE-256f
1634    pub const SHAKE_256F: SlhDsaParameterSetType = SlhDsaParameterSetType {
1635        val: CKP_SLH_DSA_SHAKE_256F,
1636    };
1637}
1638
1639impl std::fmt::Display for SlhDsaParameterSetType {
1640    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1641        write!(
1642            f,
1643            "{}",
1644            match self.val {
1645                CKP_SLH_DSA_SHA2_128S => stringify!(CKP_SLH_DSA_SHA2_128S),
1646                CKP_SLH_DSA_SHAKE_128S => stringify!(CKP_SLH_DSA_SHAKE_128S),
1647                CKP_SLH_DSA_SHA2_128F => stringify!(CKP_SLH_DSA_SHA2_128F),
1648                CKP_SLH_DSA_SHAKE_128F => stringify!(CKP_SLH_DSA_SHAKE_128F),
1649                CKP_SLH_DSA_SHA2_192S => stringify!(CKP_SLH_DSA_SHA2_192S),
1650                CKP_SLH_DSA_SHAKE_192S => stringify!(CKP_SLH_DSA_SHAKE_192S),
1651                CKP_SLH_DSA_SHA2_192F => stringify!(CKP_SLH_DSA_SHA2_192F),
1652                CKP_SLH_DSA_SHAKE_192F => stringify!(CKP_SLH_DSA_SHAKE_192F),
1653                CKP_SLH_DSA_SHA2_256S => stringify!(CKP_SLH_DSA_SHA2_256S),
1654                CKP_SLH_DSA_SHAKE_256S => stringify!(CKP_SLH_DSA_SHAKE_256S),
1655                CKP_SLH_DSA_SHA2_256F => stringify!(CKP_SLH_DSA_SHA2_256F),
1656                CKP_SLH_DSA_SHAKE_256F => stringify!(CKP_SLH_DSA_SHAKE_256F),
1657                v => return write!(f, "unknown ({v:08x})"),
1658            }
1659        )
1660    }
1661}
1662
1663impl AsRef<CK_SLH_DSA_PARAMETER_SET_TYPE> for SlhDsaParameterSetType {
1664    fn as_ref(&self) -> &CK_SLH_DSA_PARAMETER_SET_TYPE {
1665        &self.val
1666    }
1667}
1668
1669impl From<SlhDsaParameterSetType> for CK_SLH_DSA_PARAMETER_SET_TYPE {
1670    fn from(val: SlhDsaParameterSetType) -> Self {
1671        *val.as_ref()
1672    }
1673}
1674
1675impl TryFrom<CK_ML_DSA_PARAMETER_SET_TYPE> for SlhDsaParameterSetType {
1676    type Error = Error;
1677
1678    fn try_from(val: CK_ML_DSA_PARAMETER_SET_TYPE) -> Result<Self> {
1679        match val {
1680            CKP_SLH_DSA_SHA2_128S => Ok(SlhDsaParameterSetType::SHA2_128S),
1681            CKP_SLH_DSA_SHAKE_128S => Ok(SlhDsaParameterSetType::SHAKE_128S),
1682            CKP_SLH_DSA_SHA2_128F => Ok(SlhDsaParameterSetType::SHA2_128F),
1683            CKP_SLH_DSA_SHAKE_128F => Ok(SlhDsaParameterSetType::SHAKE_128F),
1684            CKP_SLH_DSA_SHA2_192S => Ok(SlhDsaParameterSetType::SHA2_192S),
1685            CKP_SLH_DSA_SHAKE_192S => Ok(SlhDsaParameterSetType::SHAKE_192S),
1686            CKP_SLH_DSA_SHA2_192F => Ok(SlhDsaParameterSetType::SHA2_192F),
1687            CKP_SLH_DSA_SHAKE_192F => Ok(SlhDsaParameterSetType::SHAKE_192F),
1688            CKP_SLH_DSA_SHA2_256S => Ok(SlhDsaParameterSetType::SHA2_256S),
1689            CKP_SLH_DSA_SHAKE_256S => Ok(SlhDsaParameterSetType::SHAKE_256S),
1690            CKP_SLH_DSA_SHA2_256F => Ok(SlhDsaParameterSetType::SHA2_256F),
1691            CKP_SLH_DSA_SHAKE_256F => Ok(SlhDsaParameterSetType::SHAKE_256F),
1692            _ => {
1693                error!("SLH-DSA parameter set {} is not supported.", val);
1694                Err(Error::NotSupported)
1695            }
1696        }
1697    }
1698}
1699
1700impl From<ParameterSetType> for SlhDsaParameterSetType {
1701    fn from(val: ParameterSetType) -> Self {
1702        SlhDsaParameterSetType {
1703            val: CK_ULONG::from(*val),
1704        }
1705    }
1706}
1707
1708#[derive(Copy, Debug, Clone, PartialEq, Eq)]
1709#[repr(transparent)]
1710/// Identifier of the class of an object
1711pub struct ObjectClass {
1712    val: CK_OBJECT_CLASS,
1713}
1714
1715impl ObjectClass {
1716    /// Data objects
1717    pub const DATA: ObjectClass = ObjectClass { val: CKO_DATA };
1718    /// Certificate objects
1719    pub const CERTIFICATE: ObjectClass = ObjectClass {
1720        val: CKO_CERTIFICATE,
1721    };
1722    /// Public key object
1723    pub const PUBLIC_KEY: ObjectClass = ObjectClass {
1724        val: CKO_PUBLIC_KEY,
1725    };
1726    /// Private key object
1727    pub const PRIVATE_KEY: ObjectClass = ObjectClass {
1728        val: CKO_PRIVATE_KEY,
1729    };
1730    /// Secret key object
1731    pub const SECRET_KEY: ObjectClass = ObjectClass {
1732        val: CKO_SECRET_KEY,
1733    };
1734    /// A hardware feature object
1735    pub const HARDWARE_FEATURE: ObjectClass = ObjectClass {
1736        val: CKO_HW_FEATURE,
1737    };
1738    /// A domain parameters object
1739    pub const DOMAIN_PARAMETERS: ObjectClass = ObjectClass {
1740        val: CKO_DOMAIN_PARAMETERS,
1741    };
1742    /// A mechanism object
1743    pub const MECHANISM: ObjectClass = ObjectClass { val: CKO_MECHANISM };
1744    /// An OTP key object
1745    pub const OTP_KEY: ObjectClass = ObjectClass { val: CKO_OTP_KEY };
1746    /// Profile object
1747    pub const PROFILE: ObjectClass = ObjectClass { val: CKO_PROFILE };
1748    /// Validation object
1749    pub const VALIDATION: ObjectClass = ObjectClass {
1750        val: CKO_VALIDATION,
1751    };
1752
1753    pub(crate) fn stringify(class: CK_OBJECT_CLASS) -> String {
1754        match class {
1755            CKO_DATA => String::from(stringify!(CKO_DATA)),
1756            CKO_CERTIFICATE => String::from(stringify!(CKO_CERTIFICATE)),
1757            CKO_PUBLIC_KEY => String::from(stringify!(CKO_PUBLIC_KEY)),
1758            CKO_PRIVATE_KEY => String::from(stringify!(CKO_PRIVATE_KEY)),
1759            CKO_SECRET_KEY => String::from(stringify!(CKO_SECRET_KEY)),
1760            CKO_HW_FEATURE => String::from(stringify!(CKO_HW_FEATURE)),
1761            CKO_DOMAIN_PARAMETERS => String::from(stringify!(CKO_DOMAIN_PARAMETERS)),
1762            CKO_MECHANISM => String::from(stringify!(CKO_MECHANISM)),
1763            CKO_OTP_KEY => String::from(stringify!(CKO_OTP_KEY)),
1764            CKO_PROFILE => String::from(stringify!(CKO_PROFILE)),
1765            CKO_VALIDATION => String::from(stringify!(CKO_VALIDATION)),
1766            _ => format!("unknown ({class:08x})"),
1767        }
1768    }
1769}
1770
1771impl std::fmt::Display for ObjectClass {
1772    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1773        write!(f, "{}", ObjectClass::stringify(self.val))
1774    }
1775}
1776
1777impl Deref for ObjectClass {
1778    type Target = CK_OBJECT_CLASS;
1779
1780    fn deref(&self) -> &Self::Target {
1781        &self.val
1782    }
1783}
1784
1785impl From<ObjectClass> for CK_OBJECT_CLASS {
1786    fn from(object_class: ObjectClass) -> Self {
1787        *object_class
1788    }
1789}
1790
1791impl TryFrom<CK_OBJECT_CLASS> for ObjectClass {
1792    type Error = Error;
1793
1794    fn try_from(object_class: CK_OBJECT_CLASS) -> Result<Self> {
1795        match object_class {
1796            CKO_DATA => Ok(ObjectClass::DATA),
1797            CKO_CERTIFICATE => Ok(ObjectClass::CERTIFICATE),
1798            CKO_PUBLIC_KEY => Ok(ObjectClass::PUBLIC_KEY),
1799            CKO_PRIVATE_KEY => Ok(ObjectClass::PRIVATE_KEY),
1800            CKO_SECRET_KEY => Ok(ObjectClass::SECRET_KEY),
1801            CKO_HW_FEATURE => Ok(ObjectClass::HARDWARE_FEATURE),
1802            CKO_DOMAIN_PARAMETERS => Ok(ObjectClass::DOMAIN_PARAMETERS),
1803            CKO_MECHANISM => Ok(ObjectClass::MECHANISM),
1804            CKO_OTP_KEY => Ok(ObjectClass::OTP_KEY),
1805            CKO_PROFILE => Ok(ObjectClass::PROFILE),
1806            CKO_VALIDATION => Ok(ObjectClass::VALIDATION),
1807
1808            _ => {
1809                error!("Object class {object_class} is not supported.");
1810                Err(Error::NotSupported)
1811            }
1812        }
1813    }
1814}
1815
1816#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1817#[repr(transparent)]
1818/// Key type
1819pub struct KeyType {
1820    val: CK_KEY_TYPE,
1821}
1822
1823impl KeyType {
1824    /// RSA key
1825    pub const RSA: KeyType = KeyType { val: CKK_RSA };
1826    /// DSA key
1827    pub const DSA: KeyType = KeyType { val: CKK_DSA };
1828    /// DH key
1829    pub const DH: KeyType = KeyType { val: CKK_DH };
1830    /// EC key
1831    pub const EC: KeyType = KeyType { val: CKK_EC };
1832    /// X9_42_DH key
1833    pub const X9_42_DH: KeyType = KeyType { val: CKK_X9_42_DH };
1834    /// KEA key
1835    pub const KEA: KeyType = KeyType { val: CKK_KEA };
1836    /// Generic Secret (hmac) key
1837    pub const GENERIC_SECRET: KeyType = KeyType {
1838        val: CKK_GENERIC_SECRET,
1839    };
1840    /// RC2 key
1841    pub const RC2: KeyType = KeyType { val: CKK_RC2 };
1842    /// RC4 key
1843    pub const RC4: KeyType = KeyType { val: CKK_RC4 };
1844    /// DES key
1845    pub const DES: KeyType = KeyType { val: CKK_DES };
1846    /// DES2 key
1847    pub const DES2: KeyType = KeyType { val: CKK_DES2 };
1848    /// DES3 secret
1849    /// Note that DES3 is deprecated. See <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf> section 2, p. 6.
1850    pub const DES3: KeyType = KeyType { val: CKK_DES3 };
1851    /// CAST key
1852    pub const CAST: KeyType = KeyType { val: CKK_CAST };
1853    /// CAST3 key
1854    pub const CAST3: KeyType = KeyType { val: CKK_CAST3 };
1855    /// CAST128 key
1856    pub const CAST128: KeyType = KeyType { val: CKK_CAST128 };
1857    /// RC5 key
1858    pub const RC5: KeyType = KeyType { val: CKK_RC5 };
1859    /// IDEA key
1860    pub const IDEA: KeyType = KeyType { val: CKK_IDEA };
1861    /// SKIPJACK key
1862    pub const SKIPJACK: KeyType = KeyType { val: CKK_SKIPJACK };
1863    /// BATON key
1864    pub const BATON: KeyType = KeyType { val: CKK_BATON };
1865    /// JUNIPER key
1866    pub const JUNIPER: KeyType = KeyType { val: CKK_JUNIPER };
1867    /// CDMF key
1868    pub const CDMF: KeyType = KeyType { val: CKK_CDMF };
1869    /// AES key
1870    pub const AES: KeyType = KeyType { val: CKK_AES };
1871    /// BLOWFISH key
1872    pub const BLOWFISH: KeyType = KeyType { val: CKK_BLOWFISH };
1873    /// TWOFISH key
1874    pub const TWOFISH: KeyType = KeyType { val: CKK_TWOFISH };
1875    /// SECURID key
1876    pub const SECURID: KeyType = KeyType { val: CKK_SECURID };
1877    /// HOTP key
1878    pub const HOTP: KeyType = KeyType { val: CKK_HOTP };
1879    /// ACTI key
1880    pub const ACTI: KeyType = KeyType { val: CKK_ACTI };
1881    /// CAMELLIA key
1882    pub const CAMELLIA: KeyType = KeyType { val: CKK_CAMELLIA };
1883    /// ARIA key
1884    pub const ARIA: KeyType = KeyType { val: CKK_ARIA };
1885    /// MD5 HMAC key
1886    pub const MD5_HMAC: KeyType = KeyType { val: CKK_MD5_HMAC };
1887    /// SHA1 HMAC key
1888    pub const SHA_1_HMAC: KeyType = KeyType {
1889        val: CKK_SHA_1_HMAC,
1890    };
1891    /// RIPEMD128 HMAC key
1892    pub const RIPEMD128_HMAC: KeyType = KeyType {
1893        val: CKK_RIPEMD128_HMAC,
1894    };
1895
1896    /// RIPEMD160 HMAC key
1897    pub const RIPEMD160_HMAC: KeyType = KeyType {
1898        val: CKK_RIPEMD160_HMAC,
1899    };
1900
1901    /// SHA256 HMAC key
1902    pub const SHA256_HMAC: KeyType = KeyType {
1903        val: CKK_SHA256_HMAC,
1904    };
1905
1906    /// SHA384 HMAC key
1907    pub const SHA384_HMAC: KeyType = KeyType {
1908        val: CKK_SHA256_HMAC,
1909    };
1910
1911    /// SHA512 HMAC key
1912    pub const SHA512_HMAC: KeyType = KeyType {
1913        val: CKK_SHA256_HMAC,
1914    };
1915
1916    /// SHA224 HMAC key
1917    pub const SHA224_HMAC: KeyType = KeyType {
1918        val: CKK_SHA256_HMAC,
1919    };
1920
1921    /// SEED key
1922    pub const SEED: KeyType = KeyType { val: CKK_SEED };
1923
1924    /// GOSTR3410 key
1925    pub const GOSTR3410: KeyType = KeyType { val: CKK_GOSTR3410 };
1926
1927    /// GOSTR3411 key
1928    pub const GOSTR3411: KeyType = KeyType { val: CKK_GOSTR3411 };
1929
1930    /// GOST28147 key
1931    pub const GOST28147: KeyType = KeyType { val: CKK_GOST28147 };
1932
1933    /// EC edwards key
1934    pub const EC_EDWARDS: KeyType = KeyType {
1935        val: CKK_EC_EDWARDS,
1936    };
1937    /// EC montgomery key
1938    pub const EC_MONTGOMERY: KeyType = KeyType {
1939        val: CKK_EC_MONTGOMERY,
1940    };
1941
1942    /// HKDF key
1943    pub const HKDF: KeyType = KeyType { val: CKK_HKDF };
1944
1945    /// ML-KEM key
1946    pub const ML_KEM: KeyType = KeyType { val: CKK_ML_KEM };
1947
1948    /// ML-DSA key
1949    pub const ML_DSA: KeyType = KeyType { val: CKK_ML_DSA };
1950
1951    /// SLH-DSA key
1952    pub const SLH_DSA: KeyType = KeyType { val: CKK_SLH_DSA };
1953
1954    /// Create vendor defined key type
1955    ///
1956    /// # Arguments
1957    ///
1958    /// * `val` - The value of vendor defined key type
1959    ///
1960    /// # Errors
1961    ///
1962    /// If `val` is less then `CKK_VENDOR_DEFINED`, a `Error::InvalidValue` will be returned
1963    ///
1964    /// # Examples
1965    /// ```rust
1966    /// use cryptoki::object::KeyType;
1967    /// use cryptoki_sys::CKK_VENDOR_DEFINED;
1968    ///
1969    /// let some_key_type: KeyType =
1970    ///     KeyType::new_vendor_defined(CKK_VENDOR_DEFINED | 0x14).unwrap();
1971    /// ```
1972    pub fn new_vendor_defined(val: CK_KEY_TYPE) -> Result<KeyType> {
1973        if val < CKK_VENDOR_DEFINED {
1974            Err(Error::InvalidValue)
1975        } else {
1976            Ok(KeyType { val })
1977        }
1978    }
1979
1980    fn stringify(key_type: CK_KEY_TYPE) -> String {
1981        match key_type {
1982            CKK_RSA => String::from(stringify!(CKK_RSA)),
1983            CKK_DSA => String::from(stringify!(CKK_DSA)),
1984            CKK_DH => String::from(stringify!(CKK_DH)),
1985            CKK_EC => String::from(stringify!(CKK_EC)),
1986            CKK_X9_42_DH => String::from(stringify!(CKK_X9_42_DH)),
1987            CKK_KEA => String::from(stringify!(CKK_KEA)),
1988            CKK_GENERIC_SECRET => String::from(stringify!(CKK_GENERIC_SECRET)),
1989            CKK_RC2 => String::from(stringify!(CKK_RC2)),
1990            CKK_RC4 => String::from(stringify!(CKK_RC4)),
1991            CKK_DES => String::from(stringify!(CKK_DES)),
1992            CKK_DES2 => String::from(stringify!(CKK_DES2)),
1993            CKK_DES3 => String::from(stringify!(CKK_DES3)),
1994            CKK_CAST => String::from(stringify!(CKK_CAST)),
1995            CKK_CAST3 => String::from(stringify!(CKK_CAST3)),
1996            CKK_CAST128 => String::from(stringify!(CKK_CAST128)),
1997            CKK_RC5 => String::from(stringify!(CKK_RC5)),
1998            CKK_IDEA => String::from(stringify!(CKK_IDEA)),
1999            CKK_SKIPJACK => String::from(stringify!(CKK_SKIPJACK)),
2000            CKK_BATON => String::from(stringify!(CKK_BATON)),
2001            CKK_JUNIPER => String::from(stringify!(CKK_JUNIPER)),
2002            CKK_CDMF => String::from(stringify!(CKK_CDMF)),
2003            CKK_AES => String::from(stringify!(CKK_AES)),
2004            CKK_BLOWFISH => String::from(stringify!(CKK_BLOWFISH)),
2005            CKK_TWOFISH => String::from(stringify!(CKK_TWOFISH)),
2006            CKK_SECURID => String::from(stringify!(CKK_SECURID)),
2007            CKK_HOTP => String::from(stringify!(CKK_HOTP)),
2008            CKK_ACTI => String::from(stringify!(CKK_ACTI)),
2009            CKK_CAMELLIA => String::from(stringify!(CKK_CAMELLIA)),
2010            CKK_ARIA => String::from(stringify!(CKK_ARIA)),
2011            CKK_MD5_HMAC => String::from(stringify!(CKK_MD5_HMAC)),
2012            CKK_SHA_1_HMAC => String::from(stringify!(CKK_SHA_1_HMAC)),
2013            CKK_RIPEMD128_HMAC => String::from(stringify!(CKK_RIPEMD128_HMAC)),
2014            CKK_RIPEMD160_HMAC => String::from(stringify!(CKK_RIPEMD160_HMAC)),
2015            CKK_SHA256_HMAC => String::from(stringify!(CKK_SHA256_HMAC)),
2016            CKK_SHA384_HMAC => String::from(stringify!(CKK_SHA384_HMAC)),
2017            CKK_SHA512_HMAC => String::from(stringify!(CKK_SHA512_HMAC)),
2018            CKK_SHA224_HMAC => String::from(stringify!(CKK_SHA224_HMAC)),
2019            CKK_SEED => String::from(stringify!(CKK_SEED)),
2020            CKK_GOSTR3410 => String::from(stringify!(CKK_GOSTR3410)),
2021            CKK_GOSTR3411 => String::from(stringify!(CKK_GOSTR3411)),
2022            CKK_GOST28147 => String::from(stringify!(CKK_GOST28147)),
2023            CKK_EC_EDWARDS => String::from(stringify!(CKK_EC_EDWARDS)),
2024            CKK_EC_MONTGOMERY => String::from(stringify!(CKK_EC_MONTGOMERY)),
2025            CKK_HKDF => String::from(stringify!(CKK_HKDF)),
2026            CKK_ML_KEM => String::from(stringify!(CKK_ML_KEM)),
2027            CKK_ML_DSA => String::from(stringify!(CKK_ML_DSA)),
2028            CKK_SLH_DSA => String::from(stringify!(CKK_SLH_DSA)),
2029            CKK_VENDOR_DEFINED..=CK_ULONG::MAX => String::from(stringify!(key_type)),
2030            _ => format!("unknown ({key_type:08x})"),
2031        }
2032    }
2033}
2034
2035impl std::fmt::Display for KeyType {
2036    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2037        write!(f, "{}", KeyType::stringify(self.val))
2038    }
2039}
2040
2041impl Deref for KeyType {
2042    type Target = CK_KEY_TYPE;
2043
2044    fn deref(&self) -> &Self::Target {
2045        &self.val
2046    }
2047}
2048
2049impl From<KeyType> for CK_KEY_TYPE {
2050    fn from(key_type: KeyType) -> Self {
2051        *key_type
2052    }
2053}
2054
2055impl TryFrom<CK_KEY_TYPE> for KeyType {
2056    type Error = Error;
2057
2058    fn try_from(key_type: CK_KEY_TYPE) -> Result<Self> {
2059        match key_type {
2060            CKK_RSA => Ok(KeyType::RSA),
2061            CKK_DSA => Ok(KeyType::DSA),
2062            CKK_DH => Ok(KeyType::DH),
2063            CKK_EC => Ok(KeyType::EC),
2064            CKK_X9_42_DH => Ok(KeyType::X9_42_DH),
2065            CKK_KEA => Ok(KeyType::KEA),
2066            CKK_GENERIC_SECRET => Ok(KeyType::GENERIC_SECRET),
2067            CKK_RC2 => Ok(KeyType::RC2),
2068            CKK_RC4 => Ok(KeyType::RC4),
2069            CKK_DES => Ok(KeyType::DES),
2070            CKK_DES2 => Ok(KeyType::DES2),
2071            CKK_DES3 => Ok(KeyType::DES3),
2072            CKK_CAST => Ok(KeyType::CAST),
2073            CKK_CAST3 => Ok(KeyType::CAST3),
2074            CKK_CAST128 => Ok(KeyType::CAST128),
2075            CKK_RC5 => Ok(KeyType::RC5),
2076            CKK_IDEA => Ok(KeyType::IDEA),
2077            CKK_SKIPJACK => Ok(KeyType::SKIPJACK),
2078            CKK_BATON => Ok(KeyType::BATON),
2079            CKK_JUNIPER => Ok(KeyType::JUNIPER),
2080            CKK_CDMF => Ok(KeyType::CDMF),
2081            CKK_AES => Ok(KeyType::AES),
2082            CKK_BLOWFISH => Ok(KeyType::BLOWFISH),
2083            CKK_TWOFISH => Ok(KeyType::TWOFISH),
2084            CKK_SECURID => Ok(KeyType::SECURID),
2085            CKK_HOTP => Ok(KeyType::HOTP),
2086            CKK_ACTI => Ok(KeyType::ACTI),
2087            CKK_CAMELLIA => Ok(KeyType::CAMELLIA),
2088            CKK_ARIA => Ok(KeyType::ARIA),
2089            CKK_MD5_HMAC => Ok(KeyType::MD5_HMAC),
2090            CKK_SHA_1_HMAC => Ok(KeyType::SHA_1_HMAC),
2091            CKK_RIPEMD128_HMAC => Ok(KeyType::RIPEMD128_HMAC),
2092            CKK_RIPEMD160_HMAC => Ok(KeyType::RIPEMD160_HMAC),
2093            CKK_SHA256_HMAC => Ok(KeyType::SHA256_HMAC),
2094            CKK_SHA384_HMAC => Ok(KeyType::SHA384_HMAC),
2095            CKK_SHA512_HMAC => Ok(KeyType::SHA512_HMAC),
2096            CKK_SHA224_HMAC => Ok(KeyType::SHA224_HMAC),
2097            CKK_SEED => Ok(KeyType::SEED),
2098            CKK_GOSTR3410 => Ok(KeyType::GOSTR3410),
2099            CKK_GOSTR3411 => Ok(KeyType::GOSTR3411),
2100            CKK_GOST28147 => Ok(KeyType::GOST28147),
2101            CKK_EC_EDWARDS => Ok(KeyType::EC_EDWARDS),
2102            CKK_EC_MONTGOMERY => Ok(KeyType::EC_MONTGOMERY),
2103            CKK_HKDF => Ok(KeyType::HKDF),
2104            CKK_ML_KEM => Ok(KeyType::ML_KEM),
2105            CKK_ML_DSA => Ok(KeyType::ML_DSA),
2106            CKK_SLH_DSA => Ok(KeyType::SLH_DSA),
2107            CKK_VENDOR_DEFINED..=CK_ULONG::MAX => KeyType::new_vendor_defined(key_type),
2108            _ => {
2109                error!("Key type {key_type} is not supported.");
2110                Err(Error::NotSupported)
2111            }
2112        }
2113    }
2114}
2115
2116#[derive(Debug, Copy, Clone)]
2117/// Information about the attribute of an object
2118pub enum AttributeInfo {
2119    /// The requested attribute is not a valid attribute for the object
2120    TypeInvalid,
2121    /// The value of the attribute is sensitive and will not be returned
2122    Sensitive,
2123    /// The attribute is available to get from the object and has the specified size in bytes.
2124    Available(usize),
2125    /// The attribute is not available.
2126    Unavailable,
2127}
2128
2129#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2130#[repr(transparent)]
2131/// The certificate type
2132pub struct CertificateType {
2133    val: CK_CERTIFICATE_TYPE,
2134}
2135
2136impl CertificateType {
2137    /// An X.509 certificate
2138    pub const X_509: CertificateType = CertificateType { val: CKC_X_509 };
2139    /// An X.509 attribute certificate
2140    pub const X_509_ATTR: CertificateType = CertificateType {
2141        val: CKC_X_509_ATTR_CERT,
2142    };
2143    /// A WTLS certificate
2144    pub const WTLS: CertificateType = CertificateType { val: CKC_WTLS };
2145
2146    pub(crate) fn stringify(cert_type: CK_CERTIFICATE_TYPE) -> String {
2147        match cert_type {
2148            CKC_X_509 => String::from(stringify!(CKC_X_509)),
2149            CKC_X_509_ATTR_CERT => String::from(stringify!(CKC_X_509_ATTR_CERT)),
2150            CKC_WTLS => String::from(stringify!(CKC_WTLS)),
2151            _ => format!("unknown ({cert_type:08x})"),
2152        }
2153    }
2154}
2155
2156impl std::fmt::Display for CertificateType {
2157    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2158        write!(f, "{}", CertificateType::stringify(self.val))
2159    }
2160}
2161
2162impl Deref for CertificateType {
2163    type Target = CK_CERTIFICATE_TYPE;
2164
2165    fn deref(&self) -> &Self::Target {
2166        &self.val
2167    }
2168}
2169
2170impl From<CertificateType> for CK_CERTIFICATE_TYPE {
2171    fn from(certificate_type: CertificateType) -> Self {
2172        *certificate_type
2173    }
2174}
2175
2176impl TryFrom<CK_CERTIFICATE_TYPE> for CertificateType {
2177    type Error = Error;
2178
2179    fn try_from(certificate_type: CK_CERTIFICATE_TYPE) -> Result<Self> {
2180        match certificate_type {
2181            CKC_X_509 => Ok(CertificateType::X_509),
2182            CKC_X_509_ATTR_CERT => Ok(CertificateType::X_509_ATTR),
2183            CKC_WTLS => Ok(CertificateType::WTLS),
2184            _ => {
2185                error!("Certificate type {certificate_type} is not supported.");
2186                Err(Error::NotSupported)
2187            }
2188        }
2189    }
2190}
2191
2192#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2193#[repr(transparent)]
2194/// The PKCS#11 Profile ID
2195///
2196/// The profiles and their meaning is defined in the following document:
2197///
2198/// <https://docs.oasis-open.org/pkcs11/pkcs11-profiles/v3.1/os/pkcs11-profiles-v3.1-os.html>
2199pub struct ProfileIdType {
2200    val: CK_PROFILE_ID,
2201}
2202
2203impl ProfileIdType {
2204    /// Baseline Provider
2205    pub const BASELINE_PROFIDER: ProfileIdType = ProfileIdType {
2206        val: CKP_BASELINE_PROVIDER,
2207    };
2208    /// Extended Provider
2209    pub const EXTENDED_PROFIDER: ProfileIdType = ProfileIdType {
2210        val: CKP_EXTENDED_PROVIDER,
2211    };
2212    /// Authentication Token Provider or Consumer
2213    pub const AUTHENTICATION_TOKEN: ProfileIdType = ProfileIdType {
2214        val: CKP_AUTHENTICATION_TOKEN,
2215    };
2216    /// Public Certificates Token Provider or Consumer
2217    pub const PUBLIC_CERTIFICATES_TOKEN: ProfileIdType = ProfileIdType {
2218        val: CKP_PUBLIC_CERTIFICATES_TOKEN,
2219    };
2220    /// Complete Provider
2221    pub const COMPLETE_PROVIDER: ProfileIdType = ProfileIdType {
2222        val: CKP_COMPLETE_PROVIDER,
2223    };
2224    /// HKDF TLS Token
2225    pub const HKDF_TLS_TOKEN: ProfileIdType = ProfileIdType {
2226        val: CKP_HKDF_TLS_TOKEN,
2227    };
2228}
2229
2230impl std::fmt::Display for ProfileIdType {
2231    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2232        write!(
2233            f,
2234            "{}",
2235            match self.val {
2236                CKP_BASELINE_PROVIDER => stringify!(CKP_BASELINE_PROVIDER),
2237                CKP_EXTENDED_PROVIDER => stringify!(CKP_EXTENDED_PROVIDER),
2238                CKP_AUTHENTICATION_TOKEN => stringify!(CKP_AUTHENTICATION_TOKEN),
2239                CKP_PUBLIC_CERTIFICATES_TOKEN => {
2240                    stringify!(CKP_PUBLIC_CERTIFICATES_TOKEN)
2241                }
2242                CKP_COMPLETE_PROVIDER => stringify!(CKP_COMPLETE_PROVIDER),
2243                CKP_HKDF_TLS_TOKEN => stringify!(CKP_HKDF_TLS_TOKEN),
2244                profile_id => return write!(f, "unknown ({profile_id:08x})"),
2245            }
2246        )
2247    }
2248}
2249
2250impl AsRef<CK_PROFILE_ID> for ProfileIdType {
2251    fn as_ref(&self) -> &CK_PROFILE_ID {
2252        &self.val
2253    }
2254}
2255
2256impl From<ProfileIdType> for CK_PROFILE_ID {
2257    fn from(profile_id: ProfileIdType) -> Self {
2258        *profile_id.as_ref()
2259    }
2260}
2261
2262impl TryFrom<CK_PROFILE_ID> for ProfileIdType {
2263    type Error = Error;
2264
2265    fn try_from(profile_id: CK_PROFILE_ID) -> Result<Self> {
2266        match profile_id {
2267            CKP_BASELINE_PROVIDER => Ok(ProfileIdType::BASELINE_PROFIDER),
2268            CKP_EXTENDED_PROVIDER => Ok(ProfileIdType::EXTENDED_PROFIDER),
2269            CKP_AUTHENTICATION_TOKEN => Ok(ProfileIdType::AUTHENTICATION_TOKEN),
2270            CKP_PUBLIC_CERTIFICATES_TOKEN => Ok(ProfileIdType::PUBLIC_CERTIFICATES_TOKEN),
2271            CKP_COMPLETE_PROVIDER => Ok(ProfileIdType::COMPLETE_PROVIDER),
2272            CKP_HKDF_TLS_TOKEN => Ok(ProfileIdType::HKDF_TLS_TOKEN),
2273            _ => {
2274                error!("Profile Id {} is not supported.", profile_id);
2275                Err(Error::NotSupported)
2276            }
2277        }
2278    }
2279}
2280
2281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2282#[repr(transparent)]
2283/// The PKCS#11 3.2 Validation Type
2284///
2285/// identifies the type of validation
2286pub struct ValidationType {
2287    val: CK_VALIDATION_TYPE,
2288}
2289
2290impl ValidationType {
2291    /// Unspecified validation type
2292    pub const UNSPECIFIED: ValidationType = ValidationType {
2293        val: CKV_TYPE_UNSPECIFIED,
2294    };
2295    /// Software validation type
2296    pub const SOFTWARE: ValidationType = ValidationType {
2297        val: CKV_TYPE_SOFTWARE,
2298    };
2299    /// Hardware validation type
2300    pub const HARDWARE: ValidationType = ValidationType {
2301        val: CKV_TYPE_HARDWARE,
2302    };
2303    /// Firmware validation type
2304    pub const FIRMWARE: ValidationType = ValidationType {
2305        val: CKV_TYPE_FIRMWARE,
2306    };
2307    /// Hybrid validation type
2308    pub const HYBRID: ValidationType = ValidationType {
2309        val: CKV_TYPE_HYBRID,
2310    };
2311
2312    pub(crate) fn stringify(validation_type: CK_VALIDATION_TYPE) -> String {
2313        match validation_type {
2314            CKV_TYPE_UNSPECIFIED => String::from(stringify!(CKV_TYPE_UNSPECIFIED)),
2315            CKV_TYPE_SOFTWARE => String::from(stringify!(CKV_TYPE_SOFTWARE)),
2316            CKV_TYPE_HARDWARE => String::from(stringify!(CKV_TYPE_HARDWARE)),
2317            CKV_TYPE_FIRMWARE => String::from(stringify!(CKV_TYPE_FIRMWARE)),
2318            CKV_TYPE_HYBRID => String::from(stringify!(CKV_TYPE_HYBRID)),
2319            _ => format!("unknown ({validation_type:08x})"),
2320        }
2321    }
2322}
2323
2324impl std::fmt::Display for ValidationType {
2325    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2326        write!(f, "{}", ValidationType::stringify(self.val))
2327    }
2328}
2329
2330impl Deref for ValidationType {
2331    type Target = CK_VALIDATION_TYPE;
2332
2333    fn deref(&self) -> &Self::Target {
2334        &self.val
2335    }
2336}
2337
2338impl From<ValidationType> for CK_VALIDATION_TYPE {
2339    fn from(validation_type: ValidationType) -> Self {
2340        *validation_type
2341    }
2342}
2343
2344impl TryFrom<CK_VALIDATION_TYPE> for ValidationType {
2345    type Error = Error;
2346
2347    fn try_from(validation_type: CK_VALIDATION_TYPE) -> Result<Self> {
2348        match validation_type {
2349            CKV_TYPE_UNSPECIFIED => Ok(ValidationType::UNSPECIFIED),
2350            CKV_TYPE_SOFTWARE => Ok(ValidationType::SOFTWARE),
2351            CKV_TYPE_HARDWARE => Ok(ValidationType::HARDWARE),
2352            CKV_TYPE_FIRMWARE => Ok(ValidationType::FIRMWARE),
2353            CKV_TYPE_HYBRID => Ok(ValidationType::HYBRID),
2354            _ => {
2355                error!("Validation type {} is not supported.", validation_type);
2356                Err(Error::NotSupported)
2357            }
2358        }
2359    }
2360}
2361
2362#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2363#[repr(transparent)]
2364/// The PKCS#11 3.2 Validation Authority Type
2365///
2366/// identifies the type of validation authority
2367pub struct ValidationAuthorityType {
2368    val: CK_VALIDATION_AUTHORITY_TYPE,
2369}
2370
2371impl ValidationAuthorityType {
2372    /// Unspecified validation authority type
2373    pub const UNSPECIFIED: ValidationAuthorityType = ValidationAuthorityType {
2374        val: CKV_AUTHORITY_TYPE_UNSPECIFIED,
2375    };
2376    /// NIST CMVP validation authority type
2377    pub const NIST_CMVP: ValidationAuthorityType = ValidationAuthorityType {
2378        val: CKV_AUTHORITY_TYPE_NIST_CMVP,
2379    };
2380    /// Common Criteria validation authority type
2381    pub const COMMON_CRITERIA: ValidationAuthorityType = ValidationAuthorityType {
2382        val: CKV_AUTHORITY_TYPE_COMMON_CRITERIA,
2383    };
2384
2385    pub(crate) fn stringify(authority_type: CK_VALIDATION_AUTHORITY_TYPE) -> String {
2386        match authority_type {
2387            CKV_AUTHORITY_TYPE_UNSPECIFIED => {
2388                String::from(stringify!(CKV_AUTHORITY_TYPE_UNSPECIFIED))
2389            }
2390            CKV_AUTHORITY_TYPE_NIST_CMVP => String::from(stringify!(CKV_AUTHORITY_TYPE_NIST_CMVP)),
2391            CKV_AUTHORITY_TYPE_COMMON_CRITERIA => {
2392                String::from(stringify!(CKV_AUTHORITY_TYPE_COMMON_CRITERIA))
2393            }
2394            _ => format!("unknown ({authority_type:08x})"),
2395        }
2396    }
2397}
2398
2399impl std::fmt::Display for ValidationAuthorityType {
2400    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2401        write!(f, "{}", ValidationAuthorityType::stringify(self.val))
2402    }
2403}
2404
2405impl Deref for ValidationAuthorityType {
2406    type Target = CK_VALIDATION_AUTHORITY_TYPE;
2407
2408    fn deref(&self) -> &Self::Target {
2409        &self.val
2410    }
2411}
2412
2413impl From<ValidationAuthorityType> for CK_VALIDATION_AUTHORITY_TYPE {
2414    fn from(validation_type: ValidationAuthorityType) -> Self {
2415        *validation_type
2416    }
2417}
2418
2419impl TryFrom<CK_VALIDATION_AUTHORITY_TYPE> for ValidationAuthorityType {
2420    type Error = Error;
2421
2422    fn try_from(authority_type: CK_VALIDATION_AUTHORITY_TYPE) -> Result<Self> {
2423        match authority_type {
2424            CKV_AUTHORITY_TYPE_UNSPECIFIED => Ok(ValidationAuthorityType::UNSPECIFIED),
2425            CKV_AUTHORITY_TYPE_NIST_CMVP => Ok(ValidationAuthorityType::NIST_CMVP),
2426            CKV_AUTHORITY_TYPE_COMMON_CRITERIA => Ok(ValidationAuthorityType::COMMON_CRITERIA),
2427            _ => {
2428                error!(
2429                    "Validation Authority type {} is not supported.",
2430                    authority_type
2431                );
2432                Err(Error::NotSupported)
2433            }
2434        }
2435    }
2436}