Skip to main content

kyberlib/
error.rs

1// Copyright © 2024 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Error types.
5//!
6//! Every fallible public function in kyberlib returns
7//! [`Result<T, KyberLibError>`]. The enum is `#[non_exhaustive]` so
8//! future backend-specific variants (the planned `fips` and `verified`
9//! features) can be added without a major-version bump.
10
11/// Error types for the failure modes in kyberlib.
12///
13/// Marked `#[non_exhaustive]` (since v0.0.7, #130) so future variants
14/// — e.g. backend-specific errors from the planned `fips` (#170) and
15/// `verified` (#171) features — can be added without a major-version
16/// bump.
17#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
18#[non_exhaustive]
19pub enum KyberLibError {
20    /// One or more inputs to a function are incorrectly sized. A likely cause of this is
21    /// two parties using different security levels while trying to negotiate a key exchange.
22    InvalidInput,
23
24    /// Error when generating keys
25    InvalidKey,
26
27    /// The length of the input buffer is invalid.
28    InvalidLength,
29
30    /// The ciphertext was unable to be authenticated. The shared secret was not decapsulated.
31    Decapsulation,
32
33    /// Error trying to fill random bytes (i.e., external (hardware) RNG modules can fail).
34    RandomBytesGeneration,
35
36    /// The `fips` feature is on but the AWS-LC module is not running in
37    /// FIPS mode (see `kyberlib::fips::fips_mode`).
38    FipsModeUnavailable,
39}
40
41impl core::fmt::Display for KyberLibError {
42    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
43        match self {
44            KyberLibError::InvalidInput => write!(f, "Function input is of incorrect length"),
45            KyberLibError::Decapsulation => write!(
46                f,
47                "Decapsulation Failure, unable to obtain shared secret from ciphertext"
48            ),
49            KyberLibError::RandomBytesGeneration => {
50                write!(f, "Random bytes generation function failed")
51            }
52            KyberLibError::InvalidKey => {
53                write!(f, "The secret and public key given does not match.")
54            },
55            KyberLibError::InvalidLength => {
56                write!(f, "The length of the input buffer is invalid.")
57            }
58            KyberLibError::FipsModeUnavailable => {
59                write!(f, "The AWS-LC FIPS module is not in FIPS mode.")
60            }
61        }
62    }
63}
64
65#[cfg(feature = "std")]
66impl std::error::Error for KyberLibError {}