libsodium_rs/
lib.rs

1//! # Rust bindings for libsodium
2//!
3//! This crate provides safe, ergonomic Rust bindings for the libsodium cryptographic library.
4//! It offers a comprehensive set of cryptographic primitives with a focus on usability, security,
5//! and performance.
6//!
7//! ## Features
8//!
9//! - **Complete Coverage**: Implements the entire libsodium API in Rust
10//! - **Memory Safety**: Ensures secure memory handling with automatic clearing of sensitive data
11//! - **Type Safety**: Leverages Rust's type system to prevent misuse of cryptographic primitives
12//! - **Flexible APIs**: Uses `AsRef` trait for parameters, allowing for more ergonomic function calls
13//! - **Extensive Testing**: Comprehensive test suite covering all functionality
14//! - **Minimal Dependencies**: Uses only a small set of carefully selected dependencies beyond libsodium itself
15//!
16//! ## Getting Started
17//!
18//! Before using any cryptographic functions, you must initialize the library:
19//!
20//! ```
21//! use libsodium_rs::ensure_init;
22//!
23//! fn main() -> Result<(), Box<dyn std::error::Error>> {
24//!     // Initialize libsodium
25//!     ensure_init()?;
26//!
27//!     // Now you can use the cryptographic functions
28//!     Ok(())
29//! }
30//! ```
31//!
32//! ## Available Modules
33//!
34//! - **[`crypto_aead`]**: Authenticated Encryption with Associated Data (AEAD)
35//! - **[`crypto_auth`]**: Secret-key message authentication
36//! - **[`crypto_box`]**: Public-key authenticated encryption
37//! - **[`crypto_core`]**: Core cryptographic operations (Ed25519, Ristretto255, Keccak1600)
38//! - **[`crypto_generichash`]**: Cryptographic hash functions (BLAKE2b)
39//! - **[`crypto_hash`]**: Traditional cryptographic hash functions (SHA-256, SHA-512)
40//! - **[`crypto_ipcrypt`]**: IP address encryption for privacy-preserving storage
41//! - **[`crypto_kdf`]**: Key derivation functions
42//! - **[`crypto_kx`]**: Key exchange
43//! - **[`crypto_pwhash`]**: Password hashing and key derivation
44//! - **[`crypto_scalarmult`]**: Elliptic curve operations
45//! - **[`crypto_secretbox`]**: Secret-key authenticated encryption
46//! - **[`crypto_secretstream`]**: Secret-key authenticated encryption for streams
47//! - **[`crypto_shorthash`]**: Short-input hash functions (SipHash)
48//! - **[`crypto_sign`]**: Public-key signatures
49//! - **[`crypto_stream`]**: Stream ciphers
50//! - **[`crypto_xof`]**: Extendable Output Functions (SHAKE, TurboSHAKE)
51//! - **[`random`]**: Secure random number generation
52//! - **[`utils`]**: Utility functions
53//! - **[`version`]**: Library version information
54
55use thiserror::Error;
56
57/// Error type for libsodium operations
58#[derive(Error, Debug)]
59pub enum SodiumError {
60    /// Hex decoding failed
61    #[error("Invalid hexadecimal string")]
62    HexDecodingFailed,
63    /// Base64 decoding failed
64    #[error("Invalid Base64 string")]
65    Base64DecodingFailed,
66    /// Initialization of libsodium failed
67    #[error("libsodium initialization failed")]
68    InitializationError,
69
70    /// Invalid key provided (wrong size or format)
71    #[error("invalid key: {0}")]
72    InvalidKey(String),
73
74    /// Invalid nonce provided (wrong size or format)
75    #[error("invalid nonce: {0}")]
76    InvalidNonce(String),
77
78    /// Invalid input data provided
79    #[error("invalid input: {0}")]
80    InvalidInput(String),
81
82    /// Authentication failed during decryption
83    #[error("authentication failed")]
84    AuthenticationError,
85
86    /// Encryption operation failed
87    #[error("encryption failed: {0}")]
88    EncryptionError(String),
89
90    /// Decryption operation failed
91    #[error("decryption failed: {0}")]
92    DecryptionError(String),
93
94    /// Generic operation error
95    #[error("operation failed: {0}")]
96    OperationError(String),
97
98    /// Operation not supported on this platform or configuration
99    #[error("unsupported operation: {0}")]
100    UnsupportedOperation(String),
101}
102
103/// Result type for sodium operations
104pub type Result<T> = std::result::Result<T, SodiumError>;
105
106/// Ensures libsodium is initialized
107pub fn ensure_init() -> Result<()> {
108    unsafe {
109        if libsodium_sys::sodium_init() < 0 {
110            return Err(SodiumError::InitializationError);
111        }
112    }
113    Ok(())
114}
115
116pub mod crypto_aead;
117pub mod crypto_auth;
118pub mod crypto_box;
119pub mod crypto_core;
120pub mod crypto_generichash;
121pub mod crypto_hash;
122pub mod crypto_ipcrypt;
123pub mod crypto_kdf;
124pub mod crypto_kx;
125pub mod crypto_onetimeauth;
126pub mod crypto_pwhash;
127pub mod crypto_scalarmult;
128pub mod crypto_secretbox;
129pub mod crypto_secretstream;
130pub mod crypto_shorthash;
131pub mod crypto_sign;
132pub mod crypto_stream;
133pub mod crypto_verify;
134pub mod crypto_xof;
135pub mod random;
136pub mod utils;
137pub mod version;
138
139// No re-exports at the top level - users should import from specific modules
140
141// Initialize libsodium when the library is loaded
142#[ctor::ctor]
143fn initialize() {
144    if let Err(e) = ensure_init() {
145        panic!("Failed to initialize libsodium: {e}");
146    }
147}