Skip to main content

lib_q_hqc/
error.rs

1//! HQC Error Types
2//!
3//! This module defines error types for HQC operations following libQ patterns.
4
5use core::fmt;
6
7#[cfg(feature = "alloc")]
8extern crate alloc;
9#[cfg(feature = "alloc")]
10use alloc::string::String;
11
12/// HQC-specific error types
13///
14/// This enum represents all possible errors that can occur during HQC operations.
15/// Each variant includes context about when the error occurs and how to resolve it.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum HqcError {
18    /// Invalid key size
19    ///
20    /// **When it occurs:** A key (public or secret) has an incorrect size for the HQC parameter set.
21    /// **Cause:** The key data provided doesn't match the expected size for the algorithm variant (HQC-128, HQC-192, or HQC-256).
22    /// **Resolution:** Ensure the key size matches the parameter set: HQC-128 (2249 bytes public, 2289 bytes secret),
23    /// HQC-192 (4522 bytes public, 4562 bytes secret), or HQC-256 (7245 bytes public, 7285 bytes secret).
24    InvalidKeySize { expected: usize, actual: usize },
25
26    /// Invalid ciphertext size
27    ///
28    /// **When it occurs:** A ciphertext has an incorrect size for the HQC parameter set.
29    /// **Cause:** The ciphertext data doesn't match the expected size for decapsulation.
30    /// **Resolution:** Ensure the ciphertext was generated for the same HQC parameter set and hasn't been corrupted.
31    InvalidCiphertextSize { expected: usize, actual: usize },
32
33    /// Invalid public key size
34    ///
35    /// **When it occurs:** A public key has an incorrect size.
36    /// **Cause:** The public key data doesn't match the expected size for the HQC parameter set.
37    /// **Resolution:** Verify the public key was generated or serialized correctly for the intended parameter set.
38    InvalidPublicKeySize { expected: usize, actual: usize },
39
40    /// Invalid secret key size
41    ///
42    /// **When it occurs:** A secret key has an incorrect size.
43    /// **Cause:** The secret key data doesn't match the expected size for the HQC parameter set.
44    /// **Resolution:** Verify the secret key was generated or deserialized correctly for the intended parameter set.
45    InvalidSecretKeySize { expected: usize, actual: usize },
46
47    /// Decryption failed
48    ///
49    /// **When it occurs:** Decapsulation fails to recover the shared secret.
50    /// **Cause:** The ciphertext may be corrupted, the secret key may be incorrect, or the ciphertext was generated with a different public key.
51    /// **Resolution:** Verify the ciphertext and secret key are valid and correspond to each other.
52    DecryptionFailed,
53
54    /// Invalid size
55    ///
56    /// **When it occurs:** A size parameter is invalid or out of bounds.
57    /// **Cause:** A size value doesn't meet the requirements for the operation.
58    /// **Resolution:** Check that all size parameters are within valid ranges for the HQC parameter set.
59    InvalidSize,
60
61    /// Encryption failed
62    ///
63    /// **When it occurs:** Encapsulation fails to generate a valid ciphertext.
64    /// **Cause:** Random number generation may have failed, or internal computation encountered an error.
65    /// **Resolution:** Ensure a secure random number generator is available and functioning correctly.
66    EncryptionFailed,
67
68    /// Key generation failed
69    ///
70    /// **When it occurs:** Key pair generation fails.
71    /// **Cause:** Random number generation may have failed, or internal computation encountered an error.
72    /// **Resolution:** Ensure a secure random number generator is available and functioning correctly.
73    KeyGenerationFailed,
74
75    /// Random number generation failed
76    ///
77    /// **When it occurs:** The random number generator fails to produce random bytes.
78    /// **Cause:** The underlying RNG implementation encountered an error or is unavailable.
79    /// **Resolution:** Check RNG initialization and ensure a secure random source is available.
80    RandomGenerationFailed,
81
82    /// Internal error
83    ///
84    /// **When it occurs:** An unexpected internal error occurs during HQC operations.
85    /// **Cause:** This typically indicates a bug in the implementation or corrupted internal state.
86    /// **Resolution:** Report this error as it may indicate a software bug. Check inputs and system state.
87    InternalError,
88
89    /// Not implemented
90    ///
91    /// **When it occurs:** A requested feature or operation is not yet implemented.
92    /// **Cause:** The operation is not available in the current implementation.
93    /// **Resolution:** Check if an alternative approach is available, or wait for the feature to be implemented.
94    NotImplemented,
95
96    /// Invalid parameter
97    ///
98    /// **When it occurs:** A parameter value is invalid for the operation.
99    /// **Cause:** A parameter doesn't meet the requirements or constraints for the HQC operation.
100    /// **Resolution:** Verify all parameters are within valid ranges and meet the algorithm requirements.
101    InvalidParameter,
102
103    /// Memory allocation failed
104    ///
105    /// **When it occurs:** Dynamic memory allocation fails during an operation.
106    /// **Cause:** Insufficient memory is available, or allocation is not supported in the current environment.
107    /// **Resolution:** Ensure sufficient memory is available, or use a no_std-compatible configuration.
108    AllocationFailed,
109
110    /// Hash function error
111    ///
112    /// **When it occurs:** A hash function operation fails.
113    /// **Cause:** The underlying hash implementation encountered an error.
114    /// **Resolution:** Check that the hash function implementation is properly initialized and functioning.
115    HashError,
116
117    /// BCH code error
118    ///
119    /// **When it occurs:** BCH (Bose-Chaudhuri-Hocquenghem) code operations fail.
120    /// **Cause:** Error correction code computation encountered an error, possibly due to corrupted data.
121    /// **Resolution:** Verify input data integrity and that error correction parameters are correct.
122    BchError,
123
124    /// Polynomial operation error
125    ///
126    /// **When it occurs:** Polynomial arithmetic operations fail.
127    /// **Cause:** Polynomial computation encountered an error, possibly due to invalid coefficients or degree.
128    /// **Resolution:** Verify polynomial inputs are valid and within expected ranges.
129    PolynomialError,
130
131    /// Encoding error
132    ///
133    /// **When it occurs:** Encoding operations fail.
134    /// **Cause:** Data encoding encountered an error, possibly due to invalid input format.
135    /// **Resolution:** Verify input data format and encoding parameters are correct.
136    EncodingError,
137
138    /// Verification error
139    ///
140    /// **When it occurs:** Verification operations fail.
141    /// **Cause:** Data verification failed, indicating the data may be corrupted or invalid.
142    /// **Resolution:** Verify input data integrity and that verification parameters are correct.
143    VerificationError,
144
145    /// Invalid weight
146    ///
147    /// **When it occurs:** A polynomial weight is invalid for the operation.
148    /// **Cause:** The weight parameter doesn't meet the requirements for the HQC parameter set.
149    /// **Resolution:** Ensure the weight is within valid ranges: HQC-128 (66), HQC-192 (103), or HQC-256 (134).
150    InvalidWeight,
151
152    /// Allocation required (for no_std environments)
153    ///
154    /// **When it occurs:** An operation requires dynamic allocation but the `alloc` feature is not enabled.
155    /// **Cause:** The operation needs heap allocation but the crate is compiled in `no_std` mode without `alloc`.
156    /// **Resolution:** Enable the `alloc` feature or use an alternative approach that doesn't require allocation.
157    AllocRequired,
158}
159
160impl fmt::Display for HqcError {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match self {
163            HqcError::InvalidKeySize { expected, actual } => {
164                write!(f, "Invalid key size: expected {}, got {}", expected, actual)
165            }
166            HqcError::InvalidCiphertextSize { expected, actual } => {
167                write!(
168                    f,
169                    "Invalid ciphertext size: expected {}, got {}",
170                    expected, actual
171                )
172            }
173            HqcError::InvalidPublicKeySize { expected, actual } => {
174                write!(
175                    f,
176                    "Invalid public key size: expected {}, got {}",
177                    expected, actual
178                )
179            }
180            HqcError::InvalidSecretKeySize { expected, actual } => {
181                write!(
182                    f,
183                    "Invalid secret key size: expected {}, got {}",
184                    expected, actual
185                )
186            }
187            HqcError::DecryptionFailed => write!(f, "Decryption failed"),
188            HqcError::InvalidSize => write!(f, "Invalid size"),
189            HqcError::EncryptionFailed => write!(f, "Encryption failed"),
190            HqcError::KeyGenerationFailed => write!(f, "Key generation failed"),
191            HqcError::RandomGenerationFailed => write!(f, "Random number generation failed"),
192            HqcError::InternalError => write!(f, "Internal error"),
193            HqcError::NotImplemented => write!(f, "Not implemented"),
194            HqcError::InvalidParameter => write!(f, "Invalid parameter"),
195            HqcError::AllocationFailed => write!(f, "Memory allocation failed"),
196            HqcError::HashError => write!(f, "Hash function error"),
197            HqcError::BchError => write!(f, "BCH code error"),
198            HqcError::PolynomialError => write!(f, "Polynomial operation error"),
199            HqcError::EncodingError => write!(f, "Encoding error"),
200            HqcError::VerificationError => write!(f, "Verification error"),
201            HqcError::InvalidWeight => write!(f, "Invalid weight"),
202            HqcError::AllocRequired => write!(f, "Allocation required (no_std environment)"),
203        }
204    }
205}
206
207#[cfg(feature = "std")]
208impl std::error::Error for HqcError {}
209
210impl From<HqcError> for lib_q_core::Error {
211    fn from(err: HqcError) -> Self {
212        match err {
213            HqcError::InvalidKeySize { expected, actual } => {
214                lib_q_core::Error::InvalidKeySize { expected, actual }
215            }
216            HqcError::InvalidCiphertextSize { expected, actual } => {
217                lib_q_core::Error::InvalidCiphertextSize { expected, actual }
218            }
219            HqcError::InvalidPublicKeySize { expected, actual } => {
220                // Map to InvalidKeySize since InvalidPublicKeySize doesn't exist in lib-q-core
221                lib_q_core::Error::InvalidKeySize { expected, actual }
222            }
223            HqcError::InvalidSecretKeySize { expected, actual } => {
224                // Map to InvalidKeySize since InvalidSecretKeySize doesn't exist in lib-q-core
225                lib_q_core::Error::InvalidKeySize { expected, actual }
226            }
227            HqcError::DecryptionFailed => {
228                #[cfg(feature = "alloc")]
229                {
230                    lib_q_core::Error::DecryptionFailed {
231                        operation: String::from("HQC decapsulation"),
232                    }
233                }
234                #[cfg(not(feature = "alloc"))]
235                {
236                    lib_q_core::Error::DecryptionFailed {
237                        operation: "HQC decapsulation".into(),
238                    }
239                }
240            }
241            HqcError::InvalidSize => {
242                #[cfg(feature = "alloc")]
243                {
244                    lib_q_core::Error::InternalError {
245                        operation: String::from("HQC operation"),
246                        details: String::from("Invalid size parameter"),
247                    }
248                }
249                #[cfg(not(feature = "alloc"))]
250                {
251                    lib_q_core::Error::InternalError {
252                        operation: "HQC operation".into(),
253                        details: "Invalid size parameter".into(),
254                    }
255                }
256            }
257            HqcError::EncryptionFailed => {
258                #[cfg(feature = "alloc")]
259                {
260                    lib_q_core::Error::EncryptionFailed {
261                        operation: String::from("HQC encapsulation"),
262                    }
263                }
264                #[cfg(not(feature = "alloc"))]
265                {
266                    lib_q_core::Error::EncryptionFailed {
267                        operation: "HQC encapsulation".into(),
268                    }
269                }
270            }
271            HqcError::KeyGenerationFailed => {
272                #[cfg(feature = "alloc")]
273                {
274                    lib_q_core::Error::KeyGenerationFailed {
275                        operation: String::from("HQC key generation"),
276                    }
277                }
278                #[cfg(not(feature = "alloc"))]
279                {
280                    lib_q_core::Error::KeyGenerationFailed {
281                        operation: "HQC key generation".into(),
282                    }
283                }
284            }
285            HqcError::RandomGenerationFailed => {
286                #[cfg(feature = "alloc")]
287                {
288                    lib_q_core::Error::RandomGenerationFailed {
289                        operation: String::from("HQC random generation"),
290                    }
291                }
292                #[cfg(not(feature = "alloc"))]
293                {
294                    lib_q_core::Error::RandomGenerationFailed {
295                        operation: "HQC random generation".into(),
296                    }
297                }
298            }
299            HqcError::InternalError => {
300                #[cfg(feature = "alloc")]
301                {
302                    lib_q_core::Error::InternalError {
303                        operation: String::from("HQC operation"),
304                        details: String::from("Internal error"),
305                    }
306                }
307                #[cfg(not(feature = "alloc"))]
308                {
309                    lib_q_core::Error::InternalError {
310                        operation: "HQC operation".into(),
311                        details: "Internal error".into(),
312                    }
313                }
314            }
315            HqcError::NotImplemented => {
316                #[cfg(feature = "alloc")]
317                {
318                    lib_q_core::Error::NotImplemented {
319                        feature: String::from("HQC feature"),
320                    }
321                }
322                #[cfg(not(feature = "alloc"))]
323                {
324                    lib_q_core::Error::NotImplemented {
325                        feature: "HQC feature".into(),
326                    }
327                }
328            }
329            HqcError::InvalidParameter => {
330                #[cfg(feature = "alloc")]
331                {
332                    lib_q_core::Error::InternalError {
333                        operation: String::from("HQC operation"),
334                        details: String::from("Invalid parameter"),
335                    }
336                }
337                #[cfg(not(feature = "alloc"))]
338                {
339                    lib_q_core::Error::InternalError {
340                        operation: "HQC operation".into(),
341                        details: "Invalid parameter".into(),
342                    }
343                }
344            }
345            HqcError::AllocationFailed => {
346                #[cfg(feature = "alloc")]
347                {
348                    lib_q_core::Error::MemoryAllocationFailed {
349                        operation: String::from("HQC operation"),
350                    }
351                }
352                #[cfg(not(feature = "alloc"))]
353                {
354                    lib_q_core::Error::MemoryAllocationFailed {
355                        operation: "HQC operation".into(),
356                    }
357                }
358            }
359            HqcError::HashError => {
360                #[cfg(feature = "alloc")]
361                {
362                    lib_q_core::Error::InternalError {
363                        operation: String::from("HQC hash operation"),
364                        details: String::from("Hash computation failed"),
365                    }
366                }
367                #[cfg(not(feature = "alloc"))]
368                {
369                    lib_q_core::Error::InternalError {
370                        operation: "HQC hash operation".into(),
371                        details: "Hash computation failed".into(),
372                    }
373                }
374            }
375            HqcError::BchError => {
376                #[cfg(feature = "alloc")]
377                {
378                    lib_q_core::Error::InternalError {
379                        operation: String::from("HQC BCH operation"),
380                        details: String::from("BCH code error"),
381                    }
382                }
383                #[cfg(not(feature = "alloc"))]
384                {
385                    lib_q_core::Error::InternalError {
386                        operation: "HQC BCH operation".into(),
387                        details: "BCH code error".into(),
388                    }
389                }
390            }
391            HqcError::PolynomialError => {
392                #[cfg(feature = "alloc")]
393                {
394                    lib_q_core::Error::InternalError {
395                        operation: String::from("HQC polynomial operation"),
396                        details: String::from("Polynomial computation error"),
397                    }
398                }
399                #[cfg(not(feature = "alloc"))]
400                {
401                    lib_q_core::Error::InternalError {
402                        operation: "HQC polynomial operation".into(),
403                        details: "Polynomial computation error".into(),
404                    }
405                }
406            }
407            HqcError::EncodingError => {
408                #[cfg(feature = "alloc")]
409                {
410                    lib_q_core::Error::InternalError {
411                        operation: String::from("HQC encoding operation"),
412                        details: String::from("Encoding computation error"),
413                    }
414                }
415                #[cfg(not(feature = "alloc"))]
416                {
417                    lib_q_core::Error::InternalError {
418                        operation: "HQC encoding operation".into(),
419                        details: "Encoding computation error".into(),
420                    }
421                }
422            }
423            HqcError::VerificationError => {
424                #[cfg(feature = "alloc")]
425                {
426                    lib_q_core::Error::InternalError {
427                        operation: String::from("HQC verification operation"),
428                        details: String::from("Verification computation error"),
429                    }
430                }
431                #[cfg(not(feature = "alloc"))]
432                {
433                    lib_q_core::Error::InternalError {
434                        operation: "HQC verification operation".into(),
435                        details: "Verification computation error".into(),
436                    }
437                }
438            }
439            HqcError::InvalidWeight => {
440                #[cfg(feature = "alloc")]
441                {
442                    lib_q_core::Error::InternalError {
443                        operation: String::from("HQC weight validation"),
444                        details: String::from("Invalid polynomial weight"),
445                    }
446                }
447                #[cfg(not(feature = "alloc"))]
448                {
449                    lib_q_core::Error::InternalError {
450                        operation: "HQC weight validation".into(),
451                        details: "Invalid polynomial weight".into(),
452                    }
453                }
454            }
455            HqcError::AllocRequired => {
456                #[cfg(feature = "alloc")]
457                {
458                    lib_q_core::Error::InternalError {
459                        operation: String::from("HQC operation"),
460                        details: String::from("Allocation required but not available"),
461                    }
462                }
463                #[cfg(not(feature = "alloc"))]
464                {
465                    lib_q_core::Error::InternalError {
466                        operation: "HQC operation".into(),
467                        details: "Allocation required but not available".into(),
468                    }
469                }
470            }
471        }
472    }
473}
474
475impl From<lib_q_core::Error> for HqcError {
476    fn from(err: lib_q_core::Error) -> Self {
477        match err {
478            lib_q_core::Error::InvalidKeySize { expected, actual } => {
479                HqcError::InvalidKeySize { expected, actual }
480            }
481            lib_q_core::Error::InvalidCiphertextSize { expected, actual } => {
482                HqcError::InvalidCiphertextSize { expected, actual }
483            }
484            // Note: InvalidPublicKeySize and InvalidSecretKeySize don't exist in lib-q-core
485            // They are mapped to InvalidKeySize in the forward direction
486            lib_q_core::Error::DecryptionFailed { .. } => HqcError::DecryptionFailed,
487            lib_q_core::Error::EncryptionFailed { .. } => HqcError::EncryptionFailed,
488            lib_q_core::Error::KeyGenerationFailed { .. } => HqcError::KeyGenerationFailed,
489            lib_q_core::Error::RandomGenerationFailed { .. } => HqcError::RandomGenerationFailed,
490            lib_q_core::Error::InternalError { .. } => HqcError::InternalError,
491            lib_q_core::Error::NotImplemented { .. } => HqcError::NotImplemented,
492            lib_q_core::Error::MemoryAllocationFailed { .. } => HqcError::AllocationFailed,
493            _ => HqcError::InternalError, // Map unknown errors to internal error
494        }
495    }
496}