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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! # Cryptographic Utilities
//!
//! This module provides various utility functions for cryptographic operations, including
//! secure memory management, constant-time comparisons, and encoding/decoding functions.
//! These utilities are designed to help implement cryptographic protocols securely and
//! efficiently.
//!
//! ## Security Considerations
//!
//! - Many functions in this module are specifically designed to prevent side-channel attacks
//! and other security vulnerabilities.
//! - The memory management functions help prevent sensitive data from being leaked or
//! swapped to disk.
//! - Always use these utilities when handling sensitive cryptographic material.
//!
//! ## Key Features
//!
//! - **Secure Memory Management**: Functions for securely allocating, protecting, and
//! clearing memory containing sensitive data.
//! - **Constant-Time Operations**: Functions for comparing data in constant time to prevent
//! timing attacks.
//! - **Encoding/Decoding**: Functions for converting between binary data and hexadecimal or
//! Base64 representations.
//! - **Arithmetic Operations**: Functions for performing arithmetic on big-endian encoded
//! numbers, useful for nonce management.
//!
//! ## Example
//!
//! ```rust
//! use libsodium_rs as sodium;
//! use sodium::utils;
//! use sodium::ensure_init;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! ensure_init()?;
//!
//! // Secure memory operations
//! let mut sensitive_data = [0x01, 0x02, 0x03, 0x04];
//!
//! // Lock memory to prevent it from being swapped to disk
//! utils::mlock(&mut sensitive_data).expect("Failed to lock memory");
//!
//! // Use the sensitive data...
//!
//! // Securely zero the memory when done
//! utils::memzero(&mut sensitive_data);
//! assert_eq!(sensitive_data, [0, 0, 0, 0]);
//!
//! // Unlock the memory
//! utils::munlock(&mut sensitive_data).expect("Failed to unlock memory");
//!
//! // Constant-time comparison
//! let tag1 = [0x01, 0x02, 0x03, 0x04];
//! let tag2 = [0x01, 0x02, 0x03, 0x04];
//! assert!(utils::memcmp(&tag1, &tag2));
//!
//! // Encoding/decoding
//! let binary = [0xDE, 0xAD, 0xBE, 0xEF];
//! let hex = utils::bin2hex(&binary);
//! assert_eq!(hex, "deadbeef");
//!
//! Ok(())
//! }
//! ```
//!
use crateResult;
use libsodium_sys;
use ptr;
/// Base64 encoding variant: original (standard) Base64 encoding
pub const BASE64_VARIANT_ORIGINAL: i32 = sodium_base64_VARIANT_ORIGINAL as i32;
/// Base64 encoding variant: original (standard) Base64 encoding without padding
pub const BASE64_VARIANT_ORIGINAL_NO_PADDING: i32 =
sodium_base64_VARIANT_ORIGINAL_NO_PADDING as i32;
/// Base64 encoding variant: URL-safe Base64 encoding
pub const BASE64_VARIANT_URLSAFE: i32 = sodium_base64_VARIANT_URLSAFE as i32;
/// Base64 encoding variant: URL-safe Base64 encoding without padding
pub const BASE64_VARIANT_URLSAFE_NO_PADDING: i32 =
sodium_base64_VARIANT_URLSAFE_NO_PADDING as i32;
/// Compare two byte slices in constant time
///
/// This function compares two byte slices in constant time, which is important for
/// comparing secret data like authentication tags or passwords. It returns true if
/// the slices are equal, false otherwise.
///
/// ## Security Considerations
///
/// - This function is designed to prevent timing attacks that could leak information
/// about the contents of the slices being compared.
/// - It should be used whenever comparing sensitive data like authentication tags,
/// MACs, or password hashes.
/// - Regular comparison operators (==) should NOT be used for comparing secret data
/// as they may be vulnerable to timing attacks.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let tag1 = [0x01, 0x02, 0x03, 0x04];
/// let tag2 = [0x01, 0x02, 0x03, 0x04];
/// let tag3 = [0x01, 0x02, 0x03, 0x05];
///
/// // Compare in constant time
/// assert!(utils::memcmp(&tag1, &tag2)); // Equal
/// assert!(!utils::memcmp(&tag1, &tag3)); // Not equal
/// ```
///
/// # Arguments
/// * `a` - First byte slice to compare
/// * `b` - Second byte slice to compare
///
/// # Returns
/// * `bool` - `true` if the slices are equal, `false` otherwise
/// Zero a byte slice in a way that won't be optimized out
///
/// This function securely zeroes a byte slice, ensuring that the operation
/// won't be optimized out by the compiler. This is important for securely
/// clearing sensitive data from memory.
///
/// ## Security Considerations
///
/// - Regular assignment operations (like `buf = [0; N]`) might be optimized out
/// by the compiler if it determines the values won't be read again.
/// - This function guarantees that the memory will be zeroed regardless of
/// compiler optimizations.
/// - Use this whenever you need to clear sensitive data like keys, passwords,
/// or other secret material from memory.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// // Some sensitive data
/// let mut secret_key = [0x01, 0x02, 0x03, 0x04];
///
/// // Use the key for some operation...
///
/// // Securely clear the key from memory when done
/// utils::memzero(&mut secret_key);
/// assert_eq!(secret_key, [0, 0, 0, 0]);
/// ```
///
/// # Arguments
/// * `buf` - The byte slice to zero
/// Zero a region of the stack in a way that won't be optimized out
///
/// This function securely zeroes a region of the stack, ensuring that the operation
/// won't be optimized out by the compiler. This is useful for clearing sensitive
/// stack-allocated variables.
///
/// ## Security Considerations
///
/// - This function is specifically designed for clearing sensitive data from the stack.
/// - For heap-allocated memory, use `memzero()` instead.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// // Some sensitive stack data
/// let mut sensitive_data = [0x01u8; 1024];
///
/// // Use the data for some operation...
///
/// // Securely clear the data from the stack
/// utils::stackzero(sensitive_data.len());
/// ```
///
/// # Arguments
/// * `len` - The number of bytes to zero on the stack
/// Lock memory pages containing this slice, preventing them from being swapped to disk
///
/// This function locks the memory pages containing the provided byte slice, preventing
/// them from being swapped to disk. This is important for sensitive data like encryption
/// keys, passwords, or other secret material.
///
/// # Returns
/// * `std::io::Result<()>` - Success or an IO error if the operation fails
///
/// # Examples
/// ```
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let mut sensitive_data = [0x01, 0x02, 0x03, 0x04];
/// utils::mlock(&mut sensitive_data).expect("Failed to lock memory");
/// // Use the sensitive data...
/// utils::munlock(&mut sensitive_data).expect("Failed to unlock memory");
/// ```
/// Unlock previously locked memory pages
///
/// This function unlocks memory pages that were previously locked with `mlock`.
/// It should be called when the sensitive data is no longer needed.
///
/// # Returns
/// * `std::io::Result<()>` - Success or an IO error if the operation fails
///
/// # Examples
/// ```
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let mut sensitive_data = [0x01, 0x02, 0x03, 0x04];
/// utils::mlock(&mut sensitive_data).expect("Failed to lock memory");
/// // Use the sensitive data...
/// utils::munlock(&mut sensitive_data).expect("Failed to unlock memory");
/// ```
/// Increment a number (usually a nonce) stored as big-endian bytes
/// Add two numbers stored as big-endian bytes
///
/// This function adds two numbers stored as big-endian bytes. The result
/// is stored in the first array (`a`).
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let mut a = [0x01, 0x02, 0x03, 0x04];
/// let b = [0x00, 0x01, 0x00, 0x01];
///
/// utils::add_be(&mut a, &b);
/// assert_eq!(a, [0x01, 0x03, 0x03, 0x05]);
/// ```
///
/// # Arguments
/// * `a` - First number as big-endian bytes (will be modified to store the result)
/// * `b` - Second number as big-endian bytes
/// Subtract one number from another, both stored as big-endian bytes
///
/// This function subtracts the second number (`b`) from the first number (`a`),
/// both stored as big-endian bytes. The result is stored in the first array (`a`).
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let mut a = [0x01, 0x03, 0x03, 0x05];
/// let b = [0x00, 0x01, 0x00, 0x01];
///
/// utils::sub_be(&mut a, &b);
/// assert_eq!(a, [0x01, 0x02, 0x03, 0x04]);
/// ```
///
/// # Arguments
/// * `a` - First number as big-endian bytes (will be modified to store the result)
/// * `b` - Second number as big-endian bytes (will be subtracted from `a`)
/// Check if bytes is all zeros
///
/// This function checks if bytes contains only zeros. It is designed to be
/// constant-time regardless of the input data, which is important for security-sensitive
/// applications.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let zeros = [0, 0, 0, 0];
/// let non_zeros = [0, 0, 1, 0];
///
/// assert!(utils::is_zero(&zeros));
/// assert!(!utils::is_zero(&non_zeros));
/// ```
///
/// # Arguments
/// * `n` - The bytes to check
///
/// # Returns
/// * `bool` - `true` if the array contains only zeros, `false` otherwise
/// Compare two byte slices in lexicographical order
///
/// This function compares two byte slices in lexicographical order. It returns -1 if
/// the first array is less than the second, 1 if the first array is greater than the
/// second, and 0 if they are equal. If the shared prefix is equal, the shorter
/// slice is considered smaller.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let a = [0x01, 0x02, 0x03, 0x04];
/// let b = [0x01, 0x02, 0x03, 0x05];
/// let c = [0x01, 0x02, 0x03, 0x04];
///
/// assert_eq!(utils::compare(&a, &b), -1); // a < b
/// assert_eq!(utils::compare(&b, &a), 1); // b > a
/// assert_eq!(utils::compare(&a, &c), 0); // a == c
/// ```
///
/// # Arguments
/// * `a` - First bytes to compare
/// * `b` - Second bytes to compare
///
/// # Returns
/// * `i32` - -1 if a < b, 1 if a > b, 0 if a == b
/// Convert bytes to a hexadecimal string
///
/// This function converts bytes to a hexadecimal string representation.
/// Each byte is represented by two hexadecimal characters.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let bytes = [0xDE, 0xAD, 0xBE, 0xEF];
/// let hex = utils::bin2hex(&bytes);
///
/// assert_eq!(hex, "deadbeef");
/// ```
///
/// # Arguments
/// * `bin` - The bytes to convert
///
/// # Returns
/// * `String` - The hexadecimal string representation
/// Calculate the required length for Base64 encoding
///
/// This function calculates the required length for encoding a binary input
/// of the given length to Base64, including the null terminator.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let bin_len = 10;
/// let b64_len = utils::base64_encoded_len(bin_len, utils::BASE64_VARIANT_ORIGINAL);
///
/// // The exact length depends on the implementation details of libsodium
/// // and may vary between versions
/// ```
///
/// # Arguments
/// * `bin_len` - The length of the binary input
/// * `variant` - The Base64 encoding variant to use
///
/// # Returns
/// * `usize` - The required length for the Base64 encoding (including null terminator)
/// Convert bytes to a Base64 string
///
/// This function converts bytes to a Base64 string representation.
/// Different encoding variants are supported, including standard Base64 and
/// URL-safe Base64, with or without padding.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let bytes = [0xDE, 0xAD, 0xBE, 0xEF];
///
/// // Standard Base64 encoding
/// let b64 = utils::bin2base64(&bytes, utils::BASE64_VARIANT_ORIGINAL);
/// assert_eq!(b64, "3q2+7w==");
///
/// // URL-safe Base64 encoding without padding
/// let b64_url = utils::bin2base64(&bytes, utils::BASE64_VARIANT_URLSAFE_NO_PADDING);
/// assert_eq!(b64_url, "3q2-7w");
/// ```
///
/// # Arguments
/// * `bin` - The bytes to convert
/// * `variant` - The Base64 encoding variant to use
///
/// # Returns
/// * `String` - The Base64 string representation
/// Convert a Base64 string to bytes
///
/// This function converts a Base64 string to its binary representation.
/// Different encoding variants are supported, including standard Base64 and
/// URL-safe Base64, with or without padding.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// // Standard Base64 encoding
/// let b64 = "3q2+7w==";
/// let bytes = utils::base642bin(b64, utils::BASE64_VARIANT_ORIGINAL).unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
///
/// // URL-safe Base64 encoding without padding
/// let b64_url = "3q2-7w";
/// let bytes = utils::base642bin(b64_url, utils::BASE64_VARIANT_URLSAFE_NO_PADDING).unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
/// ```
///
/// # Arguments
/// * `b64` - The Base64 string to convert
/// * `variant` - The Base64 encoding variant to use
///
/// # Returns
/// * `Result<Vec<u8>>` - The binary representation or an error
/// Convert a hexadecimal string to bytes
///
/// This function converts a hexadecimal string to its binary representation.
/// It ignores characters specified in the ignore parameter.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// let hex = "deadbeef";
/// let bytes = utils::hex2bin(hex).unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
///
/// // With ignored characters
/// let hex_with_colons = "de:ad:be:ef";
/// let bytes = utils::hex2bin_ignore(hex_with_colons, ":").unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
/// ```
///
/// # Arguments
/// * `hex` - The hexadecimal string to convert
///
/// # Returns
/// * `Result<Vec<u8>>` - The binary representation or an error
/// Convert a hexadecimal string to bytes, ignoring specified characters
///
/// This function converts a hexadecimal string to its binary representation,
/// ignoring any characters specified in the `ignore` parameter.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::utils;
///
/// // With ignored characters
/// let hex_with_colons = "de:ad:be:ef";
/// let bytes = utils::hex2bin_ignore(hex_with_colons, ":").unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
///
/// // With spaces and colons
/// let hex_with_spaces = "de ad be:ef";
/// let bytes = utils::hex2bin_ignore(hex_with_spaces, ": ").unwrap();
/// assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
/// ```
///
/// # Arguments
/// * `hex` - The hexadecimal string to convert
/// * `ignore` - Characters to ignore in the input string
///
/// # Returns
/// * `Result<Vec<u8>>` - The binary representation or an error
/// Secure memory allocation
///
/// This function allocates memory with extra protection, including:
/// - Protection against buffer overflows
/// - Protection against access after the memory is freed
/// - Automatic zeroing when freed
/// - Guarded pages to detect over/underflows
///
/// ## Security Considerations
///
/// - The allocated memory is automatically zeroed when freed
/// - The memory is protected from being swapped to disk
/// - This should be used for storing sensitive data like keys
///
/// ## Example
///
/// ```no_run
/// use libsodium_rs as sodium;
/// use sodium::utils;
/// use std::slice;
///
/// // Allocate 32 bytes of secure memory
/// let ptr = utils::malloc(32);
/// assert!(!ptr.is_null());
///
/// // Use the memory
/// unsafe {
/// let buf = slice::from_raw_parts_mut(ptr as *mut u8, 32);
/// // Fill with data...
/// for i in 0..32 {
/// buf[i] = i as u8;
/// }
/// }
///
/// // Free the memory (automatically zeroes it)
/// unsafe {
/// utils::free(ptr);
/// }
/// ```
///
/// # Arguments
/// * `size` - The number of bytes to allocate
///
/// # Returns
/// * `*mut libc::c_void` - A pointer to the allocated memory, or null if allocation failed
/// Allocate a buffer of a specific size and alignment
///
/// This function allocates a buffer with the specified size and alignment,
/// with the same protections as `malloc`.
///
/// ## Arguments
/// * `count` - The number of elements to allocate
/// * `size` - The size of each element
///
/// ## Returns
/// * `*mut libc::c_void` - A pointer to the allocated memory, or null if allocation failed
/// Free memory allocated by sodium_malloc or sodium_allocarray
///
/// This function frees memory that was allocated by `malloc` or `allocarray`.
/// The memory is automatically zeroed before being freed.
///
/// ## Safety
/// This function is unsafe because it dereferences a raw pointer.
/// The caller must ensure that the pointer is valid and was allocated by `malloc` or `allocarray`.
///
/// ## Arguments
/// * `ptr` - A pointer to the memory to free
pub unsafe
/// Make a region of memory inaccessible
///
/// This function makes a region of memory allocated with `malloc` or `allocarray`
/// completely inaccessible. It can be made accessible again with `mprotect_readwrite`
/// or `mprotect_readonly`.
///
/// ## Safety
/// This function is unsafe because it dereferences a raw pointer.
/// The caller must ensure that the pointer is valid and was allocated by `malloc` or `allocarray`.
///
/// ## Arguments
/// * `ptr` - A pointer to the memory region
///
/// ## Returns
/// * `i32` - 0 on success, -1 on failure
pub unsafe
/// Make a region of memory read-only
///
/// This function makes a region of memory allocated with `malloc` or `allocarray`
/// read-only. It can be made writable again with `mprotect_readwrite`.
///
/// ## Safety
/// This function is unsafe because it dereferences a raw pointer.
/// The caller must ensure that the pointer is valid and was allocated by `malloc` or `allocarray`.
///
/// ## Arguments
/// * `ptr` - A pointer to the memory region
///
/// ## Returns
/// * `i32` - 0 on success, -1 on failure
pub unsafe
/// Make a region of memory readable and writable
///
/// This function makes a region of memory allocated with `malloc` or `allocarray`
/// readable and writable.
///
/// ## Safety
/// This function is unsafe because it dereferences a raw pointer.
/// The caller must ensure that the pointer is valid and was allocated by `malloc` or `allocarray`.
///
/// ## Arguments
/// * `ptr` - A pointer to the memory region
///
/// ## Returns
/// * `i32` - 0 on success, -1 on failure
pub unsafe