1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! # Secret-key Authenticated Encryption
//!
//! This module provides functions for authenticated encryption using a secret key.
//! It combines encryption and authentication to provide confidentiality, integrity,
//! and authenticity of data.
//!
//! ## Overview
//!
//! Secret-key authenticated encryption (also known as symmetric authenticated encryption)
//! allows you to encrypt data such that:
//!
//! 1. The data remains confidential (encryption)
//! 2. The data cannot be modified without detection (authentication)
//! 3. The data can only be decrypted by someone with the same secret key
//!
//! This module uses XSalsa20 for encryption and Poly1305 for authentication by default,
//! combined in an encrypt-then-MAC construction. The `xchacha20poly1305` submodule
//! provides an alternative implementation using XChaCha20 and Poly1305.
//!
//! ## Features
//!
//! - **High security**: Uses modern, secure cryptographic primitives
//! - **Authenticated encryption**: Protects against tampering and forgery
//! - **Ease of use**: Simple API with sensible defaults
//! - **Nonce-based**: Requires a unique nonce for each encryption
//! - **Zero-copy**: Minimizes memory allocations where possible
//!
//! ## Basic Usage
//!
//! ```rust
//! use libsodium_rs as sodium;
//! use sodium::crypto_secretbox;
//! use sodium::ensure_init;
//!
//! // Initialize libsodium
//! ensure_init().expect("Failed to initialize libsodium");
//!
//! // Generate a random secret key
//! let key = crypto_secretbox::Key::generate();
//!
//! // Generate a random nonce (must be unique for each message with the same key)
//! let nonce = crypto_secretbox::Nonce::generate();
//!
//! // Message to encrypt
//! let message = b"Hello, world!";
//!
//! // Encrypt the message
//! let ciphertext = crypto_secretbox::seal(message, &nonce, &key);
//!
//! // Decrypt the message
//! let decrypted = crypto_secretbox::open(&ciphertext, &nonce, &key).unwrap();
//! assert_eq!(decrypted, message);
//! ```
//!
//! ## Nonce Management
//!
//! Proper nonce management is critical for security. A nonce must NEVER be reused with the same key.
//! Options for generating nonces include:
//!
//! 1. **Random nonces**: Use `random::bytes(NONCEBYTES)` for each message
//! 2. **Counter-based nonces**: Start with a random nonce and increment for each message
//! 3. **Timestamp-based nonces**: Combine a timestamp with a random value
//!
//! For long-term security, consider using the XChaCha20-Poly1305 variant which has a larger
//! nonce space (192 bits) and is more suitable for random nonce generation:
//!
//! ```rust
//! use libsodium_rs as sodium;
//! use sodium::crypto_secretbox::xchacha20poly1305;
//! use sodium::ensure_init;
//! use sodium::random;
//!
//! // Initialize libsodium
//! ensure_init().expect("Failed to initialize libsodium");
//!
//! // Generate a random secret key
//! let key = xchacha20poly1305::Key::generate();
//!
//! // Generate a random nonce
//! let nonce = xchacha20poly1305::Nonce::generate();
//!
//! // Encrypt and decrypt
//! let message = b"Hello, world!";
//! let ciphertext = xchacha20poly1305::encrypt(message, &nonce, &key);
//! let decrypted = xchacha20poly1305::decrypt(&ciphertext, &nonce, &key).unwrap();
//! assert_eq!(decrypted, message);
//! ```
//!
//! ## Security Considerations
//!
//! - **Never reuse a nonce with the same key**: This would completely compromise security
//! - **Store keys securely**: The secret key must be kept confidential
//! - **Verify decryption**: Always check for errors when decrypting
//! - **Consider key derivation**: For user-supplied passwords, use `crypto_pwhash` to derive keys
//! - **Prefer XChaCha20-Poly1305** for most new applications due to its larger nonce space
use crate::;
use libsodium_sys;
use ;
/// Number of bytes in a secret key (32)
///
/// This is the size of the secret key used for XSalsa20-Poly1305 encryption.
/// The key should be randomly generated using `Key::generate()` or derived
/// from a password using the `crypto_pwhash` module.
pub const KEYBYTES: usize = crypto_secretbox_KEYBYTES as usize;
/// Number of bytes in a nonce (24)
///
/// This is the size of the nonce (number used once) for XSalsa20-Poly1305 encryption.
/// The nonce must be unique for each message encrypted with the same key.
/// With a 24-byte nonce, random nonces can be safely used, but care must still
/// be taken to avoid nonce reuse in distributed systems.
///
/// Use the `Nonce::generate()` method to create a secure random nonce.
pub const NONCEBYTES: usize = crypto_secretbox_NONCEBYTES as usize;
/// A nonce (number used once) for secretbox operations
///
/// This struct represents a nonce for use with the XSalsa20-Poly1305 encryption algorithm.
/// A nonce must be unique for each message encrypted with the same key to maintain security.
;
/// Number of bytes in a MAC (message authentication code) (16)
///
/// This is the size of the authentication tag added to each encrypted message.
/// The MAC ensures the integrity and authenticity of the ciphertext.
/// It is automatically handled by the `seal` and `open` functions.
pub const MACBYTES: usize = crypto_secretbox_MACBYTES as usize;
/// A secret key for authenticated symmetric encryption
///
/// This struct represents a secret key used for XSalsa20-Poly1305 authenticated encryption.
/// The key should be kept confidential and should be randomly generated or derived
/// from a strong password.
///
/// ## Size
///
/// A secret key is always exactly `KEYBYTES` (32) bytes.
///
/// ## Security Considerations
///
/// - The key should be kept confidential at all times
/// - Each key should be used with unique nonces
/// - For long-term storage, consider encrypting the key itself
/// - If derived from a password, use the `crypto_pwhash` module with appropriate parameters
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_secretbox;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = crypto_secretbox::Key::generate();
///
/// // Create a key from existing bytes (e.g., from secure storage)
/// let key_bytes = [0x42; crypto_secretbox::KEYBYTES]; // Example bytes
/// let key_from_bytes = crypto_secretbox::Key::from_bytes(&key_bytes).unwrap();
/// ```
;
/// Encrypt a message using authenticated symmetric encryption (XSalsa20-Poly1305)
///
/// This function encrypts a message using the XSalsa20 stream cipher and authenticates
/// it using the Poly1305 message authentication code. The resulting ciphertext includes
/// both the encrypted message and the authentication tag.
///
/// ## Algorithm Details
///
/// The encryption process works as follows:
/// 1. The message is encrypted using XSalsa20 with the provided key and nonce
/// 2. A Poly1305 authentication tag is computed over the ciphertext
/// 3. The authentication tag is prepended to the ciphertext
///
/// ## Security Considerations
///
/// - The nonce must NEVER be reused with the same key
/// - For maximum security, generate a new random nonce for each message
/// - The ciphertext will be `MACBYTES` (16) bytes longer than the original message
///
/// ## Arguments
///
/// * `message` - The plaintext message to encrypt
/// * `nonce` - A unique nonce
/// * `key` - The secret key to encrypt with
///
/// ## Returns
///
/// * `Vec<u8>` - The authenticated ciphertext
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_secretbox;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a key and nonce
/// let key = crypto_secretbox::Key::generate();
/// let nonce = crypto_secretbox::Nonce::generate(); // A secure random nonce
///
/// // Encrypt a message
/// let message = b"Hello, world!";
/// let ciphertext = crypto_secretbox::seal(message, &nonce, &key);
///
/// // The ciphertext is longer than the message due to the authentication tag
/// assert_eq!(ciphertext.len(), message.len() + crypto_secretbox::MACBYTES);
/// ```
/// Decrypt and verify a message using authenticated symmetric encryption (XSalsa20-Poly1305)
///
/// This function verifies the authentication tag and decrypts the ciphertext
/// that was created using the `seal` function. It ensures that the message
/// has not been tampered with and was encrypted with the correct key.
///
/// ## Algorithm Details
///
/// The decryption process works as follows:
/// 1. The Poly1305 authentication tag is verified
/// 2. If verification succeeds, the message is decrypted using XSalsa20
/// 3. If verification fails, an error is returned and no decryption is performed
///
/// ## Security Considerations
///
/// - Always check the return value for errors, which indicate authentication failure
/// - Use the same nonce that was used for encryption
/// - The ciphertext must be at least `MACBYTES` (16) bytes long
///
/// ## Arguments
///
/// * `ciphertext` - The authenticated ciphertext to decrypt
/// * `nonce` - The same nonce used for encryption
/// * `key` - The secret key to decrypt with
///
/// ## Returns
///
/// * `Result<Vec<u8>>` - The decrypted message or an error
///
/// ## Errors
///
/// Returns an error if:
/// - The nonce is not exactly `NONCEBYTES` bytes long
/// - The ciphertext is too short (less than `MACBYTES` bytes)
/// - Authentication fails (wrong key, tampered ciphertext, or wrong nonce)
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_secretbox;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a key and nonce
/// let key = crypto_secretbox::Key::generate();
/// let nonce = crypto_secretbox::Nonce::generate();
///
/// // Encrypt a message
/// let message = b"Hello, world!";
/// let ciphertext = crypto_secretbox::seal(message, &nonce, &key);
///
/// // Decrypt the message
/// let decrypted = crypto_secretbox::open(&ciphertext, &nonce, &key).unwrap();
/// assert_eq!(decrypted, message);
///
/// // Attempting to decrypt with the wrong key will fail
/// let wrong_key = crypto_secretbox::Key::generate();
/// assert!(crypto_secretbox::open(&ciphertext, &nonce, &wrong_key).is_err());
///
/// // Tampering with the ciphertext will cause authentication to fail
/// let mut tampered = ciphertext.clone();
/// tampered[0] ^= 1; // Flip a bit
/// assert!(crypto_secretbox::open(&tampered, &nonce, &key).is_err());
/// ```
// Export submodules
/// XChaCha20-Poly1305 authenticated encryption
///
/// This submodule provides an alternative implementation of authenticated encryption
/// using XChaCha20 for encryption and Poly1305 for authentication. It is similar to
/// the functions in the parent module but uses XChaCha20 instead of XSalsa20.
///
/// The main advantage of XChaCha20-Poly1305 is its larger nonce size (192 bits vs 192 bits),
/// which makes it more suitable for applications where random nonces are preferred.
///
/// See the submodule documentation for more details.