Skip to main content

gmssl_rs/
error.rs

1// GmSSL error types and helper functions.
2
3use std::fmt;
4
5/// Errors that can occur when using the GmSSL library.
6#[derive(Debug)]
7pub enum GmsslError {
8    /// The underlying C library returned a failure.
9    LibraryError(&'static str),
10    /// An invalid key was provided (wrong size, bad format).
11    InvalidKey(&'static str),
12    /// Invalid input parameters.
13    InvalidInput(&'static str),
14    /// An I/O error occurred (file not found, permission denied, etc.).
15    IoError(std::io::Error),
16    /// Signature verification failed (the signature does not match).
17    VerificationFailed,
18    /// Decryption failed (bad padding, wrong key, tag mismatch).
19    DecryptionFailed,
20}
21
22impl fmt::Display for GmsslError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            GmsslError::LibraryError(ctx) => write!(f, "GmSSL library error: {}", ctx),
26            GmsslError::InvalidKey(msg) => write!(f, "Invalid key: {}", msg),
27            GmsslError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
28            GmsslError::IoError(e) => write!(f, "I/O error: {}", e),
29            GmsslError::VerificationFailed => write!(f, "Verification failed"),
30            GmsslError::DecryptionFailed => write!(f, "Decryption failed"),
31        }
32    }
33}
34
35impl std::error::Error for GmsslError {
36    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
37        match self {
38            GmsslError::IoError(e) => Some(e),
39            _ => None,
40        }
41    }
42}
43
44impl From<std::io::Error> for GmsslError {
45    fn from(e: std::io::Error) -> Self {
46        GmsslError::IoError(e)
47    }
48}
49
50/// Check that a C function returned 1 (success). Returns `Ok(())` or an error.
51#[inline]
52pub(crate) fn ok_or_library_error(ret: i32, context: &'static str) -> Result<(), GmsslError> {
53    if ret == 1 {
54        Ok(())
55    } else {
56        Err(GmsslError::LibraryError(context))
57    }
58}
59
60/// Check a C verify function result: 1=valid, anything else=invalid.
61///
62/// Note: GmSSL verifiers sometimes return -1 (not 0) for invalid
63/// signatures, notably sm2_verify_finish and sm9_verify_finish.
64/// We treat all non-1 results as "verification failed" rather than
65/// "library error" to match this behavior.
66#[inline]
67pub(crate) fn verify_result(ret: i32, _context: &'static str) -> Result<bool, GmsslError> {
68    Ok(ret == 1)
69}