Skip to main content

kmip_protocol/types/
common.rs

1//! Rust types common to both serialization of KMIP requests and deserialization KMIP responses.
2use std::convert::TryInto;
3use std::fmt;
4use std::str::FromStr;
5
6use enum_ordinalize::Ordinalize;
7
8use crate::ttlv::fast_scan::{FastScanError, FastScanner};
9use crate::ttlv::format::Formatter;
10use crate::ttlv::format::{FormatDone, FormatResult};
11use crate::ttlv::types::Tag;
12use crate::ttlv::{TagType, Type};
13use crate::types::request::{Name, RevocationReason};
14
15use super::impl_ttlv_serde;
16
17/// See KMIP 1.0 section 2.1.1 [Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581155).
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct AttributeName(pub String);
20
21impl std::cmp::PartialEq<str> for AttributeName {
22    fn eq(&self, other: &str) -> bool {
23        self.0 == other
24    }
25}
26
27impl_ttlv_serde!(text AttributeName as 0x42000A);
28
29/// See KMIP 1.0 section 2.1.1 [Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581155).
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct AttributeIndex(pub i32);
32
33impl std::cmp::PartialEq<i32> for AttributeIndex {
34    fn eq(&self, other: &i32) -> bool {
35        &self.0 == other
36    }
37}
38
39impl_ttlv_serde!(int AttributeIndex as 0x420009);
40
41/// See KMIP 1.0 section 2.1.1 [Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581155).
42#[derive(Clone, Debug, PartialEq, Eq)]
43#[non_exhaustive]
44pub enum AttributeValue {
45    /// See KMIP 1.0 section 3.1 Unique Identifier.
46    UniqueIdentifier(UniqueIdentifier),
47
48    /// See KMIP 1.0 section 3.2 Name.
49    Name(Name),
50
51    /// See KMIP 1.0 section 3.3 Object Type.
52    ObjectType(ObjectType),
53
54    /// See KMIP 1.0 section 3.4 Cryptographic Algorithm.
55    CryptographicAlgorithm(CryptographicAlgorithm),
56
57    /// See KMIP 1.0 section 3.5 Cryptographic Length.
58    CryptographicLength(CryptographicLength),
59
60    /// See KMIP 1.0 section 3.6 Cryptographic Parameters.
61    CryptographicParameters(CryptographicParameters),
62
63    /// See KMIP 1.0 section 3.7 Cryptographic Domain Parameters.
64    CryptographicDomainParameters(CryptographicDomainParameters),
65
66    /// See KMIP 1.0 section 3.8 Certificate Type.
67    CertificateType(CertificateType),
68
69    // See KMIP 1.0 section 3.9 Certificate Identifier.
70    // Not implemented
71
72    // See KMIP 1.0 section 3.10 Certificate Subject.
73    // Not implemented
74
75    // See KMIP 1.0 section 3.11 Certificate Issuer.
76    // Not implemented
77
78    // See KMIP 1.0 section 3.12 Digest.
79    // Not implemented
80
81    // See KMIP 1.0 section 3.13 Operation Policy Name.
82    // Not implemented
83    /// See KMIP 1.0 section 3.14 Cryptographic Usage Mask.
84    CryptographicUsageMask(CryptographicUsageMask),
85
86    // See KMIP 1.0 section 3.15 Lease Time.
87    // Not implemented
88
89    // See KMIP 1.0 section 3.16 Usage Limits.
90    // Not implemented
91    /// See KMIP 1.0 section 3.17 State.
92    State(State),
93
94    /// See KMIP 1.0 section 3.18 Initial Date.
95    InitialDate(i64),
96
97    /// See KMIP 1.0 section 3.19 Activation Date.
98    ActivationDate(i64),
99
100    // See KMIP 1.0 section 3.20 Process Start Date.
101    // Not implemented
102    /// See KMIP 1.0 section 3.21 Protect Stop Date.
103    // Not implemented
104
105    /// See KMIP 1.0 section 3.22 Deactivation Date.
106    DeactivationDate(i64),
107
108    /// See KMIP 1.0 section 3.23 Destroy Date.
109    DestroyDate(i64),
110
111    // See KMIP 1.0 section 3.24 Compromise Occurence Date.
112    // Not implemented
113
114    // See KMIP 1.0 section 3.25 Compromise Date.
115    // Not implemented
116    /// See KMIP 1.0 section 3.26 Revocation Reason.
117    RevocationReason(RevocationReason),
118
119    // See KMIP 1.0 section 3.27 Archive Date.
120    // Not implemented
121    /// See KMIP 1.0 section 3.28 Object Group.
122    ObjectGroup(String),
123
124    /// See KMIP 1.0 section 3.29 Link.
125    Link(LinkType, LinkedObjectIdentifier),
126
127    /// See KMIP 1.0 section 3.30 Application Specific Information.
128    ApplicationSpecificInformation(ApplicationNamespace, ApplicationData),
129
130    /// See KMIP 1.0 section 3.31 Contact Information.
131    ContactInformation(String),
132    // See KMIP 1.0 section 3.32 Last Change Date.
133    // Not implemented
134    /// See KMIP 1.0 section 3.33 Custom Attribute.
135    CustomAttribute,
136}
137
138impl AttributeValue {
139    pub const TAG: Tag = Tag::new(0x42000B);
140
141    pub fn fast_scan(scanner: &mut FastScanner<'_>, name: &AttributeName) -> Result<Self, FastScanError> {
142        match name.0.as_str() {
143            "Unique Identifier" => UniqueIdentifier::fast_scan_with(scanner, Self::TAG).map(Self::UniqueIdentifier),
144
145            "Name" => Name::fast_scan_with(scanner, Self::TAG).map(Self::Name),
146
147            "Object Type" => ObjectType::fast_scan_with(scanner, Self::TAG).map(Self::ObjectType),
148
149            "Cryptographic Algorithm" => {
150                CryptographicAlgorithm::fast_scan_with(scanner, Self::TAG).map(Self::CryptographicAlgorithm)
151            }
152
153            "Cryptographic Length" => {
154                CryptographicLength::fast_scan_with(scanner, Self::TAG).map(Self::CryptographicLength)
155            }
156
157            "Cryptographic Parameters" => {
158                CryptographicParameters::fast_scan_with(scanner, Self::TAG).map(Self::CryptographicParameters)
159            }
160
161            "Cryptographic Domain Parameters" => CryptographicDomainParameters::fast_scan_with(scanner, Self::TAG)
162                .map(Self::CryptographicDomainParameters),
163
164            "Cryptographic Usage Mask" => {
165                CryptographicUsageMask::fast_scan_with(scanner, Self::TAG).map(Self::CryptographicUsageMask)
166            }
167
168            "State" => State::fast_scan_with(scanner, Self::TAG).map(Self::State),
169
170            "Initial Date" => scanner.scan_date_time(Self::TAG).map(Self::InitialDate),
171
172            "Activation Date" => scanner.scan_date_time(Self::TAG).map(Self::ActivationDate),
173
174            "Deactivation Date" => scanner.scan_date_time(Self::TAG).map(Self::DeactivationDate),
175
176            "Destroy Date" => scanner.scan_date_time(Self::TAG).map(Self::DestroyDate),
177
178            "Revocation Reason" => RevocationReason::fast_scan_with(scanner, Self::TAG).map(Self::RevocationReason),
179
180            "Object Group" => scanner.scan_text(Self::TAG).map(|s| Self::ObjectGroup(s.into())),
181
182            "Link" => {
183                let mut scanner = scanner.scan_struct(Self::TAG)?;
184                let link_type = LinkType::fast_scan(&mut scanner)?;
185                let linked_object_identifier = LinkedObjectIdentifier::fast_scan(&mut scanner)?;
186                scanner.finish()?;
187                Ok(Self::Link(link_type, linked_object_identifier))
188            }
189
190            "Application Specific Information" => {
191                let mut scanner = scanner.scan_struct(Self::TAG)?;
192                let application_namespace = ApplicationNamespace::fast_scan(&mut scanner)?;
193                let application_data = ApplicationData::fast_scan(&mut scanner)?;
194                scanner.finish()?;
195                Ok(Self::ApplicationSpecificInformation(
196                    application_namespace,
197                    application_data,
198                ))
199            }
200
201            "Contact Information" => scanner.scan_text(Self::TAG).map(|s| Self::ContactInformation(s.into())),
202
203            custom_attr if custom_attr.starts_with("x-") || custom_attr.starts_with("y-") => {
204                let first_ttl = scanner.remaining()[0];
205                let tt = TagType::parse(first_ttl[0..4].try_into().unwrap());
206                match tt.r#type() {
207                    Type::Structure => scanner.skip_struct(tt.tag())?,
208                    Type::Integer => scanner.skip_int(tt.tag())?,
209                    Type::LongInteger => scanner.skip_long_int(tt.tag())?,
210                    Type::BigInteger => scanner.skip_big_int(tt.tag())?,
211                    Type::Enumeration => scanner.skip_enum(tt.tag())?,
212                    Type::Boolean => scanner.skip_bool(tt.tag())?,
213                    Type::TextString => scanner.skip_text(tt.tag())?,
214                    Type::ByteString => scanner.skip_bytes(tt.tag())?,
215                    Type::DateTime => scanner.skip_date_time(tt.tag())?,
216                    Type::Interval => scanner.skip_interval(tt.tag())?,
217                }
218                Ok(Self::CustomAttribute)
219            }
220
221            _ => Err(FastScanError::assert()),
222        }
223    }
224
225    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
226        match self {
227            AttributeValue::UniqueIdentifier(v) => v.format_with(formatter, Self::TAG),
228            AttributeValue::Name(v) => v.format_with(formatter, Self::TAG),
229            AttributeValue::ObjectType(v) => v.format_with(formatter, Self::TAG),
230            AttributeValue::CryptographicAlgorithm(v) => v.format_with(formatter, Self::TAG),
231            AttributeValue::CryptographicLength(v) => v.format_with(formatter, Self::TAG),
232            AttributeValue::CryptographicParameters(v) => v.format_with(formatter, Self::TAG),
233            AttributeValue::CryptographicDomainParameters(v) => v.format_with(formatter, Self::TAG),
234            AttributeValue::CertificateType(v) => v.format_with(formatter, Self::TAG),
235            AttributeValue::CryptographicUsageMask(v) => v.format_with(formatter, Self::TAG),
236            AttributeValue::State(v) => v.format_with(formatter, Self::TAG),
237            AttributeValue::InitialDate(v) => formatter.format_date_time(Self::TAG, *v),
238            AttributeValue::ActivationDate(v) => formatter.format_date_time(Self::TAG, *v),
239            AttributeValue::DeactivationDate(v) => formatter.format_date_time(Self::TAG, *v),
240            AttributeValue::DestroyDate(v) => formatter.format_date_time(Self::TAG, *v),
241            AttributeValue::RevocationReason(v) => v.format_with(formatter, Self::TAG),
242            AttributeValue::ObjectGroup(v) => formatter.format_text(Self::TAG, v),
243            AttributeValue::Link(link_type, linked_object_id) => {
244                let mut formatter = formatter.format_struct(Self::TAG)?;
245                link_type.format(&mut formatter)?;
246                linked_object_id.format(&mut formatter)?;
247                Ok(formatter.finish())
248            }
249            AttributeValue::ApplicationSpecificInformation(namespace, data) => {
250                let mut formatter = formatter.format_struct(Self::TAG)?;
251                namespace.format(&mut formatter)?;
252                data.format(&mut formatter)?;
253                Ok(formatter.finish())
254            }
255            AttributeValue::ContactInformation(v) => formatter.format_text(Self::TAG, v),
256            AttributeValue::CustomAttribute => Ok(FormatDone::assert()),
257        }
258    }
259}
260
261/// See KMIP 1.0 section 2.1.4 [Key Value](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581158).
262#[derive(Clone, Debug, PartialEq, Eq)]
263pub enum KeyMaterial {
264    Bytes(Vec<u8>),
265    TransparentSymmetricKey(TransparentSymmetricKey),
266    TransparentDSAPrivateKey(TransparentDSAPrivateKey),
267    TransparentDSAPublicKey(TransparentDSAPublicKey),
268    TransparentRSAPrivateKey(TransparentRSAPrivateKey),
269    TransparentRSAPublicKey(TransparentRSAPublicKey),
270    TransparentDHPrivateKey(TransparentDHPrivateKey),
271    TransparentDHPublicKey(TransparentDHPublicKey),
272    Structure(Vec<u8>), // All other transparent key types which we don't support yet
273}
274
275impl fmt::Display for KeyMaterial {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        match self {
278            KeyMaterial::Bytes(_) => write!(f, "Bytes"),
279            KeyMaterial::TransparentSymmetricKey(_) => write!(f, "TransparentSymmetricKey"),
280            KeyMaterial::TransparentDSAPrivateKey(_) => write!(f, "TransparentDSAPrivateKey"),
281            KeyMaterial::TransparentDSAPublicKey(_) => write!(f, "TransparentDSAPublicKey"),
282            KeyMaterial::TransparentRSAPrivateKey(_) => write!(f, "TransparentRSAPrivateKey"),
283            KeyMaterial::TransparentRSAPublicKey(_) => write!(f, "TransparentRSAPublicKey"),
284            KeyMaterial::TransparentDHPrivateKey(_) => write!(f, "TransparentDHPrivateKey"),
285            KeyMaterial::TransparentDHPublicKey(_) => write!(f, "TransparentDHPublicKey"),
286            KeyMaterial::Structure(_) => write!(f, "Structure"),
287        }
288    }
289}
290
291impl KeyMaterial {
292    pub const TAG: Tag = Tag::new(0x420043);
293
294    pub fn fast_scan(scanner: &mut FastScanner<'_>, format: &KeyFormatType) -> Result<Self, FastScanError> {
295        match format {
296            KeyFormatType::Raw
297            | KeyFormatType::Opaque
298            | KeyFormatType::PKCS1
299            | KeyFormatType::PKCS8
300            | KeyFormatType::X509
301            | KeyFormatType::ECPrivateKey => scanner.scan_bytes(Self::TAG).map(|s| Self::Bytes(s.into())),
302
303            KeyFormatType::TransparentSymmetricKey => {
304                TransparentSymmetricKey::fast_scan(scanner).map(Self::TransparentSymmetricKey)
305            }
306            KeyFormatType::TransparentDSAPrivateKey => {
307                TransparentDSAPrivateKey::fast_scan(scanner).map(Self::TransparentDSAPrivateKey)
308            }
309            KeyFormatType::TransparentDSAPublicKey => {
310                TransparentDSAPublicKey::fast_scan(scanner).map(Self::TransparentDSAPublicKey)
311            }
312            KeyFormatType::TransparentRSAPrivateKey => {
313                TransparentRSAPrivateKey::fast_scan(scanner).map(Self::TransparentRSAPrivateKey)
314            }
315            KeyFormatType::TransparentRSAPublicKey => {
316                TransparentRSAPublicKey::fast_scan(scanner).map(Self::TransparentRSAPublicKey)
317            }
318            KeyFormatType::TransparentDHPrivateKey => {
319                TransparentDHPrivateKey::fast_scan(scanner).map(Self::TransparentDHPrivateKey)
320            }
321            KeyFormatType::TransparentDHPublicKey => {
322                TransparentDHPublicKey::fast_scan(scanner).map(Self::TransparentDHPublicKey)
323            }
324            // TODO: Handle this more elegantly.
325            _ => {
326                scanner.skip_struct(Self::TAG)?;
327                Ok(Self::Structure(Vec::new()))
328            }
329        }
330    }
331
332    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
333        match self {
334            KeyMaterial::Bytes(v) => formatter.format_bytes(Self::TAG, v),
335
336            KeyMaterial::TransparentSymmetricKey(this) => this.format(formatter),
337            KeyMaterial::TransparentDSAPrivateKey(this) => this.format(formatter),
338            KeyMaterial::TransparentDSAPublicKey(this) => this.format(formatter),
339            KeyMaterial::TransparentRSAPrivateKey(this) => this.format(formatter),
340            KeyMaterial::TransparentRSAPublicKey(this) => this.format(formatter),
341            KeyMaterial::TransparentDHPrivateKey(this) => this.format(formatter),
342            KeyMaterial::TransparentDHPublicKey(this) => this.format(formatter),
343
344            KeyMaterial::Structure(_) => unimplemented!(),
345        }
346    }
347}
348
349/// See KMIP 1.0 section 2.1.7.1 [Transparent Symmetric Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
350#[derive(Clone, Debug, PartialEq, Eq)]
351pub struct TransparentSymmetricKey {
352    pub key: Vec<u8>,
353}
354
355impl TransparentSymmetricKey {
356    pub const TAG: Tag = Tag::new(0x420043);
357    pub const KEY_TAG: Tag = Tag::new(0x42003F);
358
359    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
360        let mut scanner = scanner.scan_struct(Self::TAG)?;
361        let key = scanner.scan_bytes(Self::KEY_TAG)?.into();
362        scanner.finish()?;
363        Ok(Self { key })
364    }
365
366    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
367        let mut formatter = formatter.format_struct(Self::TAG)?;
368        formatter.format_bytes(Self::KEY_TAG, &self.key)?;
369        Ok(formatter.finish())
370    }
371}
372
373/// See KMIP 1.0 section 2.1.7.2 [Transparent DSA Private Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub struct TransparentDSAPrivateKey {
376    pub p: Vec<u8>,
377    pub q: Vec<u8>,
378    pub g: Vec<u8>,
379    pub x: Vec<u8>,
380}
381
382impl TransparentDSAPrivateKey {
383    pub const TAG: Tag = Tag::new(0x420043);
384    pub const P_TAG: Tag = Tag::new(0x42005E);
385    pub const Q_TAG: Tag = Tag::new(0x420071);
386    pub const G_TAG: Tag = Tag::new(0x420037);
387    pub const X_TAG: Tag = Tag::new(0x42009F);
388
389    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
390        let mut scanner = scanner.scan_struct(Self::TAG)?;
391        let p = scanner.scan_big_int(Self::P_TAG)?.into();
392        let q = scanner.scan_big_int(Self::Q_TAG)?.into();
393        let g = scanner.scan_big_int(Self::G_TAG)?.into();
394        let x = scanner.scan_big_int(Self::X_TAG)?.into();
395        scanner.finish()?;
396        Ok(Self { p, q, g, x })
397    }
398
399    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
400        let mut formatter = formatter.format_struct(Self::TAG)?;
401        formatter.format_big_int(Self::P_TAG, &self.p)?;
402        formatter.format_big_int(Self::Q_TAG, &self.q)?;
403        formatter.format_big_int(Self::G_TAG, &self.g)?;
404        formatter.format_big_int(Self::X_TAG, &self.x)?;
405        Ok(formatter.finish())
406    }
407}
408
409/// See KMIP 1.0 section 2.1.7.3 [Transparent DSA Public Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
410#[derive(Clone, Debug, PartialEq, Eq)]
411pub struct TransparentDSAPublicKey {
412    pub p: Vec<u8>,
413    pub q: Vec<u8>,
414    pub g: Vec<u8>,
415    pub x: Vec<u8>,
416}
417
418impl TransparentDSAPublicKey {
419    pub const TAG: Tag = Tag::new(0x420043);
420    pub const P_TAG: Tag = Tag::new(0x42005E);
421    pub const Q_TAG: Tag = Tag::new(0x420071);
422    pub const G_TAG: Tag = Tag::new(0x420037);
423    pub const X_TAG: Tag = Tag::new(0x42009F);
424
425    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
426        let mut scanner = scanner.scan_struct(Self::TAG)?;
427        let p = scanner.scan_big_int(Self::P_TAG)?.into();
428        let q = scanner.scan_big_int(Self::Q_TAG)?.into();
429        let g = scanner.scan_big_int(Self::G_TAG)?.into();
430        let x = scanner.scan_big_int(Self::X_TAG)?.into();
431        scanner.finish()?;
432        Ok(Self { p, q, g, x })
433    }
434
435    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
436        let mut formatter = formatter.format_struct(Self::TAG)?;
437        formatter.format_big_int(Self::P_TAG, &self.p)?;
438        formatter.format_big_int(Self::Q_TAG, &self.q)?;
439        formatter.format_big_int(Self::G_TAG, &self.g)?;
440        formatter.format_big_int(Self::X_TAG, &self.x)?;
441        Ok(formatter.finish())
442    }
443}
444
445/// See KMIP 1.0 section 2.1.7.4 [Transparent RSA Private Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
446#[derive(Clone, Debug, PartialEq, Eq)]
447pub struct TransparentRSAPrivateKey {
448    pub modulus: Vec<u8>,
449    pub private_exponent: Option<Vec<u8>>,
450    pub public_exponent: Option<Vec<u8>>,
451    pub p: Option<Vec<u8>>,
452    pub q: Option<Vec<u8>>,
453    pub prime_exponent_p: Option<Vec<u8>>,
454    pub prime_exponent_q: Option<Vec<u8>>,
455    pub crt_coefficient: Option<Vec<u8>>,
456}
457
458impl TransparentRSAPrivateKey {
459    pub const TAG: Tag = Tag::new(0x420043);
460    pub const MODULUS_TAG: Tag = Tag::new(0x420052);
461    pub const PRIVATE_EXPONENT_TAG: Tag = Tag::new(0x420063);
462    pub const PUBLIC_EXPONENT_TAG: Tag = Tag::new(0x42006C);
463    pub const P_TAG: Tag = Tag::new(0x42005E);
464    pub const Q_TAG: Tag = Tag::new(0x420071);
465    pub const PRIME_EXPONENT_P_TAG: Tag = Tag::new(0x420060);
466    pub const PRIME_EXPONENT_Q_TAG: Tag = Tag::new(0x420061);
467    pub const CRT_COEFFICIENT_TAG: Tag = Tag::new(0x420027);
468
469    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
470        let mut scanner = scanner.scan_struct(Self::TAG)?;
471        let modulus = scanner.scan_big_int(Self::MODULUS_TAG)?.into();
472        let private_exponent = scanner.scan_opt_big_int(Self::PRIVATE_EXPONENT_TAG)?.map(Into::into);
473        let public_exponent = scanner.scan_opt_big_int(Self::PUBLIC_EXPONENT_TAG)?.map(Into::into);
474        let p = scanner.scan_opt_big_int(Self::P_TAG)?.map(Into::into);
475        let q = scanner.scan_opt_big_int(Self::Q_TAG)?.map(Into::into);
476        let prime_exponent_p = scanner.scan_opt_big_int(Self::PRIME_EXPONENT_P_TAG)?.map(Into::into);
477        let prime_exponent_q = scanner.scan_opt_big_int(Self::PRIME_EXPONENT_Q_TAG)?.map(Into::into);
478        let crt_coefficient = scanner.scan_opt_big_int(Self::CRT_COEFFICIENT_TAG)?.map(Into::into);
479        scanner.finish()?;
480        Ok(Self {
481            modulus,
482            private_exponent,
483            public_exponent,
484            p,
485            q,
486            prime_exponent_p,
487            prime_exponent_q,
488            crt_coefficient,
489        })
490    }
491
492    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
493        let mut formatter = formatter.format_struct(Self::TAG)?;
494        formatter.format_big_int(Self::MODULUS_TAG, &self.modulus)?;
495        if let Some(private_exponent) = &self.private_exponent {
496            formatter.format_big_int(Self::PRIVATE_EXPONENT_TAG, private_exponent)?;
497        }
498        if let Some(public_exponent) = &self.public_exponent {
499            formatter.format_big_int(Self::PUBLIC_EXPONENT_TAG, public_exponent)?;
500        }
501        if let Some(p) = &self.p {
502            formatter.format_big_int(Self::P_TAG, p)?;
503        }
504        if let Some(q) = &self.q {
505            formatter.format_big_int(Self::Q_TAG, q)?;
506        }
507        if let Some(prime_exponent_p) = &self.prime_exponent_p {
508            formatter.format_big_int(Self::PRIME_EXPONENT_P_TAG, prime_exponent_p)?;
509        }
510        if let Some(prime_exponent_q) = &self.prime_exponent_q {
511            formatter.format_big_int(Self::PRIME_EXPONENT_Q_TAG, prime_exponent_q)?;
512        }
513        if let Some(crt_coefficient) = &self.crt_coefficient {
514            formatter.format_big_int(Self::CRT_COEFFICIENT_TAG, crt_coefficient)?;
515        }
516        Ok(formatter.finish())
517    }
518}
519
520/// See KMIP 1.0 section 2.1.7.5 [Transparent RSA Public Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
521#[derive(Clone, Debug, PartialEq, Eq)]
522pub struct TransparentRSAPublicKey {
523    pub modulus: Vec<u8>,
524    pub public_exponent: Vec<u8>,
525}
526
527impl TransparentRSAPublicKey {
528    pub const TAG: Tag = Tag::new(0x420043);
529    pub const MODULUS_TAG: Tag = Tag::new(0x420052);
530    pub const PUBLIC_EXPONENT_TAG: Tag = Tag::new(0x42006C);
531
532    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
533        let mut scanner = scanner.scan_struct(Self::TAG)?;
534        let modulus = scanner.scan_big_int(Self::MODULUS_TAG)?.into();
535        let public_exponent = scanner.scan_big_int(Self::PUBLIC_EXPONENT_TAG)?.into();
536        scanner.finish()?;
537        Ok(Self {
538            modulus,
539            public_exponent,
540        })
541    }
542
543    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
544        let mut formatter = formatter.format_struct(Self::TAG)?;
545        formatter.format_big_int(Self::MODULUS_TAG, &self.modulus)?;
546        formatter.format_big_int(Self::PUBLIC_EXPONENT_TAG, &self.public_exponent)?;
547        Ok(formatter.finish())
548    }
549}
550
551/// See KMIP 1.0 section 2.1.7.6 [Transparent DH Private Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
552#[derive(Clone, Debug, PartialEq, Eq)]
553pub struct TransparentDHPrivateKey {
554    pub p: Vec<u8>,
555    pub q: Option<Vec<u8>>,
556    pub g: Vec<u8>,
557    pub j: Option<Vec<u8>>,
558    pub x: Vec<u8>,
559}
560
561impl TransparentDHPrivateKey {
562    pub const TAG: Tag = Tag::new(0x420043);
563    pub const P_TAG: Tag = Tag::new(0x42005E);
564    pub const Q_TAG: Tag = Tag::new(0x420071);
565    pub const G_TAG: Tag = Tag::new(0x420037);
566    pub const J_TAG: Tag = Tag::new(0x42003E);
567    pub const X_TAG: Tag = Tag::new(0x42009F);
568
569    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
570        let mut scanner = scanner.scan_struct(Self::TAG)?;
571        let p = scanner.scan_big_int(Self::P_TAG)?.into();
572        let q = scanner.scan_opt_big_int(Self::Q_TAG)?.map(Into::into);
573        let g = scanner.scan_big_int(Self::G_TAG)?.into();
574        let j = scanner.scan_opt_big_int(Self::J_TAG)?.map(Into::into);
575        let x = scanner.scan_big_int(Self::X_TAG)?.into();
576        scanner.finish()?;
577        Ok(Self { p, q, g, j, x })
578    }
579
580    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
581        let mut formatter = formatter.format_struct(Self::TAG)?;
582        formatter.format_big_int(Self::P_TAG, &self.p)?;
583        if let Some(q) = &self.q {
584            formatter.format_big_int(Self::Q_TAG, q)?;
585        }
586        formatter.format_big_int(Self::G_TAG, &self.g)?;
587        if let Some(j) = &self.j {
588            formatter.format_big_int(Self::J_TAG, j)?;
589        }
590        formatter.format_big_int(Self::X_TAG, &self.x)?;
591        Ok(formatter.finish())
592    }
593}
594
595/// See KMIP 1.0 section 2.1.7.7 [Transparent DH Public Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581161).
596#[derive(Clone, Debug, PartialEq, Eq)]
597pub struct TransparentDHPublicKey {
598    pub p: Vec<u8>,
599    pub q: Option<Vec<u8>>,
600    pub g: Vec<u8>,
601    pub j: Option<Vec<u8>>,
602    pub y: Vec<u8>,
603}
604
605impl TransparentDHPublicKey {
606    pub const TAG: Tag = Tag::new(0x420043);
607    pub const P_TAG: Tag = Tag::new(0x42005E);
608    pub const Q_TAG: Tag = Tag::new(0x420071);
609    pub const G_TAG: Tag = Tag::new(0x420037);
610    pub const J_TAG: Tag = Tag::new(0x42003E);
611    pub const Y_TAG: Tag = Tag::new(0x4200A0);
612
613    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
614        let mut scanner = scanner.scan_struct(Self::TAG)?;
615        let p = scanner.scan_big_int(Self::P_TAG)?.into();
616        let q = scanner.scan_opt_big_int(Self::Q_TAG)?.map(Into::into);
617        let g = scanner.scan_big_int(Self::G_TAG)?.into();
618        let j = scanner.scan_opt_big_int(Self::J_TAG)?.map(Into::into);
619        let y = scanner.scan_big_int(Self::Y_TAG)?.into();
620        scanner.finish()?;
621        Ok(Self { p, q, g, j, y })
622    }
623
624    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
625        let mut formatter = formatter.format_struct(Self::TAG)?;
626        formatter.format_big_int(Self::P_TAG, &self.p)?;
627        if let Some(q) = &self.q {
628            formatter.format_big_int(Self::Q_TAG, q)?;
629        }
630        formatter.format_big_int(Self::G_TAG, &self.g)?;
631        if let Some(j) = &self.j {
632            formatter.format_big_int(Self::J_TAG, j)?;
633        }
634        formatter.format_big_int(Self::Y_TAG, &self.y)?;
635        Ok(formatter.finish())
636    }
637}
638
639/// See KMIP 1.2 section 2.1.10 [Data](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc395776391).
640#[derive(Clone, Debug, PartialEq, Eq)]
641pub struct Data(pub Vec<u8>);
642
643impl_ttlv_serde!(bytes Data as 0x4200C2);
644
645/// See KMIP 1.2 section 2.1.11 [Data Length](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613467).
646#[derive(Clone, Copy, Debug, PartialEq, Eq)]
647pub struct DataLength(pub i32);
648
649impl_ttlv_serde!(int DataLength as 0x4200C4);
650
651/// See KMIP 1.0 section 3.1 [Unique Identifier](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613482).
652#[derive(Clone, Debug, PartialEq, Eq)]
653pub struct UniqueIdentifier(pub String);
654
655impl std::ops::Deref for UniqueIdentifier {
656    type Target = String;
657
658    fn deref(&self) -> &Self::Target {
659        &self.0
660    }
661}
662
663impl std::cmp::PartialEq<str> for UniqueIdentifier {
664    fn eq(&self, other: &str) -> bool {
665        self.0 == other
666    }
667}
668
669impl_ttlv_serde!(text UniqueIdentifier as 0x420094);
670
671/// See KMIP 1.0 section 3.2 [Name](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581174).
672#[derive(Clone, Debug, PartialEq, Eq)]
673pub struct NameValue(pub String);
674
675impl fmt::Display for NameValue {
676    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677        f.write_str(&self.0)
678    }
679}
680
681impl FromStr for NameValue {
682    type Err = ();
683
684    fn from_str(s: &str) -> Result<Self, Self::Err> {
685        Ok(Self(s.to_string()))
686    }
687}
688
689impl_ttlv_serde!(text NameValue as 0x420055);
690
691/// See KMIP 1.0 section 3.3 [Object Type](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581175).
692#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
693#[non_exhaustive]
694#[repr(u32)]
695pub enum ObjectType {
696    // KMIP 1.0 and 1.1 variants
697    Certificate = 1,
698    SymmetricKey,
699    PublicKey,
700    PrivateKey,
701    SplitKey,
702    Template,
703    SecretData,
704    OpaqueObject,
705
706    // KMIP 1.2 variants
707    PGPKey,
708}
709
710impl fmt::Display for ObjectType {
711    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
712        write!(f, "{self:?}")
713    }
714}
715
716impl_ttlv_serde!(enum ObjectType as 0x420057);
717
718/// See KMIP 1.0 section 3.4 [Cryptographic Algorithm Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581176).
719#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
720#[non_exhaustive]
721#[allow(non_camel_case_types)]
722#[repr(u32)]
723pub enum CryptographicAlgorithm {
724    // Attributes defined by KMIP 1.0.
725    DES = 1,
726    TRIPLE_DES,
727    AES,
728    RSA,
729    DSA,
730    ECDSA,
731    HMAC_SHA1,
732    HMAC_SHA224,
733    HMAC_SHA256,
734    HMAC_SHA384,
735    HMAC_SHA512,
736    HMAC_MD5,
737    DH,
738    ECDH,
739    ECMQV,
740    Blowfish,
741    Camellia,
742    CAST5,
743    IDEA,
744    MARS,
745    RC2,
746    RC4,
747    RC5,
748    SKIPJACK,
749    Twofish,
750
751    // Attributes added in KMIP 1.2.
752    EC,
753
754    // Attributes added in KMIP 1.3.
755    One_Time_Pad,
756
757    // Attributes added in KMIP 1.4.
758    ChaCha20,
759    Poly1305,
760    ChaCha20Poly1305,
761    SHA3_224,
762    SHA3_256,
763    SHA3_384,
764    SHA3_512,
765    HMAC_SHA3_224,
766    HMAC_SHA3_256,
767    HMAC_SHA3_384,
768    HMAC_SHA3_512,
769    SHAKE_128,
770    SHAKE_256,
771
772    // Attributes added in KMIP 2.0.
773    //
774    // Note: KMIP 2.0 changed the way attributes are represented. Quoting https://www.p6r.com/articles/2018/03/24/detailed-differences-between-kmip-1-4-and-2-0/:
775    //   > Another big change has occurred to attributes both in how they
776    //   > are represented and encoded in the protocol. The text string name
777    //   > of each attribute, which was also passed in the binary TTLV
778    //   > protocol version, has finally been removed.
779    //
780    // Attributes that existed in earlier versions of KMIP can still be
781    // submitted to a KMIP 2.x server using the KMIP 1.x representation,
782    // assuming that the server supports the KMIP 1.x version that defined the
783    // attribute AND that the client request specifies that KMIP 1.x version
784    // in the request.
785    //
786    // Attributes added in KMIP 2.0 or later CANNOT be submitted to the server
787    // using the KMIP 1.x representation. This library does NOT yet support
788    // KMIP 2.x style attributes. The attributes below CANNOT therefore be
789    // sent to a spec compliant KMIP 1.x server, unless it has vendor specific
790    // extensions. One such vendor specific extension is that supported by
791    // NLnet Labs Cascade-HSM-Bridge which understands Ed448 and Ed25519
792    // attributes in requests even though it does not support KMIP 2.x style
793    // attributes.
794    ARIA,
795    SEED,
796    SM2,
797    SM3,
798    SM4,
799    GOST_R_34_10_2012,
800    GOST_R_34_11_2012,
801    GOST_R_34_13_2015,
802    GOST_28147_89,
803    XMSS,
804    SPHINCS_256,
805    McEliece,
806    McEliece_6960119,
807    McEliece_8192128,
808    Ed25519,
809    Ed448,
810}
811
812impl_ttlv_serde!(enum CryptographicAlgorithm as 0x420028);
813
814impl fmt::Display for CryptographicAlgorithm {
815    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816        write!(f, "{self:?}")
817    }
818}
819
820/// See KMIP 1.0 section 3.5 [Cryptographic Length](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581177).
821#[derive(Clone, Copy, Debug, PartialEq, Eq)]
822pub struct CryptographicLength(pub i32);
823
824impl_ttlv_serde!(int CryptographicLength as 0x42002A);
825
826/// See KMIP 1.0 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
827#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
828#[rustfmt::skip]
829pub struct CryptographicParameters {
830    pub block_cipher_mode: Option<BlockCipherMode>,
831    pub padding_method: Option<PaddingMethod>,
832    pub hashing_algorithm: Option<HashingAlgorithm>,
833    pub key_role_type: Option<KeyRoleType>,
834    pub digital_signature_algorithm: Option<DigitalSignatureAlgorithm>, // KMIP 1.2
835    pub cryptographic_algorithm: Option<CryptographicAlgorithm>, // KMIP 1.2
836    pub random_iv: Option<RandomIV>, // KMIP 1.2
837    pub iv_length: Option<IVLength>, // KMIP 1.2
838    pub tag_length: Option<TagLength>, // KMIP 1.2
839    pub fixed_field_length: Option<FixedFieldLength>, // KMIP 1.2
840    pub invocation_field_length: Option<InvocationFieldLength>, // KMIP 1.2
841    pub counter_length: Option<CounterLength>, // KMIP 1.2
842    pub initial_counter_value: Option<InitialCounterValue>, // KMIP 1.2
843}
844
845impl CryptographicParameters {
846    pub fn with_block_cipher_mode(self, value: BlockCipherMode) -> Self {
847        Self {
848            block_cipher_mode: Some(value),
849            ..self
850        }
851    }
852
853    pub fn with_padding_method(self, value: PaddingMethod) -> Self {
854        Self {
855            padding_method: Some(value),
856            ..self
857        }
858    }
859
860    pub fn with_hashing_algorithm(self, value: HashingAlgorithm) -> Self {
861        Self {
862            hashing_algorithm: Some(value),
863            ..self
864        }
865    }
866
867    pub fn with_key_role_type(self, value: KeyRoleType) -> Self {
868        Self {
869            key_role_type: Some(value),
870            ..self
871        }
872    }
873
874    pub fn with_digital_signature_algorithm(self, value: DigitalSignatureAlgorithm) -> Self {
875        Self {
876            digital_signature_algorithm: Some(value),
877            ..self
878        }
879    }
880
881    pub fn with_cryptographic_algorithm(self, value: CryptographicAlgorithm) -> Self {
882        Self {
883            cryptographic_algorithm: Some(value),
884            ..self
885        }
886    }
887
888    pub fn with_random_iv(self, value: RandomIV) -> Self {
889        Self {
890            random_iv: Some(value),
891            ..self
892        }
893    }
894
895    pub fn with_iv_length(self, value: IVLength) -> Self {
896        Self {
897            iv_length: Some(value),
898            ..self
899        }
900    }
901
902    pub fn with_tag_length(self, value: TagLength) -> Self {
903        Self {
904            tag_length: Some(value),
905            ..self
906        }
907    }
908
909    pub fn with_fixed_field_length(self, value: FixedFieldLength) -> Self {
910        Self {
911            fixed_field_length: Some(value),
912            ..self
913        }
914    }
915
916    pub fn with_invocation_field_length(self, value: InvocationFieldLength) -> Self {
917        Self {
918            invocation_field_length: Some(value),
919            ..self
920        }
921    }
922
923    pub fn with_counter_length(self, value: CounterLength) -> Self {
924        Self {
925            counter_length: Some(value),
926            ..self
927        }
928    }
929
930    pub fn with_initial_counter_value(self, value: InitialCounterValue) -> Self {
931        Self {
932            initial_counter_value: Some(value),
933            ..self
934        }
935    }
936}
937
938impl_ttlv_serde!(struct CryptographicParameters {
939    #[option] block_cipher_mode: BlockCipherMode,
940    #[option] padding_method: PaddingMethod,
941    #[option] hashing_algorithm: HashingAlgorithm,
942    #[option] key_role_type: KeyRoleType,
943    #[option] digital_signature_algorithm: DigitalSignatureAlgorithm,
944    #[option] cryptographic_algorithm: CryptographicAlgorithm,
945    #[option] random_iv: RandomIV,
946    #[option] iv_length: IVLength,
947    #[option] tag_length: TagLength,
948    #[option] fixed_field_length: FixedFieldLength,
949    #[option] invocation_field_length: InvocationFieldLength,
950    #[option] counter_length: CounterLength,
951    #[option] initial_counter_value: InitialCounterValue,
952} as 0x42002B);
953
954impl From<CryptographicParameters> for AttributeValue {
955    fn from(params: CryptographicParameters) -> Self {
956        AttributeValue::CryptographicParameters(params)
957    }
958}
959
960/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
961#[derive(Clone, Copy, Debug, PartialEq, Eq)]
962pub struct RandomIV(pub bool);
963
964impl_ttlv_serde!(bool RandomIV as 0x4200C5);
965
966/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
967#[derive(Clone, Copy, Debug, PartialEq, Eq)]
968pub struct IVLength(pub i32);
969
970impl_ttlv_serde!(int IVLength as 0x4200CD);
971
972/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
973#[derive(Clone, Copy, Debug, PartialEq, Eq)]
974pub struct TagLength(pub i32);
975
976impl_ttlv_serde!(int TagLength as 0x4200CE);
977
978/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
979#[derive(Clone, Copy, Debug, PartialEq, Eq)]
980pub struct FixedFieldLength(pub i32);
981
982impl_ttlv_serde!(int FixedFieldLength as 0x4200CF);
983
984/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
985#[derive(Clone, Copy, Debug, PartialEq, Eq)]
986pub struct InvocationFieldLength(pub i32);
987
988impl_ttlv_serde!(int InvocationFieldLength as 0x4200D2);
989
990/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
991#[derive(Clone, Copy, Debug, PartialEq, Eq)]
992pub struct CounterLength(pub i32);
993
994impl_ttlv_serde!(int CounterLength as 0x4200D0);
995
996/// See KMIP 1.2 section 3.6 [Cryptographic Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613487).
997#[derive(Clone, Copy, Debug, PartialEq, Eq)]
998pub struct InitialCounterValue(pub i32);
999
1000impl_ttlv_serde!(int InitialCounterValue as 0x4200D1);
1001
1002/// See KMIP 1.0 section 3.7 [Cryptographic Domain Parameters](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613488).
1003#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1004#[rustfmt::skip]
1005pub struct CryptographicDomainParameters {
1006    pub q_length: Option<i32>,
1007    pub recommended_curve: Option<RecommendedCurve>,
1008}
1009
1010impl CryptographicDomainParameters {
1011    pub fn with_q_length(self, value: i32) -> Self {
1012        Self {
1013            q_length: Some(value),
1014            ..self
1015        }
1016    }
1017
1018    pub fn with_recommended_curve(self, value: RecommendedCurve) -> Self {
1019        Self {
1020            recommended_curve: Some(value),
1021            ..self
1022        }
1023    }
1024}
1025
1026impl CryptographicDomainParameters {
1027    pub const TAG: Tag = Tag::new(0x420029);
1028    pub const Q_LENGTH_TAG: Tag = Tag::new(0x420073);
1029
1030    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1031        Self::fast_scan_with(scanner, Self::TAG)
1032    }
1033
1034    pub fn fast_scan_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Self, FastScanError> {
1035        let mut scanner = scanner.scan_struct(tag)?;
1036        let q_length = scanner.scan_opt_int(Self::Q_LENGTH_TAG)?;
1037        let recommended_curve = RecommendedCurve::fast_scan_opt(&mut scanner)?;
1038        scanner.finish()?;
1039        Ok(Self {
1040            q_length,
1041            recommended_curve,
1042        })
1043    }
1044
1045    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1046        self.format_with(formatter, Self::TAG)
1047    }
1048
1049    pub fn format_with(&self, formatter: &mut Formatter<'_>, tag: Tag) -> FormatResult {
1050        let mut formatter = formatter.format_struct(tag)?;
1051        if let Some(q_length) = self.q_length {
1052            formatter.format_int(Self::Q_LENGTH_TAG, q_length)?;
1053        }
1054        if let Some(recommended_curve) = &self.recommended_curve {
1055            recommended_curve.format(&mut formatter)?;
1056        }
1057        Ok(formatter.finish())
1058    }
1059}
1060
1061impl From<CryptographicDomainParameters> for AttributeValue {
1062    fn from(params: CryptographicDomainParameters) -> Self {
1063        AttributeValue::CryptographicDomainParameters(params)
1064    }
1065}
1066
1067bitflags::bitflags! {
1068    /// See KMIP 1.0 section 3.14 [Cryptographic Usage Mask](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581188).
1069    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1070    pub struct CryptographicUsageMask: i32 {
1071        const Sign                            = 0x00000001;
1072        const Verify                          = 0x00000002;
1073        const Encrypt                         = 0x00000004;
1074        const Decrypt                         = 0x00000008;
1075        const WrapKey                         = 0x00000010;
1076        const UnwrapKey                       = 0x00000020;
1077        const Export                          = 0x00000040;
1078        const MacGenerate                     = 0x00000080;
1079        const MacVerify                       = 0x00000100;
1080        const DeriveKey                       = 0x00000200;
1081        const ContentCommitmentNonRepudiation = 0x00000400;
1082        const KeyAgreement                    = 0x00000800;
1083        const CertificateSign                 = 0x00001000;
1084        const CrlSign                         = 0x00002000;
1085        const GenerateCryptogram              = 0x00004000;
1086        const ValidateCryptogram              = 0x00008000;
1087        const TranslateEncrypt                = 0x00010000;
1088        const TranslateDecrypt                = 0x00020000;
1089        const TranslateWrap                   = 0x00040000;
1090        const TranslateUnwrap                 = 0x00080000;
1091
1092        const _ = !0;
1093    }
1094}
1095
1096impl CryptographicUsageMask {
1097    pub const TAG: Tag = Tag::new(0x42002C);
1098
1099    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1100        Self::fast_scan_with(scanner, Self::TAG)
1101    }
1102
1103    pub fn fast_scan_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Self, FastScanError> {
1104        scanner.scan_int(tag).map(Self::from_bits_retain)
1105    }
1106
1107    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
1108        Self::fast_scan_opt_with(scanner, Self::TAG)
1109    }
1110
1111    pub fn fast_scan_opt_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Option<Self>, FastScanError> {
1112        scanner.scan_opt_int(tag).map(|s| s.map(Self::from_bits_retain))
1113    }
1114
1115    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1116        self.format_with(formatter, Self::TAG)
1117    }
1118
1119    pub fn format_with(&self, formatter: &mut Formatter<'_>, tag: Tag) -> FormatResult {
1120        formatter.format_int(tag, self.bits())
1121    }
1122}
1123
1124/// See KMIP 1.0 section 3.24 [Compromise Occurrence Date](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581198).
1125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1126pub struct CompromiseOccurrenceDate(pub u64);
1127
1128impl_ttlv_serde!(date_time CompromiseOccurrenceDate as 0x420021);
1129
1130/// See KMIP 1.0 section 3.26 [Revocation Reason](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581200).
1131#[derive(Clone, Debug, PartialEq, Eq)]
1132pub struct RevocationMessage(pub String);
1133
1134impl_ttlv_serde!(text RevocationMessage as 0x420080);
1135
1136/// See KMIP 1.0 section 3.29 [Linked Object Identifier](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581203).
1137#[derive(Clone, Debug, PartialEq, Eq)]
1138pub struct LinkedObjectIdentifier(pub String);
1139
1140impl_ttlv_serde!(text LinkedObjectIdentifier as 0x42004C);
1141
1142/// See KMIP 1.0 section 3.30 [Application Namespace](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581204).
1143#[derive(Clone, Debug, PartialEq, Eq)]
1144pub struct ApplicationNamespace(pub String);
1145
1146impl_ttlv_serde!(text ApplicationNamespace as 0x420003);
1147
1148/// See KMIP 1.0 section 3.30 [Application Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581204).
1149#[derive(Clone, Debug, PartialEq, Eq)]
1150pub struct ApplicationData(pub String);
1151
1152impl_ttlv_serde!(text ApplicationData as 0x420002);
1153
1154/// See KMIP 1.0 section 6.4 [Unique Batch Item ID](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581242).
1155#[derive(Clone, Debug, PartialEq, Eq)]
1156pub struct UniqueBatchItemID(pub Vec<u8>);
1157
1158impl PartialEq<Vec<u8>> for &UniqueBatchItemID {
1159    fn eq(&self, other: &Vec<u8>) -> bool {
1160        &self.0 == other
1161    }
1162}
1163
1164impl_ttlv_serde!(bytes UniqueBatchItemID as 0x420093);
1165
1166/// See KMIP 1.0 section 9.1.3.2.2 [Key Compression Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref241603856).
1167#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1168#[non_exhaustive]
1169#[repr(u32)]
1170pub enum KeyCompressionType {
1171    ECPUblicKeyTypeUncompressed = 1,
1172    ECPUblicKeyTypeX962CompressedPrime,
1173    ECPUblicKeyTypeX962CompressedChar2,
1174    ECPUblicKeyTypeX962Hybrid,
1175}
1176
1177impl_ttlv_serde!(enum KeyCompressionType as 0x420041);
1178
1179impl fmt::Display for KeyCompressionType {
1180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181        write!(f, "{self:?}")
1182    }
1183}
1184
1185/// See KMIP 1.0 section 9.1.3.2.3 [Key Format Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref241992670).
1186#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1187#[non_exhaustive]
1188#[repr(u32)]
1189pub enum KeyFormatType {
1190    Raw = 1,
1191    Opaque,
1192    PKCS1,
1193    PKCS8,
1194    X509,
1195    ECPrivateKey,
1196    TransparentSymmetricKey,
1197    TransparentDSAPrivateKey,
1198    TransparentDSAPublicKey,
1199    TransparentRSAPrivateKey,
1200    TransparentRSAPublicKey,
1201    TransparentDHPrivateKey,
1202    TransparentDHPublicKey,
1203    TransparentECDSAPrivateKey,
1204    TransparentECDSAPublicKey,
1205    TransparentECHDPrivateKey,
1206    TransparentECDHPublicKey,
1207    TransparentECMQVPrivateKey,
1208    TransparentECMQVPublicKey,
1209}
1210
1211impl_ttlv_serde!(enum KeyFormatType as 0x420042);
1212
1213impl fmt::Display for KeyFormatType {
1214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215        write!(f, "{self:?}")
1216    }
1217}
1218
1219/// See KMIP 1.0 section 9.1.3.2.5 [Recommended Curve Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581179).
1220#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1221#[non_exhaustive]
1222#[allow(non_camel_case_types)]
1223#[repr(u32)]
1224pub enum RecommendedCurve {
1225    P_192 = 1,
1226    K_163,
1227    B_163,
1228    P_224,
1229    K_233,
1230    B_233,
1231    P_256,
1232    K_283,
1233    B_283,
1234    P_384,
1235    K_409,
1236    B_409,
1237    P_521,
1238    K_571,
1239    B_571,
1240}
1241
1242impl_ttlv_serde!(enum RecommendedCurve as 0x420075);
1243
1244impl fmt::Display for RecommendedCurve {
1245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246        write!(f, "{self:?}")
1247    }
1248}
1249
1250/// See KMIP 1.0 section 9.1.3.2.6 [Certificate Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref241994296).
1251#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1252#[non_exhaustive]
1253#[repr(u32)]
1254pub enum CertificateType {
1255    X509 = 1,
1256    PGP,
1257}
1258
1259impl_ttlv_serde!(enum CertificateType as 0x42001D);
1260
1261impl fmt::Display for CertificateType {
1262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1263        write!(f, "{self:?}")
1264    }
1265}
1266
1267/// See KMIP 1.2 section 9.1.3.2.7 [Digital Signature Algorithm Enumeration](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Ref306812211).
1268#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1269#[non_exhaustive]
1270#[allow(non_camel_case_types)]
1271#[repr(u32)]
1272pub enum DigitalSignatureAlgorithm {
1273    MD2WithRSAEncryption_PKCS1_v1_5 = 1,
1274    MD5WithRSAEncryption_PKCS1_v1_5,
1275    SHA1WithRSAEncryption_PKCS1_v1_5,
1276    SHA224WithRSAEncryption_PKCS1_v1_5,
1277    SHA256WithRSAEncryption_PKCS1_v1_5,
1278    SHA384WithRSAEncryption_PKCS1_v1_5,
1279    SHA512WithRSAEncryption_PKCS1_v1_5,
1280    RSASSA_PSS_PKCS1_v1_5,
1281    DSAWithSHA1,
1282    DSAWithSHA224,
1283    DSAWithSHA256,
1284    ECDSAWithSHA1,
1285    ECDSAWithSHA224,
1286    ECDSAWithSHA256,
1287    ECDSAWithSHA384,
1288    ECDSAWithSHA512,
1289}
1290
1291impl_ttlv_serde!(enum DigitalSignatureAlgorithm as 0x4200AE);
1292
1293impl fmt::Display for DigitalSignatureAlgorithm {
1294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1295        write!(f, "{self:?}")
1296    }
1297}
1298
1299/// See KMIP 1.0 section 9.1.3.2.10 [Name Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262582060).
1300#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1301#[non_exhaustive]
1302#[repr(u32)]
1303pub enum NameType {
1304    UninterpretedTextString = 1,
1305    URI,
1306}
1307
1308impl_ttlv_serde!(enum NameType as 0x420054);
1309
1310impl fmt::Display for NameType {
1311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1312        write!(f, "{self:?}")
1313    }
1314}
1315
1316/// See KMIP 1.0 section 9.1.3.2.13 [Block Cipher Mode Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc236497881).
1317#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1318#[non_exhaustive]
1319#[allow(non_camel_case_types)]
1320#[repr(u32)]
1321pub enum BlockCipherMode {
1322    CBC = 1,
1323    ECB,
1324    PCBC,
1325    CFB,
1326    OFB,
1327    CTR,
1328    CMAC,
1329    CCM,
1330    GCM,
1331    CBC_MAC,
1332    XTS,
1333    AESKeyWrapPadding,
1334    NISTKeyWrap,
1335    X9_102_AESKW,
1336    X9_102_TDKW,
1337    X9_102_AKW1,
1338    X9_102_AKW2,
1339}
1340
1341impl_ttlv_serde!(enum BlockCipherMode as 0x420011);
1342
1343impl fmt::Display for BlockCipherMode {
1344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345        write!(f, "{self:?}")
1346    }
1347}
1348
1349/// See KMIP 1.0 section 9.1.3.2.14 [Padding Method Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc236497883).
1350#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1351#[non_exhaustive]
1352#[allow(non_camel_case_types)]
1353#[repr(u32)]
1354pub enum PaddingMethod {
1355    None = 1,
1356    OAEP,
1357    PKCS5,
1358    SSL3,
1359    Zeros,
1360    ANSI_X9_23,
1361    ISO_10126,
1362    PKCS1_v1_5,
1363    X9_31,
1364    PSS,
1365}
1366
1367impl_ttlv_serde!(enum PaddingMethod as 0x42005F);
1368
1369impl fmt::Display for PaddingMethod {
1370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1371        write!(f, "{self:?}")
1372    }
1373}
1374
1375/// See KMIP 1.0 section 9.1.3.2.15 [Hashing Algorithm Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc236497883).
1376#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1377#[non_exhaustive]
1378#[allow(non_camel_case_types)]
1379#[repr(u32)]
1380pub enum HashingAlgorithm {
1381    MD2 = 1,
1382    MD4,
1383    MD5,
1384    SHA1,
1385    SHA224,
1386    SHA256,
1387    SHA384,
1388    SHA512,
1389    RIPEMD160,
1390    Tiger,
1391    Whirlpool,
1392}
1393
1394impl_ttlv_serde!(enum HashingAlgorithm as 0x420038);
1395
1396impl fmt::Display for HashingAlgorithm {
1397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398        write!(f, "{self:?}")
1399    }
1400}
1401
1402/// See KMIP 1.0 section 9.1.3.2.15 [Key Role Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc236497884).
1403#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1404#[non_exhaustive]
1405#[allow(non_camel_case_types)]
1406#[repr(u32)]
1407pub enum KeyRoleType {
1408    BDK = 1,
1409    CVK,
1410    DEK,
1411    MKAC,
1412    MKSMC,
1413    MKSMI,
1414    MKDAC,
1415    MKDN,
1416    MKCP,
1417    MKOTH,
1418    KEK,
1419    MAC16609,
1420    MAC97971,
1421    MAC97972,
1422    MAC97973,
1423    MAC97974,
1424    MAC97975,
1425    ZPK,
1426    PVKIBM,
1427    PVKPVV,
1428    PVKOTH,
1429}
1430
1431impl_ttlv_serde!(enum KeyRoleType as 0x420083);
1432
1433impl fmt::Display for KeyRoleType {
1434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1435        write!(f, "{self:?}")
1436    }
1437}
1438
1439/// See KMIP 1.0 section 9.1.3.2.17 [State Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262582066).
1440#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1441#[non_exhaustive]
1442#[repr(u32)]
1443pub enum State {
1444    PreActive = 1,
1445    Active,
1446    Deactivated,
1447    Compromised,
1448    Destroyed,
1449    DestroyedCompromised,
1450}
1451
1452impl_ttlv_serde!(enum State as 0x42008D);
1453
1454impl fmt::Display for State {
1455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456        write!(f, "{self:?}")
1457    }
1458}
1459
1460/// See KMIP 1.0 section 9.1.3.2.18 [Revocation Reason Code Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref241996204).
1461#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1462#[non_exhaustive]
1463#[repr(u32)]
1464pub enum RevocationReasonCode {
1465    Unspecified = 1,
1466    KeyCompromise,
1467    CACompromise,
1468    AffiliationChanged,
1469    Superseded,
1470    CessationOfOperation,
1471    PrivilegeWithdrawn,
1472}
1473
1474impl_ttlv_serde!(enum RevocationReasonCode as 0x420082);
1475
1476impl fmt::Display for RevocationReasonCode {
1477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478        write!(f, "{self:?}")
1479    }
1480}
1481
1482/// See KMIP 1.0 section 9.1.3.2.19 [Link Type Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262582069).
1483#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1484#[non_exhaustive]
1485#[repr(u32)]
1486pub enum LinkType {
1487    CertificateLink = 0x101,
1488    PublicKeyLink,
1489    PrivateKeyLink,
1490    DerivationBaseObjectLink,
1491    DerivedKeyLink,
1492    ReplacementObjectLink,
1493    ReplacedObjectLink,
1494}
1495
1496impl_ttlv_serde!(enum LinkType as 0x42004B);
1497
1498impl fmt::Display for LinkType {
1499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1500        write!(f, "{self:?}")
1501    }
1502}
1503
1504/// See KMIP 1.0 section 9.1.3.2.26 [Operation Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc236497894).
1505#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1506#[non_exhaustive]
1507#[repr(u32)]
1508pub enum Operation {
1509    // KMIP 1.0 operations
1510    Create = 1,
1511    CreateKeyPair,
1512    Register,
1513    Rekey,
1514    DeriveKey,
1515    Certify,
1516    Recertify,
1517    Locate,
1518    Check,
1519    Get,
1520    GetAttributes,
1521    GetAttributeList,
1522    AddAttribute,
1523    ModifyAttribute,
1524    DeleteAttribute,
1525    ObtainLease,
1526    GetUsageAllocation,
1527    Activate,
1528    Revoke,
1529    Destroy,
1530    Archive,
1531    Recover,
1532    Validate,
1533    Query,
1534    Cancel,
1535    Poll,
1536    Notify,
1537    Put,
1538
1539    // KMIP 1.1 operations
1540    RekeyKeyPair,
1541    DiscoverVersions,
1542
1543    // KMIP 1.2 operations
1544    Encrypt,
1545    Decrypt,
1546    Sign,
1547    SignatureVerify,
1548    MAC,
1549    MACVerify,
1550    RNGRetrieve,
1551    RNGSeed,
1552    Hash,
1553    CreateSplitKey,
1554    JoinSplitKey,
1555}
1556
1557impl_ttlv_serde!(enum Operation as 0x42005C);
1558
1559impl fmt::Display for Operation {
1560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561        write!(f, "{self:?}")
1562    }
1563}
1564
1565#[cfg(test)]
1566mod test {
1567    use super::Operation;
1568
1569    #[test]
1570    fn test_operation_display() {
1571        assert_ne!("WrongName", &format!("{}", Operation::Create));
1572        assert_eq!("Create", &format!("{}", Operation::Create));
1573        assert_eq!("CreateKeyPair", &format!("{}", Operation::CreateKeyPair));
1574        assert_eq!("Register", &format!("{}", Operation::Register));
1575    }
1576}