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