Skip to main content

bouncycastle_core_interface/
key_material.rs

1//! A helper class used across the bc-rust library to hold bytes-like key material.
2//! The main purpose is to hold metadata about the contained key material such as the key type and
3//! entropy content to prevent accidental misuse security bugs, such as deriving cryptographic keys
4//! from uninitialized data.
5//!
6//! This object allows several types of manual-overrides, which typically require setting the [KeyMaterialInternal::allow_hazardous_operations] flag.
7//! For example, the raw bytes data can be extracted, or the key forced to a certain type,
8//! but well-designed use of the bc-rust.test library should not need to ever set the [KeyMaterialInternal::allow_hazardous_operations] flag.
9//! The core idea of this wrapper is to keep track of the usage of the key material, including
10//! the amount of entropy that it is presumed to contain in order to prevent users from accidentally
11//! using it inappropriately in a way that could lead to security weaknesses.
12//!
13//! Various operations within the bc-rs library will consume or produce KeyMaterial objects with
14//! specific key types. In normal use of the bc-rs APIs, users should never have to manually convert
15//! the type of a KeyMaterial object because the various function calls will set the key type appropriately.
16//!
17//! Some typical workflows would be:
18//!
19//! * Hash functions take in \[u8\] byte data and return a KeyMaterial of type RawUnknownEntropy.
20//! * Password-based key derivation functions act on KeyMaterial of any type, and in the case of RawFullEntropy, RawLowEntropy, or RawUnknownEntropy, will preserve the entropy rating.
21//! * Keyed KDFs that are given a key of RawFullEntropy or KeyedHashKey a KeyMaterial data of type RawLowEntropy or RawUnknownEntropy will promote it into RawFullEntropy.
22//! * Symmetric ciphers or asymmetric ciphers such as X25519 or ML-KEM that accept private key seeds will expect KeyMaterial of type AsymmetricPrivateKeySeed.
23//!
24//! However, there is a [KeyMaterialInternal::convert_key_type] for cases where the user has more context knowledge than the library.
25//! Some conversions, such as converting a key of type RawLowEntropy into a SymmetricCipherKey, will fail unless
26//! the user has explicitly allowed them via calling allow_hazardous_operations() prior to the conversion.
27//!
28//! Examples of hazardous conversions that require allow_hazardous_operations() to be called first:
29//!
30//! * Converting a KeyMaterial of type RawLowEntropy or RawUnknownEntropy into RawFullEntropy or any other full-entropy key type.
31//! * Converting any algorithm-specific key type into a different algorithm-specific key type, which is considered hazardous since key reuse between different cryptographic algorithms is generally discouraged and can sometimes lead to key leakage.
32//!
33//! Additional security features:
34//!   * Zeroizes on destruction.
35//!   * Implementing Display and Debug to print metadata but not key material to prevent accidental logging.
36//!
37//! As with all wrappers of this nature, the intent is to protect the user from making silly mistakes, not to prevent expert users from doing what they need to do.
38//! It as always possible, for example, to extract the bytes from a KeyMaterial object, manipulate them, and then re-wrap them in a new KeyMaterial object.
39
40use crate::errors::KeyMaterialError;
41use crate::traits::{RNG, SecurityStrength};
42use bouncycastle_utils::{ct, max, min};
43
44use std::cmp::{Ordering, PartialOrd};
45use std::fmt;
46
47/// Sometimes you just need a zero-length dummy key.
48pub type KeyMaterial0 = KeyMaterialInternal<0>;
49
50pub type KeyMaterial128 = KeyMaterialInternal<16>;
51pub type KeyMaterial256 = KeyMaterialInternal<32>;
52pub type KeyMaterial512 = KeyMaterialInternal<64>;
53
54
55/// A helper class used across the bc-rust.test library to hold bytes-like key material.
56/// See [KeyMaterialInternal] for for details, such as constructors.
57pub trait KeyMaterial {
58    /// Loads the provided data into a new KeyMaterial of the specified type.
59    /// This is discouraged unless the caller knows the provenance of the data, such as loading it
60    /// from a cryptographic private key file.
61    /// It will detect if you give it all-zero source data and set the key type to [KeyType::Zeroized] instead.
62    /// Since this zeroizes and resets the key material, this is considered a dangerous conversion.
63    ///
64    /// The only hazardous operation here that requires setting [KeyMaterial::allow_hazardous_operations] is giving it
65    /// an all-zero key, which is checked as a courtesy to catch mistakes of feeding an initialized buffer
66    /// instead of an actual key. See the note on [KeyMaterialInternal::set_bytes_as_type] for suggestions
67    /// for handling this.
68    fn set_bytes_as_type(
69        &mut self,
70        source: &[u8],
71        key_type: KeyType,
72    ) -> Result<(), KeyMaterialError>;
73
74    /// Get a reference to the underlying key material bytes.
75    ///
76    /// By reading the key bytes out of the [KeyMaterial] object, you lose the protections that it offers,
77    /// however, this does not require [KeyMaterial::allow_hazardous_operations] in the name of API ergonomics:
78    /// setting [KeyMaterial::allow_hazardous_operations] requires a mutable reference and reading the bytes
79    /// is not an operation that should require mutability.
80    fn ref_to_bytes(&self) -> &[u8];
81
82    /// Get a mutable reference to the underlying key material bytes so that you can read or write
83    /// to the underlying bytes without needing to create a temporary buffer, especially useful in
84    /// cases where the required size of that buffer may be tricky to figure out at compile-time.
85    /// This requires [KeyMaterial::allow_hazardous_operations] to be set.
86    /// When writing directly to the buffer, you are responsible for setting the key_len and key_type afterwards,
87    /// and you should [KeyMaterial::drop_hazardous_operations].
88    fn mut_ref_to_bytes(&mut self) -> Result<&mut [u8], KeyMaterialError>;
89
90    /// The size of the internal buffer; ie the largest key that this instance can hold.
91    /// Equivalent to the <KEY_LEN> constant param this object was created with.
92    fn capacity(&self) -> usize;
93
94    /// Length of the key material in bytes.
95    fn key_len(&self) -> usize;
96
97    /// Requires [KeyMaterial::allow_hazardous_operations].
98    fn set_key_len(&mut self, key_len: usize) -> Result<(), KeyMaterialError>;
99
100    fn key_type(&self) -> KeyType;
101
102    /// Requires [KeyMaterial::allow_hazardous_operations].
103    fn set_key_type(&mut self, key_type: KeyType) -> Result<(), KeyMaterialError>;
104
105    /// Security Strength, as used here, aligns with NIST SP 800-90A guidance for random number generation,
106    /// specifically section 8.4.
107    ///
108    /// The idea is to be able to track for cryptographic seeds and bytes-like key objects across the entire library,
109    /// the instatiated security level of the RNG that generated it, and whether it was handled by any intermediate
110    /// objects, such as Key Derivation Functions, that have a smaller internal security level and therefore result in
111    /// downgrading the security level of the key material.
112    ///
113    /// Note that while security strength is closely related to entropy, it is a property of the algorithms
114    /// that touched the key material and not of the key material data itself, and therefore it is
115    /// tracked independantly from key length and entropy level / key type.
116    fn security_strength(&self) -> SecurityStrength;
117
118    /// Requires [KeyMaterial::allow_hazardous_operations] to raise the security strength, but not to lower it.
119    /// Throws [KeyMaterialError::HazardousOperationNotPermitted] on a request to raise the security level without
120    /// [KeyMaterial::allow_hazardous_operations] set.
121    /// Throws [KeyMaterialError::InvalidLength] on a request to set the security level higher than the current key length.
122    fn set_security_strength(&mut self, strength: SecurityStrength)
123                             -> Result<(), KeyMaterialError>;
124
125    /// Sets this instance to be able to perform potentially hazardous conversions such as
126    /// casting a KeyMaterial of type RawUnknownEntropy or RawLowEntropy into RawFullEntropy or SymmetricCipherKey,
127    /// or manually setting the key bytes via [KeyMaterial::mut_ref_to_bytes], which then requires you to be responsible
128    /// for setting the key_len and key_type afterwards.
129    ///
130    /// The purpose of the hazardous_conversions guard is not to prevent the user from accessing their data,
131    /// but rather to make the developer think carefully about the operation they are about to perform,
132    /// and to give static analysis tools an obvious marker that a given KeyMaterial variable warrants
133    /// further inspection.
134    fn allow_hazardous_operations(&mut self);
135
136    /// Resets this instance to not be able to perform potentially hazardous conversions.
137    fn drop_hazardous_operations(&mut self);
138
139    /// Sets the key_type of this KeyMaterial object.
140    /// Does not perform any operations on the actual key material, other than changing the key_type field.
141    /// If allow_hazardous_operations is true, this method will allow conversion to any KeyType, otherwise
142    /// checking is performed to ensure that the conversion is "safe".
143    /// This drops the allow_hazardous_operations flag, so if you need to do multiple hazardous conversions
144    /// on the same instance, then you'll need to call .allow_hazardous_operations() each time.
145    fn convert_key_type(&mut self, new_key_type: KeyType) -> Result<(), KeyMaterialError>;
146
147    fn is_full_entropy(&self) -> bool;
148
149    fn zeroize(&mut self);
150
151    /// Is simply an alias to [KeyMaterial::set_key_len], however, this does not require [KeyMaterial::allow_hazardous_operations]
152    /// since truncation is a safe operation.
153    /// If truncating below the current security strength, the security strength will be lowered accordingly.
154    fn truncate(&mut self, new_len: usize) -> Result<(), KeyMaterialError>;
155
156    /// Adds the other KeyMaterial into this one, assuming there is space.
157    /// Does not require [KeyMaterial::allow_hazardous_operations].
158    /// Throws [KeyMaterialError::InvalidLength] if this object does not have enough space to add the other one.
159    /// The resulting [KeyType] and security strength will be the lesser of the two keys.
160    /// In other words, concatenating two 128-bit full entropy keys generated at a 128-bit DRBG security level
161    /// will result in a 256-bit full entropy key still at the 128-bit DRBG security level.
162    /// Concatenating a full entropy key with a low entropy key will result in a low entropy key.
163    ///
164    /// Returns the new key_len.
165    fn concatenate(&mut self, other: &dyn KeyMaterial) -> Result<usize, KeyMaterialError>;
166
167    /// Perform a constant-time comparison between the two key material buffers,
168    /// ignoring differences in capacity, [KeyType], [SecurityStrength], etc.
169    fn equals(&self, other: &dyn KeyMaterial) -> bool;
170}
171
172/// A wrapper for holding bytes-like key material (symmetric keys or seeds) which aims to apply a
173/// strict typing system to prevent many kinds of mis-use mistakes.
174/// The capacity of the internal buffer can be set at compile-time via the <KEY_LEN> param.
175#[derive(Clone)]
176pub struct KeyMaterialInternal<const KEY_LEN: usize> {
177    buf: [u8; KEY_LEN],
178    key_len: usize,
179    key_type: KeyType,
180    security_strength: SecurityStrength,
181    allow_hazardous_operations: bool,
182}
183
184#[derive(Clone, Copy, Debug, Eq, PartialEq)]
185pub enum KeyType {
186    /// The KeyMaterial is zeroized and MUST NOT be used for any cryptographic operation in this state.
187    Zeroized,
188
189    /// The KeyMaterial contains data of low or unknown entropy.
190    BytesLowEntropy,
191
192    /// The KeyMaterial contains data of full entropy and can be safely converted to any other full-entropy key type.
193    BytesFullEntropy,
194
195    /// A seed for asymmetric private keys, RNGs, and other seed-based cryptographic objects.
196    Seed,
197
198    /// A MAC key.
199    MACKey,
200
201    /// A key for a symmetric block or stream cipher.
202    SymmetricCipherKey,
203}
204
205impl<const KEY_LEN: usize> Default for KeyMaterialInternal<KEY_LEN> {
206    /// Create a new empty (zeroized) instance.
207    fn default() -> Self {
208        Self::new()
209    }
210}
211
212impl<const KEY_LEN: usize> KeyMaterialInternal<KEY_LEN> {
213    pub fn new() -> Self {
214        Self {
215            buf: [0u8; KEY_LEN],
216            key_len: 0,
217            key_type: KeyType::Zeroized,
218            security_strength: SecurityStrength::None,
219            allow_hazardous_operations: false,
220        }
221    }
222
223    /// Create a new instance of KeyMaterial containing random bytes from the provided random number generator.
224    pub fn from_rng(rng: &mut impl RNG) -> Result<Self, KeyMaterialError> {
225        let mut key = Self::new();
226        key.allow_hazardous_operations();
227
228        rng.next_bytes_out(&mut key.mut_ref_to_bytes().unwrap())
229            .map_err(|_| KeyMaterialError::GenericError("RNG failed."))?;
230
231        key.key_len = KEY_LEN;
232        key.key_type = KeyType::BytesFullEntropy;
233        key.security_strength = rng.security_strength();
234        key.drop_hazardous_operations();
235        Ok(key)
236    }
237
238    /// Constructor.
239    /// Loads the provided data into a new KeyMaterial of type [KeyType::BytesLowEntropy].
240    /// It will detect if you give it all-zero source data and set the key type to [KeyType::Zeroized] instead.
241    pub fn from_bytes(source: &[u8]) -> Result<Self, KeyMaterialError> {
242        Self::from_bytes_as_type(source, KeyType::BytesLowEntropy)
243    }
244
245    /// Constructor.
246    /// Loads the provided data into a new KeyMaterial of the specified type.
247    /// This is discouraged unless the caller knows the provenance of the data, such as loading it
248    /// from a cryptographic private key file.
249    /// It will detect if you give it all-zero source data and set the key type to [KeyType::Zeroized] instead.
250    ///
251    /// Will set the [SecurityStrength] automatically according to the following rules:
252    /// * If [KeyType] is [KeyType::Zeroized] or [KeyType::BytesLowEntropy] then it will be [SecurityStrength::None].
253    /// * Otherwise it will set it based on the length of the provided source bytes.
254    pub fn from_bytes_as_type(source: &[u8], key_type: KeyType) -> Result<Self, KeyMaterialError> {
255        let mut key_material = Self::default();
256
257        // Special case: catch and ignore the courtesy error about zeroized input and simply return a zeroized key.
258        match key_material.set_bytes_as_type(source, key_type) {
259            Ok(_) => Ok(key_material),
260            Err(KeyMaterialError::ActingOnZeroizedKey) => {
261                debug_assert_eq!(key_material.key_type(), KeyType::Zeroized);
262                Ok(key_material)
263            }
264            Err(e) => Err(e),
265        }
266    }
267
268    /// Copy constructor
269    pub fn from_key(other: &impl KeyMaterial) -> Result<Self, KeyMaterialError> {
270        if other.key_len() > KEY_LEN {
271            return Err(KeyMaterialError::InputDataLongerThanKeyCapacity);
272        }
273
274        let mut key = Self {
275            buf: [0u8; KEY_LEN],
276            key_len: other.key_len(),
277            key_type: other.key_type(),
278            security_strength: SecurityStrength::None,
279            allow_hazardous_operations: false,
280        };
281        key.buf[..other.key_len()].copy_from_slice(other.ref_to_bytes());
282        Ok(key)
283    }
284}
285
286impl<const KEY_LEN: usize> KeyMaterial for KeyMaterialInternal<KEY_LEN> {
287    /// Loads the provided data into a new KeyMaterial of the specified type.
288    /// This is discouraged unless the caller knows the provenance of the data, such as loading it
289    /// from a cryptographic private key file.
290    ///
291    /// This behaves differently on all-zero input key depending on whether [KeyMaterial::allow_hazardous_operations] is set:
292    /// if not set, then it will succeed, setting the key type to [KeyType::Zeroized] and also return a [KeyMaterialError::ActingOnZeroizedKey]
293    /// to indicate that you may want to perform error-handling, which could be manually setting the key type
294    /// if you intend to allow zero keys, or do some other error-handling, like figure out why your RNG is broken.
295    /// Note that even if a [KeyMaterialError::ActingOnZeroizedKey] is returned, the object is still populated and usable.
296    /// For example, you could catch it like this:
297    /// ```
298    /// use core_interface::key_material::{KeyMaterial256, KeyType};
299    /// use core_interface::key_material::KeyMaterial;
300    /// use core_interface::errors::KeyMaterialError;
301    ///
302    /// let key_bytes = [0u8; 16];
303    /// let mut key = KeyMaterial256::new();
304    /// let res = key.set_bytes_as_type(&key_bytes, KeyType::BytesLowEntropy);
305    /// match res {
306    ///   Err(KeyMaterialError::ActingOnZeroizedKey) => {
307    ///     // Either figure out why your passed an all-zero key,
308    ///     // or set the key type manually, if that's what you intended.
309    ///     key.allow_hazardous_operations();
310    ///     key.set_key_type(KeyType::BytesLowEntropy).unwrap(); // probably you should do something more elegant than .unwrap in your code ;)
311    ///     key.drop_hazardous_operations();
312    ///   },
313    ///   Err(_) => { /* figure out what else went wrong */ },
314    ///   Ok(_) => { /* good */ },
315    /// }
316    /// ```
317    /// On the other hand, if [KeyMaterial::allow_hazardous_operations] is set then it will just do what you asked without complaining.
318    ///
319    /// Since this zeroizes and resets the key material, this is considered a dangerous conversion.
320    ///
321    /// Will set the [SecurityStrength] automatically according to the following rules:
322    /// * If [KeyType] is [KeyType::Zeroized] or [KeyType::BytesLowEntropy] then it will be [SecurityStrength::None].
323    /// * Otherwise it will set it based on the length of the provided source bytes.
324    fn set_bytes_as_type(
325        &mut self,
326        source: &[u8],
327        key_type: KeyType,
328    ) -> Result<(), KeyMaterialError> {
329        let allowed_hazardous_operations = self.allow_hazardous_operations;
330        self.allow_hazardous_operations();
331
332        if source.len() > KEY_LEN {
333            return Err(KeyMaterialError::InputDataLongerThanKeyCapacity);
334        }
335
336        let new_key_type = if !allowed_hazardous_operations && ct::ct_eq_zero_bytes(source) {
337            KeyType::Zeroized
338        } else {
339            key_type
340        };
341
342        self.buf[..source.len()].copy_from_slice(source);
343        self.key_len = source.len();
344        self.key_type = new_key_type;
345
346        if new_key_type <= KeyType::BytesLowEntropy {
347            self.set_security_strength(SecurityStrength::None)?;
348        } else {
349            self.set_security_strength(SecurityStrength::from_bits(source.len() * 8))?;
350        }
351        self.drop_hazardous_operations();
352
353        // return
354        if new_key_type == KeyType::Zeroized {
355            Err(KeyMaterialError::ActingOnZeroizedKey)
356        } else {
357            Ok(())
358        }
359    }
360
361    fn ref_to_bytes(&self) -> &[u8] {
362        &self.buf[..self.key_len]
363    }
364
365    fn mut_ref_to_bytes(&mut self) -> Result<&mut [u8], KeyMaterialError> {
366        if !self.allow_hazardous_operations {
367            return Err(KeyMaterialError::HazardousOperationNotPermitted);
368        }
369        Ok(&mut self.buf)
370    }
371
372    fn capacity(&self) -> usize {
373        KEY_LEN
374    }
375
376    fn key_len(&self) -> usize {
377        self.key_len
378    }
379
380    fn set_key_len(&mut self, key_len: usize) -> Result<(), KeyMaterialError> {
381        if !self.allow_hazardous_operations {
382            return Err(KeyMaterialError::HazardousOperationNotPermitted);
383        }
384        if key_len > KEY_LEN {
385            return Err(KeyMaterialError::InvalidLength);
386        }
387        self.key_len = key_len;
388        Ok(())
389    }
390    fn key_type(&self) -> KeyType {
391        self.key_type.clone()
392    }
393    fn set_key_type(&mut self, key_type: KeyType) -> Result<(), KeyMaterialError> {
394        if !self.allow_hazardous_operations {
395            return Err(KeyMaterialError::HazardousOperationNotPermitted);
396        }
397        self.key_type = key_type.clone();
398        Ok(())
399    }
400    fn security_strength(&self) -> SecurityStrength {
401        self.security_strength.clone()
402    }
403
404    fn set_security_strength(
405        &mut self,
406        strength: SecurityStrength,
407    ) -> Result<(), KeyMaterialError> {
408        if strength > self.security_strength && !self.allow_hazardous_operations {
409            return Err(KeyMaterialError::HazardousOperationNotPermitted);
410        };
411
412        if self.key_type <= KeyType::BytesLowEntropy && strength > SecurityStrength::None {
413            return Err(KeyMaterialError::SecurityStrength(
414                "BytesLowEntropy keys cannot have a security strength other than None.",
415            ));
416        }
417
418        match strength {
419            SecurityStrength::None => { /* fine, you can always downgrade */ }
420            SecurityStrength::_112bit => {
421                if self.key_len() < 14 {
422                    return Err(KeyMaterialError::SecurityStrength(
423                        "Security strength cannot be higher than key length.",
424                    ));
425                }
426            }
427            SecurityStrength::_128bit => {
428                if self.key_len() < 16 {
429                    return Err(KeyMaterialError::SecurityStrength(
430                        "Security strength cannot be larger than key length.",
431                    ));
432                }
433            }
434            SecurityStrength::_192bit => {
435                if self.key_len() < 24 {
436                    return Err(KeyMaterialError::SecurityStrength(
437                        "Security strength cannot be larger than key length.",
438                    ));
439                }
440            }
441            SecurityStrength::_256bit => {
442                if self.key_len() < 32 {
443                    return Err(KeyMaterialError::SecurityStrength(
444                        "Security strength cannot be larger than key length.",
445                    ));
446                }
447            }
448        }
449
450        self.security_strength = strength;
451        self.drop_hazardous_operations();
452        Ok(())
453    }
454    /// Sets this instance to be able to perform potentially hazardous operations such as
455    /// casting a KeyMaterial of type RawUnknownEntropy or RawLowEntropy into RawFullEntropy or SymmetricCipherKey.
456    ///
457    /// The purpose of the hazardous operations guard is not to prevent the user from accessing their data,
458    /// but rather to make the developer think carefully about the operation they are about to perform,
459    /// and to give static analysis tools an obvious marker that a given KeyMaterial variable warrants
460    /// further inspection.
461    fn allow_hazardous_operations(&mut self) {
462        self.allow_hazardous_operations = true;
463    }
464    /// Resets this instance to not be able to perform potentially hazardous operations.
465    fn drop_hazardous_operations(&mut self) {
466        self.allow_hazardous_operations = false;
467    }
468    /// Sets the key_type of this KeyMaterial object.
469    /// Does not perform any operations on the actual key material, other than changing the key_type field.
470    /// If allow_hazardous_operations is true, this method will allow conversion to any KeyType, otherwise
471    /// checking is performed to ensure that the conversion is "safe".
472    /// This drops the allow_hazardous_operations flag, so if you need to do multiple hazardous operations
473    /// on the same instance, then you'll need to call .allow_hazardous_operations() each time.
474    fn convert_key_type(&mut self, new_key_type: KeyType) -> Result<(), KeyMaterialError> {
475        if self.allow_hazardous_operations {
476            // just do it
477            self.key_type = new_key_type;
478            return Ok(());
479        }
480
481        match self.key_type {
482            KeyType::Zeroized => {
483                return Err(KeyMaterialError::ActingOnZeroizedKey);
484            }
485            KeyType::BytesFullEntropy => {
486                // raw full entropy can be safely converted to anything.
487                self.key_type = new_key_type;
488            }
489            KeyType::BytesLowEntropy => {
490                match new_key_type {
491                    KeyType::BytesLowEntropy => { /* No change */ }
492                    _ => {
493                        return Err(KeyMaterialError::HazardousOperationNotPermitted);
494                    }
495                }
496            }
497            KeyType::MACKey => {
498                match new_key_type {
499                    KeyType::MACKey => { /* No change */ }
500                    // Else: Once a KeyMaterial is typed, it should stay that way.
501                    _ => {
502                        return Err(KeyMaterialError::HazardousOperationNotPermitted);
503                    }
504                }
505            }
506            KeyType::SymmetricCipherKey => {
507                match new_key_type {
508                    KeyType::SymmetricCipherKey => { /* No change */ }
509                    // Else: Once a KeyMaterial is typed, it should stay that way.
510                    _ => {
511                        return Err(KeyMaterialError::HazardousOperationNotPermitted);
512                    }
513                }
514            }
515            KeyType::Seed => {
516                match new_key_type {
517                    KeyType::Seed => { /* No change */ }
518                    // Else: Once a KeyMaterial is typed, it should stay that way.
519                    _ => {
520                        return Err(KeyMaterialError::HazardousOperationNotPermitted);
521                    }
522                }
523            }
524        }
525
526        // each call to allow_hazardous_operations() is only good for one conversion.
527        self.drop_hazardous_operations();
528        Ok(())
529    }
530    fn is_full_entropy(&self) -> bool {
531        match self.key_type {
532            KeyType::BytesFullEntropy
533            | KeyType::Seed
534            | KeyType::MACKey
535            | KeyType::SymmetricCipherKey => true,
536            KeyType::Zeroized | KeyType::BytesLowEntropy => false,
537        }
538    }
539
540    fn zeroize(&mut self) {
541        self.buf.fill(0u8);
542        self.key_len = 0;
543        self.key_type = KeyType::Zeroized;
544    }
545
546    fn truncate(&mut self, new_len: usize) -> Result<(), KeyMaterialError> {
547        if new_len > self.key_len {
548            return Err(KeyMaterialError::InvalidLength);
549        }
550
551        self.security_strength =
552            min(&self.security_strength, &SecurityStrength::from_bits(new_len * 8)).clone();
553
554        if new_len == 0 {
555            self.key_type = KeyType::Zeroized;
556        }
557
558        self.key_len = new_len;
559        Ok(())
560    }
561
562    fn concatenate(&mut self, other: &dyn KeyMaterial) -> Result<usize, KeyMaterialError> {
563        let new_key_len = self.key_len() + other.key_len();
564        if self.key_len() + other.key_len() > KEY_LEN {
565            return Err(KeyMaterialError::InputDataLongerThanKeyCapacity);
566        }
567        self.buf[self.key_len..new_key_len].copy_from_slice(other.ref_to_bytes());
568        self.key_len += other.key_len();
569        self.key_type = max(&self.key_type, &other.key_type()).clone();
570        self.security_strength = max(&self.security_strength, &other.security_strength()).clone();
571        Ok(self.key_len())
572    }
573
574    fn equals(&self, other: &dyn KeyMaterial) -> bool {
575        if self.key_len() != other.key_len() {
576            return false;
577        }
578        ct::ct_eq_bytes(&self.ref_to_bytes(), &other.ref_to_bytes())
579    }
580}
581
582/// Checks for equality of the key data (using a constant-time comparison), but does not check that
583/// the two keys have the same type.
584/// Therefore, for example, two keys loaded from the same bytes, one with type [KeyType::BytesLowEntropy] and
585/// the other with [KeyType::MACKey] will be considered equal.
586impl<const KEY_LEN: usize> PartialEq for KeyMaterialInternal<KEY_LEN> {
587    fn eq(&self, other: &Self) -> bool {
588        if self.key_len != other.key_len {
589            return false;
590        }
591        ct::ct_eq_bytes(&self.buf[..self.key_len], &other.buf[..self.key_len])
592    }
593}
594impl<const KEY_LEN: usize> Eq for KeyMaterialInternal<KEY_LEN> {}
595
596/// Ordering is as follows:
597/// Zeroized < BytesLowEntropy < BytesFullEntropy < {Seed = MACKey = SymmetricCipherKey}
598impl PartialOrd for KeyType {
599    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
600        match self {
601            KeyType::Zeroized => match other {
602                KeyType::Zeroized => Some(Ordering::Equal),
603                _ => Some(Ordering::Less),
604            },
605            KeyType::BytesLowEntropy => match other {
606                KeyType::Zeroized => Some(Ordering::Greater),
607                KeyType::BytesLowEntropy => Some(Ordering::Equal),
608                _ => Some(Ordering::Less),
609            },
610            KeyType::BytesFullEntropy => match other {
611                KeyType::Zeroized | KeyType::BytesLowEntropy => Some(Ordering::Greater),
612                KeyType::BytesFullEntropy => Some(Ordering::Equal),
613                _ => Some(Ordering::Less),
614            },
615            KeyType::Seed | KeyType::MACKey | KeyType::SymmetricCipherKey => match other {
616                KeyType::Zeroized | KeyType::BytesLowEntropy | KeyType::BytesFullEntropy => {
617                    Some(Ordering::Greater)
618                }
619                KeyType::Seed | KeyType::MACKey | KeyType::SymmetricCipherKey => {
620                    Some(Ordering::Equal)
621                }
622            },
623        }
624    }
625}
626
627/// Block accidental logging of the internal key material buffer.
628impl<const KEY_LEN: usize> fmt::Display for KeyMaterialInternal<KEY_LEN> {
629    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630        write!(
631            f,
632            "KeyMaterial {{ len: {}, key_type: {:?}, security_strength: {:?} }}",
633            self.key_len, self.key_type, self.security_strength
634        )
635    }
636}
637
638/// Block accidental logging of the internal key material buffer.
639impl<const KEY_LEN: usize> fmt::Debug for KeyMaterialInternal<KEY_LEN> {
640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641        write!(
642            f,
643            "KeyMaterial {{ len: {}, key_type: {:?}, security_strength: {:?} }}",
644            self.key_len, self.key_type, self.security_strength
645        )
646    }
647}
648
649/// Zeroize the key material on drop.
650impl<const KEY_LEN: usize> Drop for KeyMaterialInternal<KEY_LEN> {
651    fn drop(&mut self) {
652        self.zeroize()
653    }
654}