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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! # XChaCha20-Poly1305-IETF Authenticated Encryption with Associated Data
//!
//! This module provides authenticated encryption and decryption using the
//! XChaCha20-Poly1305-IETF algorithm. This is a state-of-the-art AEAD cipher
//! that combines the XChaCha20 stream cipher with the Poly1305 message authentication code.
//!
//! ## Algorithm Details
//!
//! XChaCha20-Poly1305 is a two-part construction:
//!
//! 1. **XChaCha20**: An extended nonce variant of the ChaCha20 stream cipher
//! * Uses a 256-bit key for encryption
//! * Uses a 192-bit nonce (extended from ChaCha20's 96-bit nonce)
//! * The extended nonce provides protection against accidental nonce reuse
//! * Internally uses the HChaCha20 function to derive a subkey from the key and first 128 bits of the nonce
//!
//! 2. **Poly1305**: A fast message authentication code (MAC)
//! * Produces a 128-bit (16-byte) authentication tag
//! * Authenticates both the ciphertext and the additional data
//! * Uses a one-time key derived from the encryption key and nonce
//!
//! ## Features and Advantages
//!
//! - **Strong security**: 256-bit keys and 192-bit nonces provide high security margins
//! - **High performance**: Optimized for software implementations without requiring specialized hardware
//! - **Cross-platform efficiency**: Works efficiently on all platforms, from embedded devices to servers
//! - **Large nonce size**: 192-bit nonces make random nonce generation safe (collision probability is negligible)
//! - **Timing attack resistance**: The algorithm is designed to be constant-time, protecting against timing side-channels
//! - **Misuse resistance**: More forgiving of implementation errors compared to AES-GCM
//! - **Simplicity**: The algorithm is relatively simple to implement correctly
//!
//! ## Security Properties
//!
//! - **Confidentiality**: The encrypted message cannot be read without the secret key
//! - **Integrity**: Any modification to the ciphertext will be detected during decryption
//! - **Authenticity**: The receiver can verify that the message was created by someone with the secret key
//! - **Nonce misuse resistance**: While nonce reuse should always be avoided, XChaCha20-Poly1305 provides
//! better resistance to nonce reuse compared to some other AEAD constructions
//!
//! ## Security Considerations and Best Practices
//!
//! - **Nonce handling**: While the 192-bit nonce makes random generation safe, you can also use a counter
//! for maximum safety. Never reuse a nonce with the same key.
//!
//! - **Key management**: Protect your secret keys. Consider using key derivation functions (KDFs)
//! to derive encryption keys from passwords or master keys.
//!
//! - **Additional authenticated data (AAD)**: Not encrypted but is authenticated. Use it for metadata
//! that doesn't need confidentiality but must be authenticated (e.g., message headers, timestamps).
//!
//! - **Authentication failures**: If authentication fails during decryption, the entire message is
//! rejected and no plaintext is returned. Treat this as a potential attack.
//!
//! - **Ciphertext expansion**: The ciphertext will be larger than the plaintext by `ABYTES` (16 bytes)
//! for the authentication tag.
//!
//! - **Detached mode**: For some applications, it may be beneficial to store the authentication tag
//! separately from the ciphertext. Use the `encrypt_detached` and `decrypt_detached` functions for this.
//!
//! ## When to Use XChaCha20-Poly1305
//!
//! - When you need a modern, secure AEAD algorithm with excellent software performance
//! - When you want to safely use randomly generated nonces
//! - When you need an algorithm that works efficiently on all platforms without hardware acceleration
//! - When you need a well-analyzed and trusted algorithm with a large security margin
//!
//! ## Example
//!
//! ```rust
//! use libsodium_rs as sodium;
//! use sodium::crypto_aead::xchacha20poly1305;
//! use sodium::ensure_init;
//!
//! // Initialize libsodium
//! ensure_init().expect("Failed to initialize libsodium");
//!
//! // Generate a random key
//! let key = xchacha20poly1305::Key::generate();
//!
//! // Create a nonce
//! let nonce = xchacha20poly1305::Nonce::generate();
//!
//! // Message to encrypt
//! let message = b"Hello, world!";
//!
//! // Additional authenticated data (not encrypted, but authenticated)
//! let additional_data = b"Important metadata";
//!
//! // Encrypt the message
//! let ciphertext = xchacha20poly1305::encrypt(
//! message,
//! Some(additional_data),
//! &nonce,
//! &key,
//! ).unwrap();
//!
//! // Decrypt the message
//! let decrypted = xchacha20poly1305::decrypt(
//! &ciphertext,
//! Some(additional_data),
//! &nonce,
//! &key,
//! ).unwrap();
//!
//! assert_eq!(message, &decrypted[..]);
//! ```
use crate::;
use ;
/// Number of bytes in a secret key (32)
///
/// The secret key is used for both encryption and decryption.
/// It must be kept secret and should be generated using a secure random number generator.
pub const KEYBYTES: usize = crypto_aead_xchacha20poly1305_ietf_KEYBYTES as usize;
/// Number of bytes in a nonce (24)
///
/// The nonce must be unique for each encryption operation with the same key.
/// It can be public, but must never be reused with the same key.
pub const NPUBBYTES: usize = crypto_aead_xchacha20poly1305_ietf_NPUBBYTES as usize;
/// A nonce (number used once) for XChaCha20-Poly1305-IETF operations
///
/// This struct represents a nonce for use with the XChaCha20-Poly1305-IETF encryption algorithm.
/// A nonce must be unique for each message encrypted with the same key to maintain security.
/// XChaCha20-Poly1305-IETF uses a 192-bit nonce, which is large enough that random nonces can be
/// safely used without worrying about collisions.
;
/// Number of bytes in an authentication tag (16)
///
/// This is the size of the authentication tag that is added to the ciphertext.
pub const ABYTES: usize = crypto_aead_xchacha20poly1305_ietf_ABYTES as usize;
/// A secret key for XChaCha20-Poly1305 encryption and decryption
///
/// This struct represents a 256-bit (32-byte) secret key used for
/// XChaCha20-Poly1305 authenticated encryption and decryption.
/// The key should be generated using a secure random number generator
/// and kept secret.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_aead::xchacha20poly1305;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = xchacha20poly1305::Key::generate();
///
/// // Create a key from existing bytes
/// let key_bytes = [0x42; xchacha20poly1305::KEYBYTES];
/// let key_from_bytes = xchacha20poly1305::Key::from_bytes(&key_bytes).unwrap();
/// ```
;
/// Encrypt a message using XChaCha20-Poly1305-IETF
///
/// This function encrypts a message using the XChaCha20-Poly1305-IETF algorithm.
/// It provides both confidentiality and authenticity for the message, and also
/// authenticates the additional data if provided.
///
/// # Arguments
/// * `message` - The message to encrypt
/// * `additional_data` - Optional additional data to authenticate (but not encrypt)
/// * `nonce` - The nonce to use (must be exactly `NPUBBYTES` bytes)
/// * `key` - The key to use for encryption
///
/// # Returns
/// * `Result<Vec<u8>>` - The encrypted message with authentication tag appended
///
/// # Security Considerations
/// * The nonce must be unique for each encryption with the same key
/// * The nonce can be public, but must never be reused with the same key
/// * For random nonces, use `random::bytes(NPUBBYTES)`
/// * The additional data is authenticated but not encrypted
///
/// # Example
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_aead::xchacha20poly1305;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = xchacha20poly1305::Key::generate();
///
/// // Generate a random nonce
/// let nonce = xchacha20poly1305::Nonce::generate();
///
/// // Message to encrypt
/// let message = b"Hello, world!";
///
/// // Additional authenticated data (not encrypted, but authenticated)
/// let additional_data = b"Important metadata";
///
/// // Encrypt the message
/// let ciphertext = xchacha20poly1305::encrypt(
/// message,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
/// ```
///
/// # Errors
/// Returns an error if:
/// * The nonce is not exactly `NPUBBYTES` bytes
/// * The encryption operation fails
/// Decrypt a message using XChaCha20-Poly1305-IETF
///
/// This function decrypts a message that was encrypted using the XChaCha20-Poly1305-IETF
/// algorithm. It verifies the authenticity of both the ciphertext and the additional data
/// (if provided) before returning the decrypted message.
///
/// # Arguments
/// * `ciphertext` - The encrypted message with authentication tag
/// * `additional_data` - Optional additional data to authenticate (must be the same as used during encryption)
/// * `nonce` - The nonce used for encryption (must be exactly `NPUBBYTES` bytes)
/// * `key` - The key used for encryption
///
/// # Returns
/// * `Result<Vec<u8>>` - The decrypted message
///
/// # Security Considerations
/// * If authentication fails, the function returns an error and no decryption is performed
/// * The additional data must be the same as used during encryption
/// * The nonce must be the same as used during encryption
///
/// # Example
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_aead::xchacha20poly1305;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = xchacha20poly1305::Key::generate();
///
/// // Generate a random nonce
/// let nonce = xchacha20poly1305::Nonce::generate();
///
/// // Message to encrypt
/// let message = b"Hello, world!";
///
/// // Additional authenticated data (not encrypted, but authenticated)
/// let additional_data = b"Important metadata";
///
/// // Encrypt the message
/// let ciphertext = xchacha20poly1305::encrypt(
/// message,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
///
/// // Decrypt the message
/// let decrypted = xchacha20poly1305::decrypt(
/// &ciphertext,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
///
/// assert_eq!(message, &decrypted[..]);
/// ```
///
/// # Errors
/// Returns an error if:
/// * The nonce is not exactly `NPUBBYTES` bytes
/// * The ciphertext is too short (less than `ABYTES` bytes)
/// * Authentication verification fails
/// * The decryption operation fails
/// Encrypt a message using XChaCha20-Poly1305-IETF with detached authentication tag
///
/// This function encrypts a message using the XChaCha20-Poly1305-IETF algorithm and returns
/// the ciphertext and authentication tag separately. This is useful when you want
/// to store or transmit the ciphertext and tag separately.
///
/// # Arguments
/// * `message` - The message to encrypt
/// * `additional_data` - Optional additional data to authenticate (but not encrypt)
/// * `nonce` - The nonce to use (must be exactly `NPUBBYTES` bytes)
/// * `key` - The key to use for encryption
///
/// # Returns
/// * `Result<(Vec<u8>, Vec<u8>)>` - A tuple containing (ciphertext, authentication_tag)
///
/// # Security Considerations
/// * The nonce must be unique for each encryption with the same key
/// * The nonce can be public, but must never be reused with the same key
/// * For random nonces, use `random::bytes(NPUBBYTES)`
/// * The additional data is authenticated but not encrypted
///
/// # Example
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_aead::xchacha20poly1305;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = xchacha20poly1305::Key::generate();
///
/// // Generate a random nonce
/// let nonce = xchacha20poly1305::Nonce::generate();
///
/// // Message to encrypt
/// let message = b"Hello, world!";
///
/// // Additional authenticated data (not encrypted, but authenticated)
/// let additional_data = b"Important metadata";
///
/// // Encrypt the message with detached authentication tag
/// let (ciphertext, tag) = xchacha20poly1305::encrypt_detached(
/// message,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
/// ```
///
/// # Errors
/// Returns an error if:
/// * The nonce is not exactly `NPUBBYTES` bytes
/// * The encryption operation fails
/// Decrypt a message using XChaCha20-Poly1305-IETF with detached authentication tag
///
/// This function decrypts a message that was encrypted using the XChaCha20-Poly1305-IETF
/// algorithm with a detached authentication tag. It verifies the authenticity of
/// both the ciphertext and the additional data (if provided) before returning the
/// decrypted message.
///
/// # Arguments
/// * `ciphertext` - The encrypted message
/// * `tag` - The authentication tag
/// * `additional_data` - Optional additional data to authenticate (must be the same as used during encryption)
/// * `nonce` - The nonce used for encryption (must be exactly `NPUBBYTES` bytes)
/// * `key` - The key used for encryption
///
/// # Returns
/// * `Result<Vec<u8>>` - The decrypted message
///
/// # Security Considerations
/// * If authentication fails, the function returns an error and no decryption is performed
/// * The additional data must be the same as used during encryption
/// * The nonce must be the same as used during encryption
///
/// # Example
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_aead::xchacha20poly1305;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Generate a random key
/// let key = xchacha20poly1305::Key::generate();
///
/// // Generate a random nonce
/// let nonce = xchacha20poly1305::Nonce::generate();
///
/// // Message to encrypt
/// let message = b"Hello, world!";
///
/// // Additional authenticated data (not encrypted, but authenticated)
/// let additional_data = b"Important metadata";
///
/// // Encrypt the message with detached authentication tag
/// let (ciphertext, tag) = xchacha20poly1305::encrypt_detached(
/// message,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
///
/// // Decrypt the message with detached authentication tag
/// let decrypted = xchacha20poly1305::decrypt_detached(
/// &ciphertext,
/// &tag,
/// Some(additional_data),
/// &nonce,
/// &key,
/// ).unwrap();
///
/// assert_eq!(message, &decrypted[..]);
/// ```
///
/// # Errors
/// Returns an error if:
/// * The nonce is not exactly `NPUBBYTES` bytes
/// * The tag is not exactly `ABYTES` bytes
/// * Authentication verification fails
/// * The decryption operation fails