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
38//! - **[`crypto_generichash`]**: Cryptographic hash functions (BLAKE2b)
39//! - **[`crypto_hash`]**: Traditional cryptographic hash functions (SHA-256, SHA-512)
40//! - **[`crypto_kdf`]**: Key derivation functions
41//! - **[`crypto_kx`]**: Key exchange
42//! - **[`crypto_pwhash`]**: Password hashing and key derivation
43//! - **[`crypto_scalarmult`]**: Elliptic curve operations
44//! - **[`crypto_secretbox`]**: Secret-key authenticated encryption
45//! - **[`crypto_secretstream`]**: Secret-key authenticated encryption for streams
46//! - **[`crypto_shorthash`]**: Short-input hash functions (SipHash)
47//! - **[`crypto_sign`]**: Public-key signatures
48//! - **[`crypto_stream`]**: Stream ciphers
49//! - **[`random`]**: Secure random number generation
50//! - **[`utils`]**: Utility functions
51//! - **[`version`]**: Library version information
52
53use thiserror::Error;
54
55/// Error type for libsodium operations
56#[derive(Error, Debug)]
57pub enum SodiumError {
58 /// Hex decoding failed
59 #[error("Invalid hexadecimal string")]
60 HexDecodingFailed,
61 /// Base64 decoding failed
62 #[error("Invalid Base64 string")]
63 Base64DecodingFailed,
64 /// Initialization of libsodium failed
65 #[error("libsodium initialization failed")]
66 InitializationError,
67
68 /// Invalid key provided (wrong size or format)
69 #[error("invalid key: {0}")]
70 InvalidKey(String),
71
72 /// Invalid nonce provided (wrong size or format)
73 #[error("invalid nonce: {0}")]
74 InvalidNonce(String),
75
76 /// Invalid input data provided
77 #[error("invalid input: {0}")]
78 InvalidInput(String),
79
80 /// Authentication failed during decryption
81 #[error("authentication failed")]
82 AuthenticationError,
83
84 /// Encryption operation failed
85 #[error("encryption failed: {0}")]
86 EncryptionError(String),
87
88 /// Decryption operation failed
89 #[error("decryption failed: {0}")]
90 DecryptionError(String),
91
92 /// Generic operation error
93 #[error("operation failed: {0}")]
94 OperationError(String),
95
96 /// Operation not supported on this platform or configuration
97 #[error("unsupported operation: {0}")]
98 UnsupportedOperation(String),
99}
100
101/// Result type for sodium operations
102pub type Result<T> = std::result::Result<T, SodiumError>;
103
104/// Ensures libsodium is initialized
105pub fn ensure_init() -> Result<()> {
106 unsafe {
107 if libsodium_sys::sodium_init() < 0 {
108 return Err(SodiumError::InitializationError);
109 }
110 }
111 Ok(())
112}
113
114pub mod crypto_aead;
115pub mod crypto_auth;
116pub mod crypto_box;
117pub mod crypto_core;
118pub mod crypto_generichash;
119pub mod crypto_hash;
120pub mod crypto_kdf;
121pub mod crypto_kx;
122pub mod crypto_onetimeauth;
123pub mod crypto_pwhash;
124pub mod crypto_scalarmult;
125pub mod crypto_secretbox;
126pub mod crypto_secretstream;
127pub mod crypto_shorthash;
128pub mod crypto_sign;
129pub mod crypto_stream;
130pub mod crypto_verify;
131pub mod random;
132pub mod utils;
133pub mod version;
134
135// No re-exports at the top level - users should import from specific modules
136
137// Initialize libsodium when the library is loaded
138#[ctor::ctor]
139fn initialize() {
140 if let Err(e) = ensure_init() {
141 panic!("Failed to initialize libsodium: {e}");
142 }
143}