1#[cfg(feature = "alloc")]
2use alloc::{boxed::Box, string::String, vec::Vec};
3use core::{
4 fmt,
5 hint::black_box,
6 marker::PhantomData,
7 sync::atomic::{compiler_fence, Ordering},
8};
9
10use crate::{ct, wipe, wipe_backend};
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub struct LengthError {
15 pub expected: usize,
17 pub actual: usize,
19}
20
21impl fmt::Display for LengthError {
22 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23 write!(
24 formatter,
25 "length mismatch: expected {} bytes, got {} bytes",
26 self.expected, self.actual
27 )
28 }
29}
30
31#[cfg(feature = "std")]
32impl std::error::Error for LengthError {}
33
34pub trait SecureSanitize {
91 fn secure_sanitize(&mut self);
93}
94
95#[diagnostic::on_unimplemented(
116 message = "`{Self}` is not approved for destructor-path sanitization",
117 label = "`SecureSanitizeOnDrop` requires `DropSafeSanitize`",
118 note = "derive `SecureSanitize` for a generated field-wise sanitizer, or explicitly implement `DropSafeSanitize` after reviewing a manual aggregate sanitizer"
119)]
120pub trait DropSafeSanitize: SecureSanitize {}
121
122#[diagnostic::on_unimplemented(
201 message = "`{Self}` does not guarantee stable shared secret storage",
202 label = "generic shared secret exposure requires `StableSharedSecretStorage`",
203 note = "use a dedicated secret container or implement and document the storage contract for a reviewed fixed-storage type"
204)]
205pub trait StableSharedSecretStorage: SecureSanitize {}
206
207#[diagnostic::on_unimplemented(
247 message = "`{Self}` does not guarantee stable mutable secret storage",
248 label = "generic mutable secret exposure requires `StableMutableSecretStorage`",
249 note = "use a dedicated secret container or implement and document the storage contract for a reviewed fixed-storage type"
250)]
251pub trait StableMutableSecretStorage: StableSharedSecretStorage {}
252
253#[diagnostic::on_unimplemented(
273 message = "`{Self}` does not allow-list `{T}` as secret storage",
274 label = "this exact storage type is absent from the selected policy",
275 note = "review the type and add it with `define_secret_storage_policy!`, or select an already approved type"
276)]
277pub trait SecretStoragePolicy<T: SecureSanitize> {
278 const RATIONALE: &'static str;
280}
281
282#[macro_export]
321macro_rules! define_secret_storage_policy {
322 (
323 $(#[$metadata:meta])*
324 $visibility:vis $policy:ident {
325 $($storage:ty => $reason:literal),+ $(,)?
326 }
327 ) => {
328 $(#[$metadata])*
329 $visibility enum $policy {}
330
331 $(
332 const _: () = {
333 let reason: &str = $reason;
334 let bytes = reason.as_bytes();
335 let mut index = 0;
336 let mut has_content = false;
337 while index < bytes.len() {
338 let byte = bytes[index];
339 if byte != b' '
340 && byte != b'\t'
341 && byte != b'\n'
342 && byte != b'\r'
343 && byte != 0x0b
344 && byte != 0x0c
345 {
346 has_content = true;
347 }
348 index += 1;
349 }
350 assert!(
351 has_content,
352 "secret storage policy rationale must not be empty or ASCII-whitespace-only",
353 );
354 };
355
356 impl $crate::SecretStoragePolicy<$storage> for $policy {
357 const RATIONALE: &'static str = $reason;
358 }
359 )+
360 };
361}
362
363#[inline]
372pub fn secure_replace<T: SecureSanitize>(slot: &mut T, replacement: T) {
373 slot.secure_sanitize();
374 *slot = replacement;
375}
376
377#[cfg(feature = "std")]
389#[inline(never)]
390pub fn sanitize_then_abort<T: SecureSanitize + ?Sized>(root: &mut T) -> ! {
391 root.secure_sanitize();
392 compiler_fence(Ordering::SeqCst);
393 black_box(&mut *root);
394 std::process::abort()
395}
396
397macro_rules! impl_secure_sanitize_scalar {
398 ($($ty:ty),+ $(,)?) => {
399 $(
400 impl SecureSanitize for $ty {
401 #[inline(never)]
402 fn secure_sanitize(&mut self) {
403 wipe_backend::erase_plain_data(self);
404 }
405 }
406
407 impl StableSharedSecretStorage for $ty {}
408 impl StableMutableSecretStorage for $ty {}
409 )+
410 };
411}
412
413impl_secure_sanitize_scalar!(
414 u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, bool, char, f32, f64,
415);
416
417#[macro_export]
446macro_rules! secure_sanitize_struct {
447 (
448 $(#[$attr:meta])*
449 $vis:vis struct $name:ident {
450 $(
451 $(#[$field_attr:meta])*
452 $field_vis:vis $field:ident: $field_ty:ty
453 ),* $(,)?
454 }
455 ) => {
456 $(#[$attr])*
457 $vis struct $name {
458 $(
459 $(#[$field_attr])*
460 $field_vis $field: $field_ty,
461 )*
462 }
463
464 impl $crate::SecureSanitize for $name {
465 #[inline]
466 fn secure_sanitize(&mut self) {
467 $(
468 $crate::SecureSanitize::secure_sanitize(&mut self.$field);
469 )*
470 }
471 }
472
473 impl $crate::DropSafeSanitize for $name {}
474 };
475}
476
477#[macro_export]
501macro_rules! secure_drop_struct {
502 (
503 $(#[$attr:meta])*
504 $vis:vis struct $name:ident {
505 $(
506 $(#[$field_attr:meta])*
507 $field_vis:vis $field:ident: $field_ty:ty
508 ),* $(,)?
509 }
510 ) => {
511 $crate::secure_sanitize_struct! {
512 $(#[$attr])*
513 $vis struct $name {
514 $(
515 $(#[$field_attr])*
516 $field_vis $field: $field_ty,
517 )*
518 }
519 }
520
521 impl Drop for $name {
522 #[inline]
523 fn drop(&mut self) {
524 fn require_drop_contract<T: ?Sized + $crate::DropSafeSanitize + ::core::marker::Unpin>() {}
525 require_drop_contract::<Self>();
526 $crate::SecureSanitize::secure_sanitize(self);
527 }
528 }
529 };
530}
531
532#[cfg(feature = "alloc")]
533#[inline(never)]
534pub(crate) fn sanitize_vec_capacity(bytes: &mut Vec<u8>) {
535 wipe::vec(bytes);
536}
537
538#[cfg(all(feature = "alloc", feature = "multi-pass-clear"))]
539#[inline(never)]
540fn sanitize_vec_capacity_multi_pass(bytes: &mut Vec<u8>) {
541 wipe::vec_multi_pass(bytes);
542}
543
544#[cfg(feature = "alloc")]
545#[inline]
546fn next_secret_capacity(current: usize, required: usize) -> usize {
547 current.saturating_mul(2).max(required).max(8)
548}
549
550#[cfg(feature = "alloc")]
551const MAX_UTF8_CHAR_BYTES: usize = 4;
552
553impl<T: SecureSanitize> SecureSanitize for [T] {
554 #[inline(never)]
555 fn secure_sanitize(&mut self) {
556 for item in self.iter_mut() {
557 item.secure_sanitize();
558 }
559 compiler_fence(Ordering::SeqCst);
560 }
561}
562
563impl<T: SecureSanitize, const N: usize> SecureSanitize for [T; N] {
564 #[inline(never)]
565 fn secure_sanitize(&mut self) {
566 self.as_mut_slice().secure_sanitize();
567 }
568}
569
570impl<T: StableSharedSecretStorage> StableSharedSecretStorage for [T] {}
571impl<T: StableMutableSecretStorage> StableMutableSecretStorage for [T] {}
572
573impl<T: StableSharedSecretStorage, const N: usize> StableSharedSecretStorage for [T; N] {}
574impl<T: StableMutableSecretStorage, const N: usize> StableMutableSecretStorage for [T; N] {}
575
576impl SecureSanitize for () {
577 #[inline]
578 fn secure_sanitize(&mut self) {}
579}
580
581impl StableSharedSecretStorage for () {}
582impl StableMutableSecretStorage for () {}
583
584macro_rules! impl_tuple_storage_contracts {
585 ($(($($type:ident:$index:tt),+)),+ $(,)?) => {
586 $(
587 impl<$($type: SecureSanitize),+> SecureSanitize for ($($type,)+) {
588 #[inline]
589 fn secure_sanitize(&mut self) {
590 $(
591 self.$index.secure_sanitize();
592 )+
593 compiler_fence(Ordering::SeqCst);
594 }
595 }
596
597 impl<$($type: StableSharedSecretStorage),+> StableSharedSecretStorage
598 for ($($type,)+)
599 {}
600
601 impl<$($type: StableMutableSecretStorage),+> StableMutableSecretStorage
602 for ($($type,)+)
603 {}
604 )+
605 };
606}
607
608impl_tuple_storage_contracts!(
609 (A:0),
610 (A:0, B:1),
611 (A:0, B:1, C:2),
612 (A:0, B:1, C:2, D:3),
613 (A:0, B:1, C:2, D:3, E:4),
614 (A:0, B:1, C:2, D:3, E:4, F:5),
615 (A:0, B:1, C:2, D:3, E:4, F:5, G:6),
616 (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7),
617 (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8),
618 (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9),
619 (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10),
620 (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11),
621);
622
623impl<T: SecureSanitize> SecureSanitize for Option<T> {
624 #[inline]
625 fn secure_sanitize(&mut self) {
626 if let Some(value) = self.as_mut() {
627 value.secure_sanitize();
628 }
629 *self = None;
630 compiler_fence(Ordering::SeqCst);
631 }
632}
633
634impl<T: SecureSanitize, E: SecureSanitize> SecureSanitize for Result<T, E> {
635 #[inline]
636 fn secure_sanitize(&mut self) {
637 match self {
638 Ok(value) => value.secure_sanitize(),
639 Err(error) => error.secure_sanitize(),
640 }
641 compiler_fence(Ordering::SeqCst);
642 }
643}
644
645impl<T> SecureSanitize for PhantomData<T> {
646 #[inline]
647 fn secure_sanitize(&mut self) {}
648}
649
650impl<T> StableSharedSecretStorage for PhantomData<T> {}
651impl<T> StableMutableSecretStorage for PhantomData<T> {}
652
653#[cfg(feature = "alloc")]
654impl<T: SecureSanitize + ?Sized> SecureSanitize for Box<T> {
661 #[inline]
662 fn secure_sanitize(&mut self) {
663 self.as_mut().secure_sanitize();
664 }
665}
666
667impl SecureSanitize for str {
672 #[inline]
673 fn secure_sanitize(&mut self) {
674 crate::wipe_backend::erase_str(self);
675 }
676}
677
678impl StableSharedSecretStorage for str {}
679
680impl StableMutableSecretStorage for str {}
681
682#[cfg(feature = "alloc")]
683impl<T: SecureSanitize> SecureSanitize for Vec<T> {
691 #[inline]
692 fn secure_sanitize(&mut self) {
693 for item in self.iter_mut() {
694 item.secure_sanitize();
695 }
696 self.clear();
697 wipe_backend::erase(
698 self.as_mut_ptr().cast::<u8>(),
699 self.capacity().saturating_mul(core::mem::size_of::<T>()),
700 );
701 compiler_fence(Ordering::SeqCst);
702 }
703}
704
705#[cfg(feature = "alloc")]
706impl SecureSanitize for String {
707 #[inline(never)]
708 fn secure_sanitize(&mut self) {
709 crate::wipe::string(self);
710 }
711}
712
713#[inline]
714pub(crate) fn constant_time_eq_slices(left: &[u8], right: &[u8]) -> bool {
715 if left.len() != right.len() {
716 return false;
717 }
718
719 constant_time_eq_equal_len(left, right)
720}
721
722#[inline]
723pub(crate) fn constant_time_eq_equal_len(left: &[u8], right: &[u8]) -> bool {
724 debug_assert_eq!(left.len(), right.len());
725
726 #[cfg(all(
727 feature = "asm-compare",
728 any(target_arch = "x86_64", target_arch = "aarch64"),
729 not(miri)
730 ))]
731 {
732 crate::compare_asm::constant_time_eq_equal_len(left, right)
733 }
734
735 #[cfg(not(all(
736 feature = "asm-compare",
737 any(target_arch = "x86_64", target_arch = "aarch64"),
738 not(miri)
739 )))]
740 {
741 portable_constant_time_eq_equal_len(left, right)
742 }
743}
744
745#[inline]
746#[cfg_attr(
747 all(
748 feature = "asm-compare",
749 any(target_arch = "x86_64", target_arch = "aarch64"),
750 not(miri)
751 ),
752 allow(dead_code)
753)]
754pub(crate) fn portable_constant_time_eq_equal_len(left: &[u8], right: &[u8]) -> bool {
755 debug_assert_eq!(left.len(), right.len());
756
757 let mut diff = 0usize;
758 let mut index = 0;
759 while index < left.len() {
760 diff = black_box(diff | usize::from(left[index] ^ right[index]));
761 index += 1;
762 }
763 black_box(diff) == 0
764}
765
766#[cfg(kani)]
767mod kani_verification {
768 use super::*;
769 use core::cmp::Ordering;
770
771 fn assert_ct_ordering_matches(ordering: ct::CtOrdering, expected: Ordering) {
772 match expected {
773 Ordering::Less => {
774 assert_eq!(
775 ordering
776 .is_less()
777 .declassify_u8("test or verification observes normalized choice"),
778 1
779 );
780 assert_eq!(
781 ordering
782 .is_equal()
783 .declassify_u8("test or verification observes normalized choice"),
784 0
785 );
786 assert_eq!(
787 ordering
788 .is_greater()
789 .declassify_u8("test or verification observes normalized choice"),
790 0
791 );
792 }
793 Ordering::Equal => {
794 assert_eq!(
795 ordering
796 .is_less()
797 .declassify_u8("test or verification observes normalized choice"),
798 0
799 );
800 assert_eq!(
801 ordering
802 .is_equal()
803 .declassify_u8("test or verification observes normalized choice"),
804 1
805 );
806 assert_eq!(
807 ordering
808 .is_greater()
809 .declassify_u8("test or verification observes normalized choice"),
810 0
811 );
812 }
813 Ordering::Greater => {
814 assert_eq!(
815 ordering
816 .is_less()
817 .declassify_u8("test or verification observes normalized choice"),
818 0
819 );
820 assert_eq!(
821 ordering
822 .is_equal()
823 .declassify_u8("test or verification observes normalized choice"),
824 0
825 );
826 assert_eq!(
827 ordering
828 .is_greater()
829 .declassify_u8("test or verification observes normalized choice"),
830 1
831 );
832 }
833 }
834 }
835
836 fn lexicographic_cmp_4(left: &[u8; 4], right: &[u8; 4]) -> Ordering {
837 let mut index = 0;
838 while index < 4 {
839 if left[index] < right[index] {
840 return Ordering::Less;
841 }
842 if left[index] > right[index] {
843 return Ordering::Greater;
844 }
845 index += 1;
846 }
847 Ordering::Equal
848 }
849
850 #[kani::proof]
851 fn prove_wipe_bytes_clears_fixed_buffer() {
852 let mut bytes: [u8; 4] = kani::any();
853
854 wipe::bytes(&mut bytes);
855
856 assert_eq!(bytes, [0; 4]);
857 }
858
859 #[kani::proof]
860 fn prove_secret_bytes_clear_erases_visible_contents() {
861 let source: [u8; 4] = kani::any();
862 let mut secret = SecretBytes::<4>::from_array(source);
863 let mut output = [0xA5; 4];
864
865 secret.secure_clear();
866 assert!(secret
867 .export_to_slice("test exports bytes for verification output", &mut output)
868 .is_ok());
869
870 assert_eq!(output, [0; 4]);
871 }
872
873 #[kani::proof]
874 fn prove_secret_bytes_constant_time_eq_matches_byte_equality() {
875 let left: [u8; 4] = kani::any();
876 let right: [u8; 4] = kani::any();
877 let secret = SecretBytes::<4>::from_array(left);
878
879 let mut expected = true;
880 let mut index = 0;
881 while index < 4 {
882 expected &= left[index] == right[index];
883 index += 1;
884 }
885
886 assert_eq!(secret.constant_time_eq(&right), expected);
887 }
888
889 #[kani::proof]
890 fn prove_ct_choice_is_normalized() {
891 let value: u8 = kani::any();
892 let choice = ct::Choice::from_u8(value);
893 let unwrapped = choice.declassify_u8("test or verification observes normalized choice");
894
895 assert!(unwrapped == 0 || unwrapped == 1);
896 }
897
898 #[kani::proof]
899 fn prove_ct_choice_boolean_algebra_matches_public_bits() {
900 let left_byte: u8 = kani::any();
901 let right_byte: u8 = kani::any();
902 let left = ct::Choice::from_u8(left_byte);
903 let right = ct::Choice::from_u8(right_byte);
904 let left_bit = left.declassify_u8("test or verification observes normalized choice");
905 let right_bit = right.declassify_u8("test or verification observes normalized choice");
906
907 assert_eq!(
908 (left & right).declassify_u8("test or verification observes normalized choice"),
909 left_bit & right_bit
910 );
911 assert_eq!(
912 (left | right).declassify_u8("test or verification observes normalized choice"),
913 left_bit | right_bit
914 );
915 assert_eq!(
916 (left ^ right).declassify_u8("test or verification observes normalized choice"),
917 left_bit ^ right_bit
918 );
919 assert_eq!(
920 (!left).declassify_u8("test or verification observes normalized choice"),
921 left_bit ^ 1
922 );
923 }
924
925 #[kani::proof]
926 fn prove_ct_fixed_equality_matches_byte_equality() {
927 let left: [u8; 4] = kani::any();
928 let right: [u8; 4] = kani::any();
929
930 let mut expected = true;
931 let mut index = 0;
932 while index < 4 {
933 expected &= left[index] == right[index];
934 index += 1;
935 }
936
937 assert_eq!(
938 ct::eq_fixed(&left, &right)
939 .declassify_u8("test or verification observes normalized choice")
940 == 1,
941 expected
942 );
943 }
944
945 #[kani::proof]
946 fn prove_ct_public_length_equality_rejects_mismatch() {
947 let left: [u8; 4] = kani::any();
948 let right: [u8; 3] = kani::any();
949
950 assert_eq!(
951 ct::eq_public_len(&left, &right)
952 .declassify_u8("test or verification observes normalized choice"),
953 0
954 );
955 }
956
957 #[kani::proof]
958 fn prove_ct_fixed_ordering_matches_lexicographic_ordering() {
959 let left: [u8; 4] = kani::any();
960 let right: [u8; 4] = kani::any();
961
962 assert_ct_ordering_matches(
963 ct::cmp_fixed(&left, &right),
964 lexicographic_cmp_4(&left, &right),
965 );
966 }
967
968 #[kani::proof]
969 fn prove_ct_unsigned_ordering_matches_rust_ordering() {
970 let left: u16 = kani::any();
971 let right: u16 = kani::any();
972
973 assert_ct_ordering_matches(
974 <u16 as ct::ConstantTimeOrd>::ct_cmp(&left, &right),
975 left.cmp(&right),
976 );
977 }
978
979 #[kani::proof]
980 fn prove_ct_signed_ordering_matches_rust_ordering() {
981 let left: i16 = kani::any();
982 let right: i16 = kani::any();
983
984 assert_ct_ordering_matches(
985 <i16 as ct::ConstantTimeOrd>::ct_cmp(&left, &right),
986 left.cmp(&right),
987 );
988 }
989
990 #[kani::proof]
991 fn prove_ct_conditional_copy_matches_choice() {
992 let initial: [u8; 4] = kani::any();
993 let source: [u8; 4] = kani::any();
994 let choice_byte: u8 = kani::any();
995 let choice = ct::Choice::from_u8(choice_byte);
996 let mut destination = initial;
997
998 assert!(ct::conditional_copy(&mut destination, &source, choice).is_ok());
999
1000 if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1001 assert_eq!(destination, source);
1002 } else {
1003 assert_eq!(destination, initial);
1004 }
1005 }
1006
1007 #[kani::proof]
1008 fn prove_ct_conditional_swap_matches_choice() {
1009 let initial_left: [u8; 4] = kani::any();
1010 let initial_right: [u8; 4] = kani::any();
1011 let choice_byte: u8 = kani::any();
1012 let choice = ct::Choice::from_u8(choice_byte);
1013 let mut left = initial_left;
1014 let mut right = initial_right;
1015
1016 assert!(ct::conditional_swap(&mut left, &mut right, choice).is_ok());
1017
1018 if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1019 assert_eq!(left, initial_right);
1020 assert_eq!(right, initial_left);
1021 } else {
1022 assert_eq!(left, initial_left);
1023 assert_eq!(right, initial_right);
1024 }
1025 }
1026
1027 #[kani::proof]
1028 fn prove_ct_oblivious_lookup_matches_public_index() {
1029 let table: [u8; 4] = kani::any();
1030 let fallback: u8 = kani::any();
1031 let index: usize = kani::any();
1032
1033 let selected = ct::oblivious_lookup(&table, ct::SecretIndex::new(index), &fallback);
1034
1035 if index < 4 {
1036 assert_eq!(selected, table[index]);
1037 } else {
1038 assert_eq!(selected, fallback);
1039 }
1040 }
1041
1042 #[kani::proof]
1043 fn prove_ct_select_slice_matches_choice() {
1044 let left: [u8; 4] = kani::any();
1045 let right: [u8; 4] = kani::any();
1046 let choice_byte: u8 = kani::any();
1047 let choice = ct::Choice::from_u8(choice_byte);
1048 let mut destination = [0u8; 4];
1049
1050 assert!(ct::select_slice(&mut destination, &left, &right, choice).is_ok());
1051
1052 if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1053 assert_eq!(destination, right);
1054 } else {
1055 assert_eq!(destination, left);
1056 }
1057 }
1058
1059 #[kani::proof]
1060 fn prove_ct_option_unwrap_or_matches_presence() {
1061 let value: u8 = kani::any();
1062 let fallback: u8 = kani::any();
1063 let presence_byte: u8 = kani::any();
1064 let presence = ct::Choice::from_u8(presence_byte);
1065 let option = ct::PublicCtOption::new(value, presence);
1066
1067 let selected = option.unwrap_or(&fallback);
1068
1069 if presence.declassify_u8("test or verification observes normalized choice") == 1 {
1070 assert_eq!(selected, value);
1071 } else {
1072 assert_eq!(selected, fallback);
1073 }
1074 }
1075
1076 #[kani::proof]
1077 fn prove_ct_option_and_or_match_presence_bits() {
1078 let left_value: u8 = kani::any();
1079 let right_value: u8 = kani::any();
1080 let fallback: u8 = kani::any();
1081 let left_presence_byte: u8 = kani::any();
1082 let right_presence_byte: u8 = kani::any();
1083 let left_presence = ct::Choice::from_u8(left_presence_byte);
1084 let right_presence = ct::Choice::from_u8(right_presence_byte);
1085 let left = ct::PublicCtOption::new(left_value, left_presence);
1086 let right = ct::PublicCtOption::new(right_value, right_presence);
1087
1088 let and_selected = left.and(right).unwrap_or(&fallback);
1089 let or_selected = left.or(right).unwrap_or(&fallback);
1090
1091 if left_presence.declassify_u8("test or verification observes normalized choice") == 1
1092 && right_presence.declassify_u8("test or verification observes normalized choice") == 1
1093 {
1094 assert_eq!(and_selected, right_value);
1095 } else {
1096 assert_eq!(and_selected, fallback);
1097 }
1098
1099 if left_presence.declassify_u8("test or verification observes normalized choice") == 1 {
1100 assert_eq!(or_selected, left_value);
1101 } else if right_presence.declassify_u8("test or verification observes normalized choice")
1102 == 1
1103 {
1104 assert_eq!(or_selected, right_value);
1105 } else {
1106 assert_eq!(or_selected, fallback);
1107 }
1108 }
1109
1110 #[kani::proof]
1111 fn prove_ct_result_unwrap_or_and_maps_match_success_bit() {
1112 let value: u8 = kani::any();
1113 let error: u8 = kani::any();
1114 let fallback: u8 = kani::any();
1115 let success_byte: u8 = kani::any();
1116 let success = ct::Choice::from_u8(success_byte);
1117 let result = ct::PublicCtResult::new(value, error, success);
1118
1119 let selected = result.unwrap_or(&fallback);
1120 let mapped = result.map(|inner| inner.wrapping_add(1));
1121 let mapped_error = result.map_err(|inner| inner.wrapping_add(1));
1122
1123 if success.declassify_u8("test or verification observes normalized choice") == 1 {
1124 assert_eq!(selected, value);
1125 assert_eq!(
1126 mapped.declassify("Kani exposes mapped success bit"),
1127 Ok(value.wrapping_add(1))
1128 );
1129 assert_eq!(
1130 mapped_error.declassify("Kani exposes mapped success bit"),
1131 Ok(value)
1132 );
1133 } else {
1134 assert_eq!(selected, fallback);
1135 assert_eq!(
1136 mapped.declassify("Kani exposes mapped error bit"),
1137 Err(error)
1138 );
1139 assert_eq!(
1140 mapped_error.declassify("Kani exposes mapped error bit"),
1141 Err(error.wrapping_add(1))
1142 );
1143 }
1144 }
1145
1146 #[kani::proof]
1147 fn prove_ct_option_and_result_conditional_select_match_choice() {
1148 let left_value: u8 = kani::any();
1149 let right_value: u8 = kani::any();
1150 let choice_byte: u8 = kani::any();
1151 let choice = ct::Choice::from_u8(choice_byte);
1152 let left_option = ct::PublicCtOption::some(left_value);
1153 let right_option = ct::PublicCtOption::some(right_value);
1154 let left_result = ct::PublicCtResult::new(left_value, 11u8, ct::Choice::TRUE);
1155 let right_result = ct::PublicCtResult::new(right_value, 22u8, ct::Choice::TRUE);
1156
1157 let selected_option =
1158 <ct::PublicCtOption<u8> as ct::ConditionallySelectable>::conditional_select(
1159 &left_option,
1160 &right_option,
1161 choice,
1162 );
1163 let selected_result =
1164 <ct::PublicCtResult<u8, u8> as ct::ConditionallySelectable>::conditional_select(
1165 &left_result,
1166 &right_result,
1167 choice,
1168 );
1169
1170 if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1171 assert_eq!(selected_option.unwrap_or(&0), right_value);
1172 assert_eq!(selected_result.unwrap_or(&0), right_value);
1173 } else {
1174 assert_eq!(selected_option.unwrap_or(&0), left_value);
1175 assert_eq!(selected_result.unwrap_or(&0), left_value);
1176 }
1177 }
1178
1179 #[kani::proof]
1180 fn prove_constant_time_eq_rejects_length_mismatch() {
1181 let left: [u8; 4] = kani::any();
1182 let right: [u8; 3] = kani::any();
1183
1184 assert!(!constant_time_eq_slices(&left, &right));
1185 }
1186
1187 #[kani::proof]
1188 fn prove_secret_bytes_replacement_commits_complete_new_value() {
1189 let initial: [u8; 4] = kani::any();
1190 let replacement: [u8; 4] = kani::any();
1191 let mut secret = SecretBytes::<4>::from_array(initial);
1192 let mut observed = [0_u8; 4];
1193
1194 secret.copy_from_slice(&replacement).unwrap();
1195 secret
1196 .export_to_slice("test exports bytes for verification output", &mut observed)
1197 .unwrap();
1198
1199 assert_eq!(observed, replacement);
1200 }
1201
1202 #[kani::proof]
1203 #[cfg(feature = "alloc")]
1204 fn prove_next_secret_capacity_never_under_allocates() {
1205 let current: usize = kani::any();
1206 let required: usize = kani::any();
1207
1208 let capacity = next_secret_capacity(current, required);
1209
1210 assert!(capacity >= required);
1211 assert!(capacity >= 8);
1212 }
1213}
1214
1215struct TemporaryBytes<'a, const N: usize> {
1216 bytes: &'a mut [u8; N],
1217}
1218
1219impl<const N: usize> Drop for TemporaryBytes<'_, N> {
1220 #[inline]
1221 fn drop(&mut self) {
1222 wipe::bytes(self.bytes);
1223 }
1224}
1225
1226pub(crate) fn expose_array_copy<const N: usize, R>(
1227 source: &[u8; N],
1228 inspect: impl FnOnce(&[u8; N]) -> R,
1229) -> R {
1230 let mut temporary = [0; N];
1231 temporary.copy_from_slice(source);
1232 compiler_fence(Ordering::SeqCst);
1233 let guard = TemporaryBytes {
1234 bytes: &mut temporary,
1235 };
1236 let result = inspect(guard.bytes);
1237 wipe::bytes(guard.bytes);
1240 result
1241}
1242
1243#[cfg(all(test, feature = "std"))]
1244mod temporary_bytes_tests {
1245 use super::TemporaryBytes;
1246 use std::panic::{catch_unwind, AssertUnwindSafe};
1247
1248 #[test]
1249 fn temporary_bytes_clear_during_unwind() {
1250 let mut bytes = [7_u8; 32];
1251
1252 let result = catch_unwind(AssertUnwindSafe(|| {
1253 let _guard = TemporaryBytes { bytes: &mut bytes };
1254 panic!("exercise temporary cleanup");
1255 }));
1256
1257 assert!(result.is_err());
1258 assert_eq!(bytes, [0; 32]);
1259 }
1260}
1261
1262pub struct SecretBytes<const N: usize> {
1282 bytes: [u8; N],
1283}
1284
1285impl<const N: usize> SecretBytes<N> {
1286 #[must_use]
1288 #[inline]
1289 pub const fn zeroed() -> Self {
1290 Self { bytes: [0; N] }
1291 }
1292
1293 #[must_use]
1299 #[inline]
1300 pub fn from_array(mut bytes: [u8; N]) -> Self {
1301 let mut secret = Self::zeroed();
1302 for (index, byte) in bytes.iter().copied().enumerate() {
1303 secret.store(index, byte);
1304 }
1305 secret.after_secret_write();
1306 wipe::bytes(&mut bytes);
1307 secret
1308 }
1309
1310 #[must_use]
1314 #[inline]
1315 pub fn from_fn(mut make_byte: impl FnMut(usize) -> u8) -> Self {
1316 let mut secret = Self::zeroed();
1317 let mut index = 0;
1318 while index < N {
1319 secret.store(index, make_byte(index));
1320 index += 1;
1321 }
1322 secret.after_secret_write();
1323 secret
1324 }
1325
1326 #[inline]
1332 pub fn try_from_fn<E>(mut make_byte: impl FnMut(usize) -> Result<u8, E>) -> Result<Self, E> {
1333 let mut secret = Self::zeroed();
1334 let mut index = 0;
1335 while index < N {
1336 let byte = make_byte(index)?;
1337 secret.store(index, byte);
1338 index += 1;
1339 }
1340 secret.after_secret_write();
1341 Ok(secret)
1342 }
1343
1344 #[must_use]
1346 #[inline]
1347 pub const fn len(&self) -> usize {
1348 N
1349 }
1350
1351 #[must_use]
1353 #[inline]
1354 pub const fn is_empty(&self) -> bool {
1355 N == 0
1356 }
1357
1358 #[inline]
1360 pub fn copy_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
1361 if source.len() != N {
1362 return Err(LengthError {
1363 expected: N,
1364 actual: source.len(),
1365 });
1366 }
1367
1368 for (index, byte) in source.iter().copied().enumerate() {
1369 self.store(index, byte);
1370 }
1371 self.after_secret_write();
1372 Ok(())
1373 }
1374
1375 #[inline]
1381 pub fn replace_from_array(&mut self, mut bytes: [u8; N]) {
1382 for (index, byte) in bytes.iter().copied().enumerate() {
1383 self.store(index, byte);
1384 }
1385 self.after_secret_write();
1386 wipe::bytes(&mut bytes);
1387 }
1388
1389 #[inline]
1396 pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
1397 let mut replacement = Self::from_fn(make_byte);
1398 self.secure_clear();
1399 core::mem::swap(self, &mut replacement);
1400 }
1401
1402 #[inline]
1409 pub fn try_replace_from_fn<E>(
1410 &mut self,
1411 make_byte: impl FnMut(usize) -> Result<u8, E>,
1412 ) -> Result<(), E> {
1413 let mut replacement = Self::try_from_fn(make_byte)?;
1414 self.secure_clear();
1415 core::mem::swap(self, &mut replacement);
1416 Ok(())
1417 }
1418
1419 #[inline]
1426 pub fn transform(&mut self, edit: impl FnOnce(&mut [u8; N])) {
1427 edit(&mut self.bytes);
1428 self.after_secret_write();
1429 }
1430
1431 #[inline]
1437 pub fn try_transform<E>(
1438 &mut self,
1439 edit: impl FnOnce(&mut [u8; N]) -> Result<(), E>,
1440 ) -> Result<(), E> {
1441 edit(&mut self.bytes)?;
1442 self.after_secret_write();
1443 Ok(())
1444 }
1445
1446 #[must_use]
1454 #[inline]
1455 pub fn derive<const M: usize>(
1456 &self,
1457 derive: impl FnOnce(&[u8; N], &mut [u8; M]),
1458 ) -> SecretBytes<M> {
1459 let mut output = SecretBytes::<M>::zeroed();
1460 derive(&self.bytes, &mut output.bytes);
1461 output.after_secret_write();
1462 output
1463 }
1464
1465 #[inline]
1470 pub fn try_derive<const M: usize, E>(
1471 &self,
1472 derive: impl FnOnce(&[u8; N], &mut [u8; M]) -> Result<(), E>,
1473 ) -> Result<SecretBytes<M>, E> {
1474 let mut output = SecretBytes::<M>::zeroed();
1475 derive(&self.bytes, &mut output.bytes)?;
1476 output.after_secret_write();
1477 Ok(output)
1478 }
1479
1480 #[inline]
1486 pub fn export_to_slice(
1487 &self,
1488 reason: &'static str,
1489 destination: &mut [u8],
1490 ) -> Result<(), LengthError> {
1491 black_box(reason);
1492 if destination.len() != N {
1493 return Err(LengthError {
1494 expected: N,
1495 actual: destination.len(),
1496 });
1497 }
1498
1499 for (index, byte) in destination.iter_mut().enumerate() {
1500 *byte = self.load(index);
1501 }
1502 compiler_fence(Ordering::SeqCst);
1503 black_box(destination);
1504 Ok(())
1505 }
1506
1507 #[must_use]
1513 #[inline]
1514 pub fn export_byte(&self, reason: &'static str, index: usize) -> Option<u8> {
1515 black_box(reason);
1516 if index < N {
1517 Some(self.load(index))
1518 } else {
1519 None
1520 }
1521 }
1522
1523 #[inline]
1525 pub fn write_byte(&mut self, index: usize, value: u8) -> Result<(), LengthError> {
1526 if index >= N {
1527 return Err(LengthError {
1528 expected: N,
1529 actual: index.saturating_add(1),
1530 });
1531 }
1532
1533 self.store(index, value);
1534 self.after_secret_write();
1535 Ok(())
1536 }
1537
1538 #[inline]
1555 pub fn expose_secret<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R {
1556 inspect(&self.bytes)
1557 }
1558
1559 #[inline]
1569 pub fn export_secret_copy<R>(
1570 &self,
1571 reason: &'static str,
1572 inspect: impl FnOnce(&[u8; N]) -> R,
1573 ) -> R {
1574 black_box(reason);
1575 expose_array_copy(&self.bytes, inspect)
1576 }
1577
1578 #[must_use]
1589 #[inline]
1590 pub fn constant_time_eq(&self, other: &[u8]) -> bool {
1591 constant_time_eq_slices(self.bytes.as_slice(), other)
1592 }
1593
1594 #[must_use]
1599 #[inline]
1600 pub fn constant_time_eq_secret(&self, other: &Self) -> bool {
1601 constant_time_eq_equal_len(self.bytes.as_slice(), other.bytes.as_slice())
1602 }
1603
1604 #[inline(never)]
1606 pub fn secure_clear(&mut self) {
1607 wipe_backend::erase(self.bytes.as_mut_ptr(), N);
1608 }
1609
1610 #[cfg(feature = "multi-pass-clear")]
1616 #[inline(never)]
1617 pub fn secure_clear_multi_pass(&mut self) {
1618 wipe_backend::erase_multi_pass(self.bytes.as_mut_ptr(), N);
1619 }
1620
1621 #[inline]
1626 pub fn into_cleared(mut self) {
1627 self.secure_clear();
1628 }
1629
1630 #[cfg(feature = "cache-flush")]
1633 #[inline(never)]
1634 pub fn secure_clear_and_flush(
1635 &mut self,
1636 ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
1637 crate::cache_flush::cache_flush_sanitize_bytes(self.bytes.as_mut_slice())
1638 }
1639
1640 #[inline]
1641 fn load(&self, index: usize) -> u8 {
1642 self.bytes[index]
1643 }
1644
1645 #[inline]
1646 pub(crate) fn store(&mut self, index: usize, value: u8) {
1647 self.bytes[index] = value;
1648 }
1649
1650 #[inline]
1651 pub(crate) fn after_secret_write(&self) {
1652 compiler_fence(Ordering::SeqCst);
1653 }
1654}
1655
1656impl<const N: usize> Default for SecretBytes<N> {
1657 #[inline]
1658 fn default() -> Self {
1659 Self::zeroed()
1660 }
1661}
1662
1663impl<const N: usize> Drop for SecretBytes<N> {
1664 #[inline]
1665 fn drop(&mut self) {
1666 self.secure_clear();
1667 }
1668}
1669
1670impl<const N: usize> SecureSanitize for SecretBytes<N> {
1671 #[inline]
1672 fn secure_sanitize(&mut self) {
1673 self.secure_clear();
1674 }
1675}
1676
1677impl<const N: usize> StableSharedSecretStorage for SecretBytes<N> {}
1678impl<const N: usize> StableMutableSecretStorage for SecretBytes<N> {}
1679
1680impl<const N: usize> fmt::Debug for SecretBytes<N> {
1681 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1682 formatter
1683 .debug_struct("SecretBytes")
1684 .field("len", &N)
1685 .field("contents", &"<redacted>")
1686 .finish()
1687 }
1688}
1689
1690impl<const N: usize> ct::ConstantTimeEq for SecretBytes<N> {
1691 #[inline]
1692 fn ct_eq(&self, other: &Self) -> ct::Choice {
1693 ct::eq_fixed(&self.bytes, &other.bytes)
1694 }
1695}
1696
1697impl<const N: usize> ct::ConstantTimeEq<[u8]> for SecretBytes<N> {
1698 #[inline]
1699 fn ct_eq(&self, other: &[u8]) -> ct::Choice {
1700 ct::eq_public_len(self.bytes.as_slice(), other)
1701 }
1702}
1703
1704impl<const N: usize> ct::ConditionallySelectable for SecretBytes<N> {
1705 #[inline]
1706 fn conditional_select(left: &Self, right: &Self, choice: ct::Choice) -> Self {
1707 let mut output = Self::zeroed();
1708 let mut index = 0usize;
1709 while index < N {
1710 output.bytes[index] = <u8 as ct::ConditionallySelectable>::conditional_select(
1711 &left.bytes[index],
1712 &right.bytes[index],
1713 choice,
1714 );
1715 index += 1;
1716 }
1717 output.after_secret_write();
1718 output
1719 }
1720}
1721
1722#[cfg(feature = "split-secret")]
1724#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1725pub enum SplitSecretError {
1726 TooFewShares,
1728 TrivialMask,
1733}
1734
1735#[cfg(feature = "split-secret")]
1736impl fmt::Display for SplitSecretError {
1737 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1738 match self {
1739 Self::TooFewShares => formatter.write_str("split secrets require at least two shares"),
1740 Self::TrivialMask => formatter.write_str(
1741 "split-secret mask shares are trivially constant; use cryptographically random mask bytes",
1742 ),
1743 }
1744 }
1745}
1746
1747#[cfg(all(feature = "split-secret", feature = "std"))]
1748impl std::error::Error for SplitSecretError {}
1749
1750#[cfg(feature = "split-secret")]
1766pub struct SplitSecretBytes<const N: usize, const SHARES: usize> {
1767 shares: [SecretBytes<N>; SHARES],
1768}
1769
1770#[cfg(feature = "split-secret")]
1771impl<const N: usize, const SHARES: usize> SplitSecretBytes<N, SHARES> {
1772 pub fn from_array_with_generator(
1779 mut secret: [u8; N],
1780 mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1781 ) -> Result<Self, SplitSecretError> {
1782 let guard = TemporaryBytes { bytes: &mut secret };
1783
1784 if SHARES < 2 {
1785 return Err(SplitSecretError::TooFewShares);
1786 }
1787
1788 let split = Self::from_secret_bytes_with_generator(guard.bytes, &mut make_mask_byte)?;
1789 wipe::bytes(guard.bytes);
1790 Ok(split)
1791 }
1792
1793 pub fn from_secret_with_generator(
1799 secret: &SecretBytes<N>,
1800 mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1801 ) -> Result<Self, SplitSecretError> {
1802 if SHARES < 2 {
1803 return Err(SplitSecretError::TooFewShares);
1804 }
1805
1806 Self::from_secret_bytes_with_generator(&secret.bytes, &mut make_mask_byte)
1807 }
1808
1809 pub fn from_secret_consuming_with_generator(
1812 mut secret: SecretBytes<N>,
1813 mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1814 ) -> Result<Self, SplitSecretError> {
1815 let split = Self::from_secret_bytes_with_generator(&secret.bytes, &mut make_mask_byte)?;
1816 secret.secure_clear();
1817 Ok(split)
1818 }
1819
1820 #[must_use]
1822 pub fn reconstruct(&self) -> SecretBytes<N> {
1823 let mut output = SecretBytes::<N>::zeroed();
1824 let mut byte_index = 0;
1825 while byte_index < N {
1826 let mut value = 0;
1827 let mut share_index = 0;
1828 while share_index < SHARES {
1829 value ^= self.shares[share_index].load(byte_index);
1830 share_index += 1;
1831 }
1832 output.store(byte_index, value);
1833 byte_index += 1;
1834 }
1835 output.after_secret_write();
1836 output
1837 }
1838
1839 #[inline]
1847 pub fn expose_secret_copy<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R {
1848 let reconstructed = self.reconstruct();
1849 reconstructed.expose_secret(inspect)
1850 }
1851
1852 #[must_use]
1854 #[inline]
1855 pub const fn shares(&self) -> &[SecretBytes<N>; SHARES] {
1856 &self.shares
1857 }
1858
1859 #[must_use]
1861 #[inline]
1862 pub fn share(&self, index: usize) -> Option<&SecretBytes<N>> {
1863 self.shares.get(index)
1864 }
1865
1866 #[must_use]
1868 #[inline]
1869 pub fn into_shares(self) -> [SecretBytes<N>; SHARES] {
1870 self.shares
1871 }
1872
1873 fn from_secret_bytes_with_generator(
1874 secret: &[u8; N],
1875 make_mask_byte: &mut impl FnMut(usize, usize) -> u8,
1876 ) -> Result<Self, SplitSecretError> {
1877 if SHARES < 2 {
1878 return Err(SplitSecretError::TooFewShares);
1879 }
1880
1881 let mut shares = core::array::from_fn(|_| SecretBytes::<N>::zeroed());
1882
1883 let mut byte_index = 0;
1884 while byte_index < N {
1885 let mut accumulator = 0;
1886 let mut share_index = 0;
1887 while share_index + 1 < SHARES {
1888 let mask = make_mask_byte(share_index, byte_index);
1889 shares[share_index].store(byte_index, mask);
1890 accumulator ^= mask;
1891 share_index += 1;
1892 }
1893
1894 shares[SHARES - 1].store(byte_index, secret[byte_index] ^ accumulator);
1895 byte_index += 1;
1896 }
1897
1898 let trivial_mask = u8::from(Self::mask_shares_are_trivially_constant(&shares))
1899 | u8::from(Self::mask_accumulator_is_trivial(&shares));
1900 if trivial_mask != 0 {
1901 shares.secure_sanitize();
1902 return Err(SplitSecretError::TrivialMask);
1903 }
1904
1905 for share in shares.iter() {
1906 share.after_secret_write();
1907 }
1908
1909 Ok(Self { shares })
1910 }
1911
1912 #[inline]
1913 fn mask_shares_are_trivially_constant(shares: &[SecretBytes<N>; SHARES]) -> bool {
1914 if N < 2 {
1915 return false;
1916 }
1917
1918 let mut any_trivial = false;
1919 let mut share_index = 0;
1920 while share_index + 1 < SHARES {
1921 let first = shares[share_index].load(0);
1922 let mut byte_index = 1;
1923 let mut all_same = true;
1924 while byte_index < N {
1925 let diff = shares[share_index].load(byte_index) ^ first;
1926 all_same &= diff == 0;
1927 byte_index += 1;
1928 }
1929
1930 any_trivial |= all_same;
1931 share_index += 1;
1932 }
1933
1934 any_trivial
1935 }
1936
1937 #[inline]
1938 fn mask_accumulator_is_trivial(shares: &[SecretBytes<N>; SHARES]) -> bool {
1939 if N == 0 || SHARES < 2 {
1940 return false;
1941 }
1942
1943 let mut first_accumulator = 0u8;
1944 let mut share_index = 0;
1945 while share_index + 1 < SHARES {
1946 first_accumulator ^= shares[share_index].load(0);
1947 share_index += 1;
1948 }
1949
1950 let mut all_same = true;
1951 let mut byte_index = 1;
1952 while byte_index < N {
1953 let mut accumulator = 0u8;
1954 let mut share_index = 0;
1955 while share_index + 1 < SHARES {
1956 accumulator ^= shares[share_index].load(byte_index);
1957 share_index += 1;
1958 }
1959
1960 all_same &= accumulator == first_accumulator;
1961 byte_index += 1;
1962 }
1963
1964 if N == 1 {
1965 first_accumulator == 0
1966 } else {
1967 all_same
1968 }
1969 }
1970}
1971
1972#[cfg(feature = "split-secret")]
1973impl<const N: usize, const SHARES: usize> SecureSanitize for SplitSecretBytes<N, SHARES> {
1974 #[inline]
1975 fn secure_sanitize(&mut self) {
1976 self.shares.secure_sanitize();
1977 }
1978}
1979
1980#[cfg(feature = "split-secret")]
1981impl<const N: usize, const SHARES: usize> StableSharedSecretStorage
1982 for SplitSecretBytes<N, SHARES>
1983{
1984}
1985
1986#[cfg(feature = "split-secret")]
1987impl<const N: usize, const SHARES: usize> StableMutableSecretStorage
1988 for SplitSecretBytes<N, SHARES>
1989{
1990}
1991
1992#[cfg(feature = "split-secret")]
1993impl<const N: usize, const SHARES: usize> fmt::Debug for SplitSecretBytes<N, SHARES> {
1994 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1995 formatter
1996 .debug_struct("SplitSecretBytes")
1997 .field("len", &N)
1998 .field("shares", &SHARES)
1999 .field("contents", &"<redacted>")
2000 .finish()
2001 }
2002}
2003
2004#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2006pub struct SecretExpiredError;
2007
2008impl fmt::Display for SecretExpiredError {
2009 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2010 formatter.write_str("secret has expired")
2011 }
2012}
2013
2014#[cfg(feature = "std")]
2015impl std::error::Error for SecretExpiredError {}
2016
2017#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2019pub enum ExpiringSecretError {
2020 Expired(SecretExpiredError),
2022 Length(LengthError),
2024}
2025
2026impl fmt::Display for ExpiringSecretError {
2027 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2028 match self {
2029 Self::Expired(error) => error.fmt(formatter),
2030 Self::Length(error) => error.fmt(formatter),
2031 }
2032 }
2033}
2034
2035#[cfg(feature = "std")]
2036impl std::error::Error for ExpiringSecretError {
2037 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2038 match self {
2039 Self::Expired(error) => Some(error),
2040 Self::Length(error) => Some(error),
2041 }
2042 }
2043}
2044
2045impl From<SecretExpiredError> for ExpiringSecretError {
2046 #[inline]
2047 fn from(error: SecretExpiredError) -> Self {
2048 Self::Expired(error)
2049 }
2050}
2051
2052impl From<LengthError> for ExpiringSecretError {
2053 #[inline]
2054 fn from(error: LengthError) -> Self {
2055 Self::Length(error)
2056 }
2057}
2058
2059pub trait MonotonicClock {
2065 fn now(&self) -> u64;
2067}
2068
2069impl<C: MonotonicClock + ?Sized> MonotonicClock for &C {
2070 #[inline]
2071 fn now(&self) -> u64 {
2072 (**self).now()
2073 }
2074}
2075
2076pub struct MonotonicExpiringSecretBytes<const N: usize, C: MonotonicClock> {
2099 inner: SecretBytes<N>,
2100 clock: C,
2101 created_at: u64,
2102 max_age: u64,
2103}
2104
2105impl<const N: usize, C: MonotonicClock> MonotonicExpiringSecretBytes<N, C> {
2106 #[must_use]
2113 #[inline]
2114 pub fn zeroed(clock: C, max_age: u64) -> Self {
2115 let created_at = clock.now();
2116 Self {
2117 inner: SecretBytes::zeroed(),
2118 clock,
2119 created_at,
2120 max_age,
2121 }
2122 }
2123
2124 #[must_use]
2127 #[inline]
2128 pub fn from_array(bytes: [u8; N], clock: C, max_age: u64) -> Self {
2129 let created_at = clock.now();
2130 Self {
2131 inner: SecretBytes::from_array(bytes),
2132 clock,
2133 created_at,
2134 max_age,
2135 }
2136 }
2137
2138 #[must_use]
2140 #[inline]
2141 pub fn from_fn(clock: C, max_age: u64, make_byte: impl FnMut(usize) -> u8) -> Self {
2142 let created_at = clock.now();
2143 Self {
2144 inner: SecretBytes::from_fn(make_byte),
2145 clock,
2146 created_at,
2147 max_age,
2148 }
2149 }
2150
2151 #[inline]
2156 pub fn try_from_fn<E>(
2157 clock: C,
2158 max_age: u64,
2159 make_byte: impl FnMut(usize) -> Result<u8, E>,
2160 ) -> Result<Self, E> {
2161 let created_at = clock.now();
2162 Ok(Self {
2163 inner: SecretBytes::try_from_fn(make_byte)?,
2164 clock,
2165 created_at,
2166 max_age,
2167 })
2168 }
2169
2170 #[must_use]
2172 #[inline]
2173 pub fn from_secret(secret: SecretBytes<N>, clock: C, max_age: u64) -> Self {
2174 let created_at = clock.now();
2175 Self {
2176 inner: secret,
2177 clock,
2178 created_at,
2179 max_age,
2180 }
2181 }
2182
2183 #[must_use]
2185 #[inline]
2186 pub const fn len(&self) -> usize {
2187 N
2188 }
2189
2190 #[must_use]
2192 #[inline]
2193 pub const fn is_empty(&self) -> bool {
2194 N == 0
2195 }
2196
2197 #[must_use]
2201 #[inline]
2202 pub const fn max_age_ticks(&self) -> u64 {
2203 self.max_age
2204 }
2205
2206 #[must_use]
2211 #[inline]
2212 pub fn age_ticks(&self) -> u64 {
2213 self.clock.now().saturating_sub(self.created_at)
2214 }
2215
2216 #[must_use]
2218 #[inline]
2219 pub fn is_expired(&self) -> bool {
2220 self.age_ticks() >= self.max_age
2221 }
2222
2223 #[must_use]
2225 #[inline]
2226 pub const fn clock(&self) -> &C {
2227 &self.clock
2228 }
2229
2230 #[inline]
2235 pub fn replace_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
2236 if source.len() != N {
2237 if self.is_expired() {
2238 self.inner.secure_clear();
2239 }
2240 return Err(LengthError {
2241 expected: N,
2242 actual: source.len(),
2243 });
2244 }
2245
2246 let mut replacement = SecretBytes::<N>::zeroed();
2247 replacement.copy_from_slice(source)?;
2248 self.inner.secure_clear();
2249 self.inner = replacement;
2250 self.created_at = self.clock.now();
2251 Ok(())
2252 }
2253
2254 #[inline]
2257 pub fn replace_from_array(&mut self, bytes: [u8; N]) {
2258 let replacement = SecretBytes::from_array(bytes);
2259 self.inner.secure_clear();
2260 self.inner = replacement;
2261 self.created_at = self.clock.now();
2262 }
2263
2264 #[inline]
2266 pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2267 let expired = self.is_expired();
2268 if expired {
2269 self.inner.secure_clear();
2270 }
2271
2272 let replacement = SecretBytes::from_fn(make_byte);
2273 if !expired {
2274 self.inner.secure_clear();
2275 }
2276 self.inner = replacement;
2277 self.created_at = self.clock.now();
2278 }
2279
2280 #[inline]
2287 pub fn try_replace_from_fn<E>(
2288 &mut self,
2289 make_byte: impl FnMut(usize) -> Result<u8, E>,
2290 ) -> Result<(), E> {
2291 let expired = self.is_expired();
2292 if expired {
2293 self.inner.secure_clear();
2294 }
2295
2296 let replacement = SecretBytes::try_from_fn(make_byte)?;
2297 if !expired {
2298 self.inner.secure_clear();
2299 }
2300 self.inner = replacement;
2301 self.created_at = self.clock.now();
2302 Ok(())
2303 }
2304
2305 #[inline]
2308 pub fn try_export_to_slice(
2309 &mut self,
2310 reason: &'static str,
2311 destination: &mut [u8],
2312 ) -> Result<(), ExpiringSecretError> {
2313 self.enforce_live()?;
2314 self.inner
2315 .export_to_slice(reason, destination)
2316 .map_err(Into::into)
2317 }
2318
2319 #[inline]
2321 pub fn try_expose_secret<R>(
2322 &mut self,
2323 inspect: impl FnOnce(&[u8; N]) -> R,
2324 ) -> Result<R, SecretExpiredError> {
2325 self.enforce_live()?;
2326 Ok(self.inner.expose_secret(inspect))
2327 }
2328
2329 #[inline]
2334 pub fn try_export_secret_copy<R>(
2335 &mut self,
2336 reason: &'static str,
2337 inspect: impl FnOnce(&[u8; N]) -> R,
2338 ) -> Result<R, SecretExpiredError> {
2339 self.enforce_live()?;
2340 Ok(self.inner.export_secret_copy(reason, inspect))
2341 }
2342
2343 #[inline]
2347 pub fn try_constant_time_eq(&mut self, other: &[u8]) -> Result<bool, SecretExpiredError> {
2348 self.enforce_live()?;
2349 Ok(self.inner.constant_time_eq(other))
2350 }
2351
2352 #[inline(never)]
2354 pub fn secure_clear(&mut self) {
2355 self.inner.secure_clear();
2356 }
2357
2358 #[inline]
2360 pub fn into_cleared(mut self) {
2361 self.secure_clear();
2362 }
2363
2364 #[inline]
2365 fn enforce_live(&mut self) -> Result<(), SecretExpiredError> {
2366 if self.is_expired() {
2367 self.inner.secure_clear();
2368 Err(SecretExpiredError)
2369 } else {
2370 Ok(())
2371 }
2372 }
2373}
2374
2375impl<const N: usize, C: MonotonicClock> Drop for MonotonicExpiringSecretBytes<N, C> {
2376 #[inline]
2377 fn drop(&mut self) {
2378 self.secure_clear();
2379 }
2380}
2381
2382impl<const N: usize, C: MonotonicClock> SecureSanitize for MonotonicExpiringSecretBytes<N, C> {
2383 #[inline]
2384 fn secure_sanitize(&mut self) {
2385 self.secure_clear();
2386 }
2387}
2388
2389impl<const N: usize, C: MonotonicClock> fmt::Debug for MonotonicExpiringSecretBytes<N, C> {
2390 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2391 formatter
2392 .debug_struct("MonotonicExpiringSecretBytes")
2393 .field("len", &N)
2394 .field("age_ticks", &self.age_ticks())
2395 .field("max_age_ticks", &self.max_age)
2396 .field("contents", &"<redacted>")
2397 .finish()
2398 }
2399}
2400
2401#[cfg(feature = "std")]
2411pub struct ExpiringSecretBytes<const N: usize> {
2412 inner: SecretBytes<N>,
2413 created_at: std::time::Instant,
2414 max_age: std::time::Duration,
2415}
2416
2417#[cfg(feature = "std")]
2418impl<const N: usize> ExpiringSecretBytes<N> {
2419 #[must_use]
2421 #[inline]
2422 pub fn zeroed(max_age: std::time::Duration) -> Self {
2423 Self {
2424 inner: SecretBytes::zeroed(),
2425 created_at: std::time::Instant::now(),
2426 max_age,
2427 }
2428 }
2429
2430 #[must_use]
2433 #[inline]
2434 pub fn from_array(bytes: [u8; N], max_age: std::time::Duration) -> Self {
2435 Self {
2436 inner: SecretBytes::from_array(bytes),
2437 created_at: std::time::Instant::now(),
2438 max_age,
2439 }
2440 }
2441
2442 #[must_use]
2444 #[inline]
2445 pub fn from_fn(max_age: std::time::Duration, make_byte: impl FnMut(usize) -> u8) -> Self {
2446 Self {
2447 inner: SecretBytes::from_fn(make_byte),
2448 created_at: std::time::Instant::now(),
2449 max_age,
2450 }
2451 }
2452
2453 #[inline]
2458 pub fn try_from_fn<E>(
2459 max_age: std::time::Duration,
2460 make_byte: impl FnMut(usize) -> Result<u8, E>,
2461 ) -> Result<Self, E> {
2462 Ok(Self {
2463 inner: SecretBytes::try_from_fn(make_byte)?,
2464 created_at: std::time::Instant::now(),
2465 max_age,
2466 })
2467 }
2468
2469 #[must_use]
2471 #[inline]
2472 pub fn from_secret(secret: SecretBytes<N>, max_age: std::time::Duration) -> Self {
2473 Self {
2474 inner: secret,
2475 created_at: std::time::Instant::now(),
2476 max_age,
2477 }
2478 }
2479
2480 #[must_use]
2482 #[inline]
2483 pub const fn len(&self) -> usize {
2484 N
2485 }
2486
2487 #[must_use]
2489 #[inline]
2490 pub const fn is_empty(&self) -> bool {
2491 N == 0
2492 }
2493
2494 #[must_use]
2496 #[inline]
2497 pub const fn max_age(&self) -> std::time::Duration {
2498 self.max_age
2499 }
2500
2501 #[must_use]
2503 #[inline]
2504 pub fn age(&self) -> std::time::Duration {
2505 self.created_at.elapsed()
2506 }
2507
2508 #[must_use]
2510 #[inline]
2511 pub fn is_expired(&self) -> bool {
2512 self.age() >= self.max_age
2513 }
2514
2515 #[inline]
2520 pub fn replace_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
2521 if source.len() != N {
2522 if self.is_expired() {
2523 self.inner.secure_clear();
2524 }
2525 return Err(LengthError {
2526 expected: N,
2527 actual: source.len(),
2528 });
2529 }
2530
2531 let mut replacement = SecretBytes::<N>::zeroed();
2532 replacement.copy_from_slice(source)?;
2533 self.inner.secure_clear();
2534 self.inner = replacement;
2535 self.created_at = std::time::Instant::now();
2536 Ok(())
2537 }
2538
2539 #[inline]
2545 pub fn replace_from_array(&mut self, bytes: [u8; N]) {
2546 let replacement = SecretBytes::from_array(bytes);
2547 self.inner.secure_clear();
2548 self.inner = replacement;
2549 self.created_at = std::time::Instant::now();
2550 }
2551
2552 #[inline]
2558 pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2559 let expired = self.is_expired();
2560 if expired {
2561 self.inner.secure_clear();
2562 }
2563
2564 let replacement = SecretBytes::from_fn(make_byte);
2565 if !expired {
2566 self.inner.secure_clear();
2567 }
2568 self.inner = replacement;
2569 self.created_at = std::time::Instant::now();
2570 }
2571
2572 #[inline]
2579 pub fn try_replace_from_fn<E>(
2580 &mut self,
2581 make_byte: impl FnMut(usize) -> Result<u8, E>,
2582 ) -> Result<(), E> {
2583 let expired = self.is_expired();
2584 if expired {
2585 self.inner.secure_clear();
2586 }
2587
2588 let replacement = SecretBytes::try_from_fn(make_byte)?;
2589 if !expired {
2590 self.inner.secure_clear();
2591 }
2592 self.inner = replacement;
2593 self.created_at = std::time::Instant::now();
2594 Ok(())
2595 }
2596
2597 #[inline]
2600 pub fn try_export_to_slice(
2601 &mut self,
2602 reason: &'static str,
2603 destination: &mut [u8],
2604 ) -> Result<(), ExpiringSecretError> {
2605 self.enforce_live()?;
2606 self.inner
2607 .export_to_slice(reason, destination)
2608 .map_err(Into::into)
2609 }
2610
2611 #[inline]
2613 pub fn try_expose_secret<R>(
2614 &mut self,
2615 inspect: impl FnOnce(&[u8; N]) -> R,
2616 ) -> Result<R, SecretExpiredError> {
2617 self.enforce_live()?;
2618 Ok(self.inner.expose_secret(inspect))
2619 }
2620
2621 #[inline]
2625 pub fn try_export_secret_copy<R>(
2626 &mut self,
2627 reason: &'static str,
2628 inspect: impl FnOnce(&[u8; N]) -> R,
2629 ) -> Result<R, SecretExpiredError> {
2630 self.enforce_live()?;
2631 Ok(self.inner.export_secret_copy(reason, inspect))
2632 }
2633
2634 #[inline]
2641 pub fn try_constant_time_eq(&mut self, other: &[u8]) -> Result<bool, SecretExpiredError> {
2642 self.enforce_live()?;
2643 Ok(self.inner.constant_time_eq(other))
2644 }
2645
2646 #[inline(never)]
2648 pub fn secure_clear(&mut self) {
2649 self.inner.secure_clear();
2650 }
2651
2652 #[inline]
2657 pub fn into_cleared(mut self) {
2658 self.secure_clear();
2659 }
2660
2661 #[inline]
2662 fn enforce_live(&mut self) -> Result<(), SecretExpiredError> {
2663 if self.is_expired() {
2664 self.inner.secure_clear();
2665 Err(SecretExpiredError)
2666 } else {
2667 Ok(())
2668 }
2669 }
2670}
2671
2672#[cfg(feature = "std")]
2673impl<const N: usize> Drop for ExpiringSecretBytes<N> {
2674 #[inline]
2675 fn drop(&mut self) {
2676 self.secure_clear();
2677 }
2678}
2679
2680#[cfg(feature = "std")]
2681impl<const N: usize> SecureSanitize for ExpiringSecretBytes<N> {
2682 #[inline]
2683 fn secure_sanitize(&mut self) {
2684 self.secure_clear();
2685 }
2686}
2687
2688#[cfg(feature = "std")]
2689impl<const N: usize> StableSharedSecretStorage for ExpiringSecretBytes<N> {}
2690
2691#[cfg(feature = "std")]
2692impl<const N: usize> StableMutableSecretStorage for ExpiringSecretBytes<N> {}
2693
2694#[cfg(feature = "std")]
2695impl<const N: usize> fmt::Debug for ExpiringSecretBytes<N> {
2696 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2697 formatter
2698 .debug_struct("ExpiringSecretBytes")
2699 .field("len", &N)
2700 .field("max_age", &self.max_age)
2701 .field("contents", &"<redacted>")
2702 .finish()
2703 }
2704}
2705
2706#[cfg(feature = "alloc")]
2726pub struct SecretBoxBytes {
2727 pub(crate) inner: Vec<u8>,
2728}
2729
2730#[cfg(feature = "alloc")]
2731impl SecretBoxBytes {
2732 #[must_use]
2739 #[inline]
2740 pub fn zeroed(len: usize) -> Self {
2741 Self {
2742 inner: alloc::vec![0; len],
2743 }
2744 }
2745
2746 #[inline]
2752 pub fn try_zeroed(len: usize, maximum: usize) -> Result<Self, SecretBoxBytesBuildError> {
2753 if len > maximum {
2754 return Err(SecretBoxBytesBuildError::TooLong {
2755 maximum,
2756 actual: len,
2757 });
2758 }
2759
2760 let mut inner = Vec::new();
2761 inner
2762 .try_reserve_exact(len)
2763 .map_err(SecretBoxBytesBuildError::Allocation)?;
2764 inner.resize(len, 0);
2765 Ok(Self { inner })
2766 }
2767
2768 #[must_use]
2773 #[inline]
2774 pub fn from_boxed_slice(inner: Box<[u8]>) -> Self {
2775 Self {
2776 inner: inner.into_vec(),
2777 }
2778 }
2779
2780 #[must_use]
2786 #[inline]
2787 pub fn from_slice(bytes: &[u8]) -> Self {
2788 Self {
2789 inner: Vec::from(bytes),
2790 }
2791 }
2792
2793 #[inline]
2795 pub fn try_from_slice(bytes: &[u8], maximum: usize) -> Result<Self, SecretBoxBytesBuildError> {
2796 let mut secret = Self::try_zeroed(bytes.len(), maximum)?;
2797 secret.inner.copy_from_slice(bytes);
2798 Ok(secret)
2799 }
2800
2801 #[must_use]
2808 #[inline]
2809 pub fn from_fn(len: usize, mut make_byte: impl FnMut(usize) -> u8) -> Self {
2810 let mut secret = Self::zeroed(len);
2811 let mut index = 0;
2812 while index < len {
2813 secret.inner[index] = make_byte(index);
2814 index += 1;
2815 }
2816 secret
2817 }
2818
2819 #[inline]
2827 pub fn try_from_fn<E>(
2828 len: usize,
2829 mut make_byte: impl FnMut(usize) -> Result<u8, E>,
2830 ) -> Result<Self, E> {
2831 let mut secret = Self::zeroed(len);
2832 let mut index = 0;
2833 while index < len {
2834 secret.inner[index] = make_byte(index)?;
2835 index += 1;
2836 }
2837 Ok(secret)
2838 }
2839
2840 #[inline]
2843 pub fn try_from_fn_bounded<E>(
2844 len: usize,
2845 maximum: usize,
2846 mut make_byte: impl FnMut(usize) -> Result<u8, E>,
2847 ) -> Result<Self, SecretBoxBytesGenerateError<E>> {
2848 let mut secret =
2849 Self::try_zeroed(len, maximum).map_err(SecretBoxBytesGenerateError::Build)?;
2850 let mut index = 0;
2851 while index < len {
2852 secret.inner[index] =
2853 make_byte(index).map_err(SecretBoxBytesGenerateError::Generate)?;
2854 index += 1;
2855 }
2856 Ok(secret)
2857 }
2858
2859 #[must_use]
2861 #[inline]
2862 pub const fn len(&self) -> usize {
2863 self.inner.len()
2864 }
2865
2866 #[must_use]
2868 #[inline]
2869 pub const fn is_empty(&self) -> bool {
2870 self.inner.is_empty()
2871 }
2872
2873 #[inline]
2885 pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
2886 inspect(self.inner.as_slice())
2887 }
2888
2889 #[inline]
2893 pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
2894 edit(self.inner.as_mut_slice())
2895 }
2896
2897 #[inline]
2899 pub fn copy_to_slice(&self, destination: &mut [u8]) -> Result<(), LengthError> {
2900 if destination.len() != self.len() {
2901 return Err(LengthError {
2902 expected: self.len(),
2903 actual: destination.len(),
2904 });
2905 }
2906
2907 destination.copy_from_slice(self.inner.as_slice());
2908 Ok(())
2909 }
2910
2911 #[inline]
2916 pub fn replace_from_slice(&mut self, bytes: &[u8]) -> Result<(), LengthError> {
2917 self.ensure_replacement_len(bytes.len())?;
2918 let replacement = Self::from_slice(bytes);
2919 self.replace_staged(replacement);
2920 Ok(())
2921 }
2922
2923 #[inline]
2928 pub fn replace_from_boxed_slice(&mut self, bytes: Box<[u8]>) -> Result<(), LengthError> {
2929 let replacement = Self::from_boxed_slice(bytes);
2930 self.ensure_replacement_len(replacement.len())?;
2931 self.replace_staged(replacement);
2932 Ok(())
2933 }
2934
2935 #[inline]
2940 pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2941 let replacement = Self::from_fn(self.len(), make_byte);
2942 self.replace_staged(replacement);
2943 }
2944
2945 #[inline]
2950 pub fn try_replace_from_fn<E>(
2951 &mut self,
2952 make_byte: impl FnMut(usize) -> Result<u8, E>,
2953 ) -> Result<(), E> {
2954 let replacement = Self::try_from_fn(self.len(), make_byte)?;
2955 self.replace_staged(replacement);
2956 Ok(())
2957 }
2958
2959 #[inline(never)]
2961 pub fn clear_secret(&mut self) {
2962 wipe_backend::erase(self.inner.as_mut_ptr(), self.inner.capacity());
2963 }
2964
2965 #[inline]
2967 pub fn into_cleared(mut self) {
2968 self.clear_secret();
2969 }
2970
2971 #[must_use]
2975 #[inline]
2976 pub fn constant_time_eq(&self, other: &[u8]) -> bool {
2977 constant_time_eq_slices(self.inner.as_slice(), other)
2978 }
2979
2980 #[inline]
2981 fn ensure_replacement_len(&self, actual: usize) -> Result<(), LengthError> {
2982 if actual == self.len() {
2983 Ok(())
2984 } else {
2985 Err(LengthError {
2986 expected: self.len(),
2987 actual,
2988 })
2989 }
2990 }
2991
2992 #[inline]
2993 fn replace_staged(&mut self, mut replacement: Self) {
2994 self.clear_secret();
2995 core::mem::swap(&mut self.inner, &mut replacement.inner);
2996 }
2997}
2998
2999#[cfg(feature = "alloc")]
3000impl Drop for SecretBoxBytes {
3001 #[inline]
3002 fn drop(&mut self) {
3003 self.clear_secret();
3004 }
3005}
3006
3007#[cfg(feature = "alloc")]
3008impl Default for SecretBoxBytes {
3009 #[inline]
3010 fn default() -> Self {
3011 Self::zeroed(0)
3012 }
3013}
3014
3015#[cfg(feature = "alloc")]
3016impl SecureSanitize for SecretBoxBytes {
3017 #[inline]
3018 fn secure_sanitize(&mut self) {
3019 self.clear_secret();
3020 }
3021}
3022
3023#[cfg(feature = "alloc")]
3024impl StableSharedSecretStorage for SecretBoxBytes {}
3025
3026#[cfg(feature = "alloc")]
3027impl StableMutableSecretStorage for SecretBoxBytes {}
3028
3029#[cfg(feature = "alloc")]
3030impl fmt::Debug for SecretBoxBytes {
3031 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3032 formatter
3033 .debug_struct("SecretBoxBytes")
3034 .field("len", &self.len())
3035 .field("contents", &"<redacted>")
3036 .finish()
3037 }
3038}
3039
3040#[cfg(feature = "alloc")]
3041impl ct::ConstantTimeEq for SecretBoxBytes {
3042 #[inline]
3043 fn ct_eq(&self, other: &Self) -> ct::Choice {
3044 ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
3045 }
3046}
3047
3048#[cfg(feature = "alloc")]
3049impl ct::ConstantTimeEq<[u8]> for SecretBoxBytes {
3050 #[inline]
3051 fn ct_eq(&self, other: &[u8]) -> ct::Choice {
3052 ct::eq_public_len(self.inner.as_slice(), other)
3053 }
3054}
3055
3056#[cfg(feature = "alloc")]
3060#[derive(Debug)]
3061pub enum SecretAllocationError {
3062 TooLong {
3064 maximum: usize,
3066 actual: usize,
3068 },
3069 CapacityOverflow,
3071 Allocation(alloc::collections::TryReserveError),
3073}
3074
3075#[cfg(feature = "alloc")]
3076impl From<alloc::collections::TryReserveError> for SecretAllocationError {
3077 #[inline]
3078 fn from(error: alloc::collections::TryReserveError) -> Self {
3079 Self::Allocation(error)
3080 }
3081}
3082
3083#[cfg(feature = "alloc")]
3084impl fmt::Display for SecretAllocationError {
3085 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3086 match self {
3087 Self::TooLong { maximum, actual } => write!(
3088 formatter,
3089 "secret length exceeds limit: maximum {maximum} bytes, got {actual} bytes"
3090 ),
3091 Self::CapacityOverflow => formatter.write_str("secret capacity calculation overflowed"),
3092 Self::Allocation(error) => write!(formatter, "secret allocation failed: {error}"),
3093 }
3094 }
3095}
3096
3097#[cfg(feature = "std")]
3098impl std::error::Error for SecretAllocationError {
3099 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3100 match self {
3101 Self::TooLong { .. } | Self::CapacityOverflow => None,
3102 Self::Allocation(error) => Some(error),
3103 }
3104 }
3105}
3106
3107#[cfg(feature = "alloc")]
3112#[derive(Debug)]
3113pub enum SecretGenerateError<E> {
3114 Build(SecretAllocationError),
3116 Generate(E),
3118}
3119
3120#[cfg(feature = "alloc")]
3121impl<E> From<SecretAllocationError> for SecretGenerateError<E> {
3122 #[inline]
3123 fn from(error: SecretAllocationError) -> Self {
3124 Self::Build(error)
3125 }
3126}
3127
3128#[cfg(feature = "alloc")]
3129impl<E: fmt::Display> fmt::Display for SecretGenerateError<E> {
3130 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3131 match self {
3132 Self::Build(error) => error.fmt(formatter),
3133 Self::Generate(error) => write!(formatter, "secret generation failed: {error}"),
3134 }
3135 }
3136}
3137
3138#[cfg(feature = "std")]
3139impl<E> std::error::Error for SecretGenerateError<E>
3140where
3141 E: std::error::Error + 'static,
3142{
3143 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3144 match self {
3145 Self::Build(error) => Some(error),
3146 Self::Generate(error) => Some(error),
3147 }
3148 }
3149}
3150
3151#[cfg(feature = "alloc")]
3153pub type SecretBoxBytesBuildError = SecretAllocationError;
3154
3155#[cfg(feature = "alloc")]
3157pub type SecretBoxBytesGenerateError<E> = SecretGenerateError<E>;
3158
3159#[cfg(feature = "alloc")]
3170pub struct SecretVec {
3171 pub(crate) inner: Vec<u8>,
3172}
3173
3174#[cfg(feature = "alloc")]
3180pub const DEFAULT_SECRET_VEC_SERDE_MAX_LEN: usize = 1024 * 1024;
3181
3182#[cfg(feature = "alloc")]
3183impl SecretVec {
3184 #[must_use]
3186 #[inline]
3187 pub const fn new(inner: Vec<u8>) -> Self {
3188 Self { inner }
3189 }
3190
3191 #[must_use]
3197 #[inline]
3198 pub const fn from_vec(bytes: Vec<u8>) -> Self {
3199 Self::new(bytes)
3200 }
3201
3202 #[must_use]
3204 #[inline]
3205 pub const fn empty() -> Self {
3206 Self::new(Vec::new())
3207 }
3208
3209 #[must_use]
3214 #[inline]
3215 pub fn with_capacity(capacity: usize) -> Self {
3216 Self::new(Vec::with_capacity(capacity))
3217 }
3218
3219 #[inline]
3225 pub fn try_with_capacity(capacity: usize) -> Result<Self, SecretAllocationError> {
3226 let mut inner = Vec::new();
3227 inner
3228 .try_reserve_exact(capacity)
3229 .map_err(SecretAllocationError::Allocation)?;
3230 Ok(Self::new(inner))
3231 }
3232
3233 #[must_use]
3238 #[inline]
3239 pub fn from_slice(bytes: &[u8]) -> Self {
3240 Self::new(Vec::from(bytes))
3241 }
3242
3243 #[inline]
3249 pub fn try_from_slice_bounded(
3250 bytes: &[u8],
3251 maximum: usize,
3252 ) -> Result<Self, SecretAllocationError> {
3253 if bytes.len() > maximum {
3254 return Err(SecretAllocationError::TooLong {
3255 maximum,
3256 actual: bytes.len(),
3257 });
3258 }
3259
3260 let mut secret = Self::try_with_capacity(bytes.len())?;
3261 secret.inner.extend_from_slice(bytes);
3262 Ok(secret)
3263 }
3264
3265 #[must_use]
3272 #[inline]
3273 pub fn from_fn(len: usize, mut make_byte: impl FnMut(usize) -> u8) -> Self {
3274 let mut secret = Self::with_capacity(len);
3275 let mut index = 0;
3276 while index < len {
3277 secret.inner.push(make_byte(index));
3278 index += 1;
3279 }
3280 secret
3281 }
3282
3283 #[inline]
3292 pub fn try_from_fn<E>(
3293 len: usize,
3294 mut make_byte: impl FnMut(usize) -> Result<u8, E>,
3295 ) -> Result<Self, SecretGenerateError<E>> {
3296 let mut secret = Self::try_with_capacity(len).map_err(SecretGenerateError::Build)?;
3297 let mut index = 0;
3298 while index < len {
3299 let byte = make_byte(index).map_err(SecretGenerateError::Generate)?;
3300 secret.inner.push(byte);
3301 index += 1;
3302 }
3303 Ok(secret)
3304 }
3305
3306 #[inline]
3311 pub fn try_from_fn_bounded<E>(
3312 len: usize,
3313 maximum: usize,
3314 make_byte: impl FnMut(usize) -> Result<u8, E>,
3315 ) -> Result<Self, SecretGenerateError<E>> {
3316 if len > maximum {
3317 return Err(SecretGenerateError::Build(SecretAllocationError::TooLong {
3318 maximum,
3319 actual: len,
3320 }));
3321 }
3322 Self::try_from_fn(len, make_byte)
3323 }
3324
3325 #[must_use]
3327 #[inline]
3328 pub fn len(&self) -> usize {
3329 self.inner.len()
3330 }
3331
3332 #[must_use]
3334 #[inline]
3335 pub fn is_empty(&self) -> bool {
3336 self.inner.is_empty()
3337 }
3338
3339 #[must_use]
3341 #[inline]
3342 pub fn capacity(&self) -> usize {
3343 self.inner.capacity()
3344 }
3345
3346 #[inline]
3348 pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
3349 inspect(self.inner.as_slice())
3350 }
3351
3352 #[inline]
3354 pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
3355 edit(self.inner.as_mut_slice())
3356 }
3357
3358 #[inline]
3364 pub fn extend_from_slice(&mut self, bytes: &[u8]) {
3365 self.grow_for(bytes.len());
3366 self.inner.extend_from_slice(bytes);
3367 }
3368
3369 #[inline]
3374 pub fn replace_from_slice(&mut self, bytes: &[u8]) {
3375 if bytes.len() > self.inner.capacity() {
3376 let new_capacity = next_secret_capacity(self.inner.capacity(), bytes.len());
3377 let mut replacement = Vec::with_capacity(new_capacity);
3378 replacement.extend_from_slice(bytes);
3379 self.clear_secret();
3380 self.inner = replacement;
3381 return;
3382 }
3383
3384 self.clear_secret();
3385 self.inner.extend_from_slice(bytes);
3386 }
3387
3388 #[inline]
3394 pub fn replace_from_vec(&mut self, bytes: Vec<u8>) {
3395 self.clear_secret();
3396 self.inner = bytes;
3397 }
3398
3399 #[inline]
3406 pub fn replace_from_fn(&mut self, len: usize, make_byte: impl FnMut(usize) -> u8) {
3407 let mut replacement = Self::from_fn(len, make_byte);
3408 self.clear_secret();
3409 core::mem::swap(&mut self.inner, &mut replacement.inner);
3410 }
3411
3412 #[inline]
3419 pub fn try_replace_from_fn<E>(
3420 &mut self,
3421 len: usize,
3422 make_byte: impl FnMut(usize) -> Result<u8, E>,
3423 ) -> Result<(), SecretGenerateError<E>> {
3424 let mut replacement = Self::try_from_fn(len, make_byte)?;
3425 self.clear_secret();
3426 core::mem::swap(&mut self.inner, &mut replacement.inner);
3427 Ok(())
3428 }
3429
3430 #[inline(never)]
3432 pub fn clear_secret(&mut self) {
3433 sanitize_vec_capacity(&mut self.inner);
3434 }
3435
3436 #[cfg(feature = "multi-pass-clear")]
3443 #[inline(never)]
3444 pub fn clear_secret_multi_pass(&mut self) {
3445 sanitize_vec_capacity_multi_pass(&mut self.inner);
3446 }
3447
3448 #[cfg(feature = "cache-flush")]
3451 #[inline(never)]
3452 pub fn clear_secret_and_flush(
3453 &mut self,
3454 ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
3455 crate::cache_flush::cache_flush_sanitize_vec(&mut self.inner)
3456 }
3457
3458 #[must_use]
3469 #[inline]
3470 pub fn constant_time_eq(&self, other: &[u8]) -> bool {
3471 constant_time_eq_slices(self.inner.as_slice(), other)
3472 }
3473
3474 #[inline]
3476 pub fn into_cleared(mut self) {
3477 self.clear_secret();
3478 }
3479
3480 #[inline]
3486 pub fn try_into_secret_string(self) -> Result<SecretString, core::str::Utf8Error> {
3487 SecretString::from_secret_vec(self)
3488 }
3489
3490 fn grow_for(&mut self, additional: usize) {
3491 let required = self.inner.len().saturating_add(additional);
3492 if required <= self.inner.capacity() {
3493 return;
3494 }
3495
3496 let new_capacity = next_secret_capacity(self.inner.capacity(), required);
3497 let mut replacement = Vec::with_capacity(new_capacity);
3498 replacement.extend_from_slice(self.inner.as_slice());
3499 self.clear_secret();
3500 self.inner = replacement;
3501 }
3502}
3503
3504#[cfg(feature = "alloc")]
3505impl Drop for SecretVec {
3506 #[inline]
3507 fn drop(&mut self) {
3508 self.clear_secret();
3509 }
3510}
3511
3512#[cfg(feature = "alloc")]
3513impl Default for SecretVec {
3514 #[inline]
3515 fn default() -> Self {
3516 Self::empty()
3517 }
3518}
3519
3520#[cfg(feature = "alloc")]
3521impl SecureSanitize for SecretVec {
3522 #[inline]
3523 fn secure_sanitize(&mut self) {
3524 self.clear_secret();
3525 }
3526}
3527
3528#[cfg(feature = "alloc")]
3529impl fmt::Debug for SecretVec {
3530 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3531 formatter
3532 .debug_struct("SecretVec")
3533 .field("len", &self.inner.len())
3534 .field("contents", &"<redacted>")
3535 .finish()
3536 }
3537}
3538
3539#[cfg(feature = "alloc")]
3540impl ct::ConstantTimeEq for SecretVec {
3541 #[inline]
3542 fn ct_eq(&self, other: &Self) -> ct::Choice {
3543 ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
3544 }
3545}
3546
3547#[cfg(feature = "alloc")]
3548impl ct::ConstantTimeEq<[u8]> for SecretVec {
3549 #[inline]
3550 fn ct_eq(&self, other: &[u8]) -> ct::Choice {
3551 ct::eq_public_len(self.inner.as_slice(), other)
3552 }
3553}
3554
3555#[cfg(feature = "alloc")]
3557#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3558pub struct SecretVecLimitError {
3559 pub maximum: usize,
3561 pub actual: usize,
3563}
3564
3565#[cfg(feature = "alloc")]
3566impl fmt::Display for SecretVecLimitError {
3567 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3568 write!(
3569 formatter,
3570 "secret length exceeds limit: maximum {} bytes, got {} bytes",
3571 self.maximum, self.actual
3572 )
3573 }
3574}
3575
3576#[cfg(feature = "std")]
3577impl std::error::Error for SecretVecLimitError {}
3578
3579#[cfg(feature = "alloc")]
3587pub struct BoundedSecretVec<const MAX: usize> {
3588 pub(crate) inner: SecretVec,
3589}
3590
3591#[cfg(feature = "alloc")]
3592impl<const MAX: usize> BoundedSecretVec<MAX> {
3593 #[must_use]
3595 #[inline]
3596 pub const fn empty() -> Self {
3597 Self {
3598 inner: SecretVec::empty(),
3599 }
3600 }
3601
3602 #[inline]
3604 pub fn from_slice(bytes: &[u8]) -> Result<Self, SecretVecLimitError> {
3605 Self::validate_len(bytes.len())?;
3606 Ok(Self {
3607 inner: SecretVec::from_slice(bytes),
3608 })
3609 }
3610
3611 #[inline]
3616 pub fn from_vec(mut bytes: Vec<u8>) -> Result<Self, SecretVecLimitError> {
3617 if let Err(error) = Self::validate_len(bytes.len()) {
3618 sanitize_vec_capacity(&mut bytes);
3619 return Err(error);
3620 }
3621 Ok(Self {
3622 inner: SecretVec::from_vec(bytes),
3623 })
3624 }
3625
3626 #[inline]
3630 pub fn from_secret_vec(mut secret: SecretVec) -> Result<Self, SecretVecLimitError> {
3631 if let Err(error) = Self::validate_len(secret.len()) {
3632 secret.clear_secret();
3633 return Err(error);
3634 }
3635 Ok(Self { inner: secret })
3636 }
3637
3638 #[must_use]
3640 #[inline]
3641 pub const fn max_len() -> usize {
3642 MAX
3643 }
3644
3645 #[must_use]
3647 #[inline]
3648 pub fn len(&self) -> usize {
3649 self.inner.len()
3650 }
3651
3652 #[must_use]
3654 #[inline]
3655 pub fn is_empty(&self) -> bool {
3656 self.inner.is_empty()
3657 }
3658
3659 #[inline]
3661 pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
3662 self.inner.with_secret(inspect)
3663 }
3664
3665 #[inline]
3667 pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
3668 self.inner.with_secret_mut(edit)
3669 }
3670
3671 #[inline]
3673 pub fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), SecretVecLimitError> {
3674 let actual = self.len().saturating_add(bytes.len());
3675 Self::validate_len(actual)?;
3676 self.inner.extend_from_slice(bytes);
3677 Ok(())
3678 }
3679
3680 #[inline]
3682 pub fn replace_from_slice(&mut self, bytes: &[u8]) -> Result<(), SecretVecLimitError> {
3683 Self::validate_len(bytes.len())?;
3684 self.inner.replace_from_slice(bytes);
3685 Ok(())
3686 }
3687
3688 #[inline(never)]
3690 pub fn clear_secret(&mut self) {
3691 self.inner.clear_secret();
3692 }
3693
3694 #[must_use]
3696 #[inline]
3697 pub fn into_secret_vec(self) -> SecretVec {
3698 self.inner
3699 }
3700
3701 #[inline]
3702 fn validate_len(actual: usize) -> Result<(), SecretVecLimitError> {
3703 if actual > MAX {
3704 Err(SecretVecLimitError {
3705 maximum: MAX,
3706 actual,
3707 })
3708 } else {
3709 Ok(())
3710 }
3711 }
3712}
3713
3714#[cfg(feature = "alloc")]
3715impl<const MAX: usize> Default for BoundedSecretVec<MAX> {
3716 #[inline]
3717 fn default() -> Self {
3718 Self::empty()
3719 }
3720}
3721
3722#[cfg(feature = "alloc")]
3723impl<const MAX: usize> From<BoundedSecretVec<MAX>> for SecretVec {
3724 #[inline]
3725 fn from(secret: BoundedSecretVec<MAX>) -> Self {
3726 secret.into_secret_vec()
3727 }
3728}
3729
3730#[cfg(feature = "alloc")]
3731impl<const MAX: usize> SecureSanitize for BoundedSecretVec<MAX> {
3732 #[inline]
3733 fn secure_sanitize(&mut self) {
3734 self.clear_secret();
3735 }
3736}
3737
3738#[cfg(feature = "alloc")]
3739impl<const MAX: usize> fmt::Debug for BoundedSecretVec<MAX> {
3740 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3741 formatter
3742 .debug_struct("BoundedSecretVec")
3743 .field("len", &self.len())
3744 .field("max_len", &MAX)
3745 .field("contents", &"<redacted>")
3746 .finish()
3747 }
3748}
3749
3750#[cfg(feature = "alloc")]
3751impl<const MAX: usize> ct::ConstantTimeEq for BoundedSecretVec<MAX> {
3752 #[inline]
3753 fn ct_eq(&self, other: &Self) -> ct::Choice {
3754 self.inner.ct_eq(&other.inner)
3755 }
3756}
3757
3758#[cfg(feature = "alloc")]
3765pub struct SecretString {
3766 pub(crate) inner: Vec<u8>,
3767}
3768
3769#[cfg(feature = "alloc")]
3774pub const DEFAULT_SECRET_STRING_SERDE_MAX_LEN: usize = 1024 * 1024;
3775
3776#[cfg(feature = "alloc")]
3777impl SecretString {
3778 #[must_use]
3780 #[inline]
3781 pub fn new(inner: String) -> Self {
3782 Self {
3783 inner: inner.into_bytes(),
3784 }
3785 }
3786
3787 #[must_use]
3793 #[inline]
3794 pub fn from_string(text: String) -> Self {
3795 Self::new(text)
3796 }
3797
3798 #[inline]
3804 pub fn from_secret_vec(mut secret: SecretVec) -> Result<Self, core::str::Utf8Error> {
3805 if let Err(error) = core::str::from_utf8(secret.inner.as_slice()) {
3806 secret.clear_secret();
3807 return Err(error);
3808 }
3809
3810 Ok(Self {
3811 inner: core::mem::take(&mut secret.inner),
3812 })
3813 }
3814
3815 #[must_use]
3817 #[inline]
3818 pub const fn empty() -> Self {
3819 Self { inner: Vec::new() }
3820 }
3821
3822 #[must_use]
3827 #[inline]
3828 pub fn with_capacity(capacity: usize) -> Self {
3829 Self {
3830 inner: Vec::with_capacity(capacity),
3831 }
3832 }
3833
3834 #[inline]
3840 pub fn try_with_capacity(capacity: usize) -> Result<Self, SecretAllocationError> {
3841 let mut inner = Vec::new();
3842 inner
3843 .try_reserve_exact(capacity)
3844 .map_err(SecretAllocationError::Allocation)?;
3845 Ok(Self { inner })
3846 }
3847
3848 #[must_use]
3853 #[inline]
3854 pub fn from_secret_str(text: &str) -> Self {
3855 Self {
3856 inner: Vec::from(text.as_bytes()),
3857 }
3858 }
3859
3860 #[inline]
3866 pub fn try_from_secret_str_bounded(
3867 text: &str,
3868 maximum_bytes: usize,
3869 ) -> Result<Self, SecretAllocationError> {
3870 if text.len() > maximum_bytes {
3871 return Err(SecretAllocationError::TooLong {
3872 maximum: maximum_bytes,
3873 actual: text.len(),
3874 });
3875 }
3876
3877 let mut secret = Self::try_with_capacity(text.len())?;
3878 secret.inner.extend_from_slice(text.as_bytes());
3879 Ok(secret)
3880 }
3881
3882 #[must_use]
3890 #[inline]
3891 pub fn from_chars(char_count: usize, mut make_char: impl FnMut(usize) -> char) -> Self {
3892 let capacity = char_count
3893 .checked_mul(MAX_UTF8_CHAR_BYTES)
3894 .expect("secret UTF-8 capacity calculation overflowed");
3895 let mut secret = Self::with_capacity(capacity);
3896 let mut index = 0;
3897 while index < char_count {
3898 secret.push_secret_char(make_char(index));
3899 index += 1;
3900 }
3901 secret
3902 }
3903
3904 #[inline]
3914 pub fn try_from_chars<E>(
3915 char_count: usize,
3916 mut make_char: impl FnMut(usize) -> Result<char, E>,
3917 ) -> Result<Self, SecretGenerateError<E>> {
3918 let capacity =
3919 char_count
3920 .checked_mul(MAX_UTF8_CHAR_BYTES)
3921 .ok_or(SecretGenerateError::Build(
3922 SecretAllocationError::CapacityOverflow,
3923 ))?;
3924 let mut secret = Self::try_with_capacity(capacity).map_err(SecretGenerateError::Build)?;
3925 let mut index = 0;
3926 while index < char_count {
3927 let character = make_char(index).map_err(SecretGenerateError::Generate)?;
3928 secret.push_secret_char(character);
3929 index += 1;
3930 }
3931 Ok(secret)
3932 }
3933
3934 #[inline]
3940 pub fn try_from_chars_bounded<E>(
3941 char_count: usize,
3942 maximum_bytes: usize,
3943 make_char: impl FnMut(usize) -> Result<char, E>,
3944 ) -> Result<Self, SecretGenerateError<E>> {
3945 let capacity =
3946 char_count
3947 .checked_mul(MAX_UTF8_CHAR_BYTES)
3948 .ok_or(SecretGenerateError::Build(
3949 SecretAllocationError::CapacityOverflow,
3950 ))?;
3951 if capacity > maximum_bytes {
3952 return Err(SecretGenerateError::Build(SecretAllocationError::TooLong {
3953 maximum: maximum_bytes,
3954 actual: capacity,
3955 }));
3956 }
3957 Self::try_from_chars(char_count, make_char)
3958 }
3959
3960 #[must_use]
3962 #[inline]
3963 pub fn len(&self) -> usize {
3964 self.inner.len()
3965 }
3966
3967 #[must_use]
3969 #[inline]
3970 pub fn is_empty(&self) -> bool {
3971 self.inner.is_empty()
3972 }
3973
3974 #[must_use]
3976 #[inline]
3977 pub fn capacity(&self) -> usize {
3978 self.inner.capacity()
3979 }
3980
3981 #[inline]
3986 pub fn try_with_secret<R>(
3987 &self,
3988 inspect: impl FnOnce(&str) -> R,
3989 ) -> Result<R, core::str::Utf8Error> {
3990 core::str::from_utf8(self.inner.as_slice()).map(inspect)
3991 }
3992
3993 #[inline]
3999 pub fn try_with_secret_mut<R>(
4000 &mut self,
4001 edit: impl FnOnce(&mut str) -> R,
4002 ) -> Result<R, core::str::Utf8Error> {
4003 core::str::from_utf8_mut(self.inner.as_mut_slice()).map(edit)
4004 }
4005
4006 #[inline]
4008 pub fn with_secret_bytes<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
4009 inspect(self.inner.as_slice())
4010 }
4011
4012 #[inline]
4018 pub fn push_str(&mut self, text: &str) {
4019 self.grow_for(text.len());
4020 self.inner.extend_from_slice(text.as_bytes());
4021 }
4022
4023 #[inline]
4028 pub fn replace_from_secret_str(&mut self, text: &str) {
4029 if text.len() > self.inner.capacity() {
4030 let new_capacity = next_secret_capacity(self.inner.capacity(), text.len());
4031 let mut replacement = Vec::with_capacity(new_capacity);
4032 replacement.extend_from_slice(text.as_bytes());
4033 self.clear_secret();
4034 self.inner = replacement;
4035 return;
4036 }
4037
4038 self.clear_secret();
4039 self.inner.extend_from_slice(text.as_bytes());
4040 }
4041
4042 #[inline]
4049 pub fn replace_from_string(&mut self, text: String) {
4050 let replacement = text.into_bytes();
4051 self.clear_secret();
4052 self.inner = replacement;
4053 }
4054
4055 #[inline]
4062 pub fn replace_from_chars(&mut self, char_count: usize, make_char: impl FnMut(usize) -> char) {
4063 let mut replacement = Self::from_chars(char_count, make_char);
4064 self.clear_secret();
4065 core::mem::swap(&mut self.inner, &mut replacement.inner);
4066 }
4067
4068 #[inline]
4075 pub fn try_replace_from_chars<E>(
4076 &mut self,
4077 char_count: usize,
4078 make_char: impl FnMut(usize) -> Result<char, E>,
4079 ) -> Result<(), SecretGenerateError<E>> {
4080 let mut replacement = Self::try_from_chars(char_count, make_char)?;
4081 self.clear_secret();
4082 core::mem::swap(&mut self.inner, &mut replacement.inner);
4083 Ok(())
4084 }
4085
4086 #[inline(never)]
4088 pub fn clear_secret(&mut self) {
4089 sanitize_vec_capacity(&mut self.inner);
4090 }
4091
4092 #[cfg(feature = "multi-pass-clear")]
4099 #[inline(never)]
4100 pub fn clear_secret_multi_pass(&mut self) {
4101 sanitize_vec_capacity_multi_pass(&mut self.inner);
4102 }
4103
4104 #[cfg(feature = "cache-flush")]
4107 #[inline(never)]
4108 pub fn clear_secret_and_flush(
4109 &mut self,
4110 ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
4111 crate::cache_flush::cache_flush_sanitize_vec(&mut self.inner)
4112 }
4113
4114 #[must_use]
4125 #[inline]
4126 pub fn constant_time_eq(&self, other: &str) -> bool {
4127 constant_time_eq_slices(self.inner.as_slice(), other.as_bytes())
4128 }
4129
4130 #[inline]
4132 pub fn into_cleared(mut self) {
4133 self.clear_secret();
4134 }
4135
4136 #[must_use]
4138 #[inline]
4139 pub fn into_secret_vec(mut self) -> SecretVec {
4140 SecretVec::from_vec(core::mem::take(&mut self.inner))
4141 }
4142
4143 fn grow_for(&mut self, additional: usize) {
4144 let required = self.inner.len().saturating_add(additional);
4145 if required <= self.inner.capacity() {
4146 return;
4147 }
4148
4149 let new_capacity = next_secret_capacity(self.inner.capacity(), required);
4150 let mut replacement = Vec::with_capacity(new_capacity);
4151 replacement.extend_from_slice(self.inner.as_slice());
4152 self.clear_secret();
4153 self.inner = replacement;
4154 }
4155
4156 fn push_secret_char(&mut self, character: char) {
4157 let mut encoded = [0; 4];
4158 let text = character.encode_utf8(&mut encoded);
4159 self.inner.extend_from_slice(text.as_bytes());
4160 wipe::bytes(&mut encoded);
4161 }
4162}
4163
4164#[cfg(feature = "alloc")]
4165impl Drop for SecretString {
4166 #[inline]
4167 fn drop(&mut self) {
4168 self.clear_secret();
4169 }
4170}
4171
4172#[cfg(feature = "alloc")]
4173impl Default for SecretString {
4174 #[inline]
4175 fn default() -> Self {
4176 Self::empty()
4177 }
4178}
4179
4180#[cfg(feature = "alloc")]
4181impl SecureSanitize for SecretString {
4182 #[inline]
4183 fn secure_sanitize(&mut self) {
4184 self.clear_secret();
4185 }
4186}
4187
4188#[cfg(feature = "alloc")]
4189impl fmt::Debug for SecretString {
4190 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4191 formatter
4192 .debug_struct("SecretString")
4193 .field("len", &self.inner.len())
4194 .field("contents", &"<redacted>")
4195 .finish()
4196 }
4197}
4198
4199#[cfg(feature = "alloc")]
4200impl ct::ConstantTimeEq for SecretString {
4201 #[inline]
4202 fn ct_eq(&self, other: &Self) -> ct::Choice {
4203 ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
4204 }
4205}
4206
4207#[cfg(feature = "alloc")]
4208impl ct::ConstantTimeEq<str> for SecretString {
4209 #[inline]
4210 fn ct_eq(&self, other: &str) -> ct::Choice {
4211 ct::eq_public_len(self.inner.as_slice(), other.as_bytes())
4212 }
4213}
4214
4215#[cfg(feature = "alloc")]
4216impl TryFrom<SecretVec> for SecretString {
4217 type Error = core::str::Utf8Error;
4218
4219 #[inline]
4220 fn try_from(secret: SecretVec) -> Result<Self, Self::Error> {
4221 Self::from_secret_vec(secret)
4222 }
4223}
4224
4225#[cfg(feature = "alloc")]
4226impl From<SecretString> for SecretVec {
4227 #[inline]
4228 fn from(secret: SecretString) -> Self {
4229 secret.into_secret_vec()
4230 }
4231}
4232
4233#[cfg(feature = "alloc")]
4235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4236pub struct SecretStringLimitError {
4237 pub maximum: usize,
4239 pub actual: usize,
4241}
4242
4243#[cfg(feature = "alloc")]
4244impl fmt::Display for SecretStringLimitError {
4245 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4246 write!(
4247 formatter,
4248 "secret text length exceeds limit: maximum {} UTF-8 bytes, got {} bytes",
4249 self.maximum, self.actual
4250 )
4251 }
4252}
4253
4254#[cfg(feature = "std")]
4255impl std::error::Error for SecretStringLimitError {}
4256
4257#[cfg(feature = "alloc")]
4264pub struct BoundedSecretString<const MAX: usize> {
4265 pub(crate) inner: SecretString,
4266}
4267
4268#[cfg(feature = "alloc")]
4269impl<const MAX: usize> BoundedSecretString<MAX> {
4270 #[must_use]
4272 #[inline]
4273 pub const fn empty() -> Self {
4274 Self {
4275 inner: SecretString::empty(),
4276 }
4277 }
4278
4279 #[inline]
4281 pub fn from_secret_str(text: &str) -> Result<Self, SecretStringLimitError> {
4282 Self::validate_len(text.len())?;
4283 Ok(Self {
4284 inner: SecretString::from_secret_str(text),
4285 })
4286 }
4287
4288 #[inline]
4293 pub fn from_string(mut text: String) -> Result<Self, SecretStringLimitError> {
4294 if let Err(error) = Self::validate_len(text.len()) {
4295 text.secure_sanitize();
4296 return Err(error);
4297 }
4298 Ok(Self {
4299 inner: SecretString::from_string(text),
4300 })
4301 }
4302
4303 #[inline]
4307 pub fn from_secret_string(mut secret: SecretString) -> Result<Self, SecretStringLimitError> {
4308 if let Err(error) = Self::validate_len(secret.len()) {
4309 secret.clear_secret();
4310 return Err(error);
4311 }
4312 Ok(Self { inner: secret })
4313 }
4314
4315 #[inline]
4320 pub fn from_secret_vec(secret: SecretVec) -> Result<Self, BoundedSecretStringError> {
4321 let text = SecretString::from_secret_vec(secret).map_err(BoundedSecretStringError::Utf8)?;
4322 Self::from_secret_string(text).map_err(BoundedSecretStringError::Limit)
4323 }
4324
4325 #[must_use]
4327 #[inline]
4328 pub const fn max_len() -> usize {
4329 MAX
4330 }
4331
4332 #[must_use]
4334 #[inline]
4335 pub fn len(&self) -> usize {
4336 self.inner.len()
4337 }
4338
4339 #[must_use]
4341 #[inline]
4342 pub fn is_empty(&self) -> bool {
4343 self.inner.is_empty()
4344 }
4345
4346 #[must_use]
4348 #[inline]
4349 pub fn capacity(&self) -> usize {
4350 self.inner.capacity()
4351 }
4352
4353 #[inline]
4355 pub fn try_with_secret<R>(
4356 &self,
4357 inspect: impl FnOnce(&str) -> R,
4358 ) -> Result<R, core::str::Utf8Error> {
4359 self.inner.try_with_secret(inspect)
4360 }
4361
4362 #[inline]
4364 pub fn try_with_secret_mut<R>(
4365 &mut self,
4366 edit: impl FnOnce(&mut str) -> R,
4367 ) -> Result<R, core::str::Utf8Error> {
4368 self.inner.try_with_secret_mut(edit)
4369 }
4370
4371 #[inline]
4373 pub fn push_str(&mut self, text: &str) -> Result<(), SecretStringLimitError> {
4374 Self::validate_len(self.len().saturating_add(text.len()))?;
4375 self.inner.push_str(text);
4376 Ok(())
4377 }
4378
4379 #[inline]
4381 pub fn replace_from_secret_str(&mut self, text: &str) -> Result<(), SecretStringLimitError> {
4382 Self::validate_len(text.len())?;
4383 self.inner.replace_from_secret_str(text);
4384 Ok(())
4385 }
4386
4387 #[inline]
4392 pub fn replace_from_string(&mut self, text: String) -> Result<(), SecretStringLimitError> {
4393 let mut replacement = Self::from_string(text)?;
4394 self.clear_secret();
4395 core::mem::swap(&mut self.inner, &mut replacement.inner);
4396 Ok(())
4397 }
4398
4399 #[inline(never)]
4401 pub fn clear_secret(&mut self) {
4402 self.inner.clear_secret();
4403 }
4404
4405 #[must_use]
4407 #[inline]
4408 pub fn constant_time_eq(&self, other: &str) -> bool {
4409 self.inner.constant_time_eq(other)
4410 }
4411
4412 #[must_use]
4414 #[inline]
4415 pub fn into_secret_string(self) -> SecretString {
4416 self.inner
4417 }
4418
4419 #[must_use]
4421 #[inline]
4422 pub fn into_secret_vec(self) -> SecretVec {
4423 self.inner.into_secret_vec()
4424 }
4425
4426 #[inline]
4427 fn validate_len(actual: usize) -> Result<(), SecretStringLimitError> {
4428 if actual > MAX {
4429 Err(SecretStringLimitError {
4430 maximum: MAX,
4431 actual,
4432 })
4433 } else {
4434 Ok(())
4435 }
4436 }
4437}
4438
4439#[cfg(feature = "alloc")]
4441#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4442pub enum BoundedSecretStringError {
4443 Utf8(core::str::Utf8Error),
4445 Limit(SecretStringLimitError),
4447}
4448
4449#[cfg(feature = "alloc")]
4450impl fmt::Display for BoundedSecretStringError {
4451 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4452 match self {
4453 Self::Utf8(error) => error.fmt(formatter),
4454 Self::Limit(error) => error.fmt(formatter),
4455 }
4456 }
4457}
4458
4459#[cfg(feature = "std")]
4460impl std::error::Error for BoundedSecretStringError {
4461 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
4462 match self {
4463 Self::Utf8(error) => Some(error),
4464 Self::Limit(error) => Some(error),
4465 }
4466 }
4467}
4468
4469#[cfg(feature = "alloc")]
4470impl<const MAX: usize> Default for BoundedSecretString<MAX> {
4471 #[inline]
4472 fn default() -> Self {
4473 Self::empty()
4474 }
4475}
4476
4477#[cfg(feature = "alloc")]
4478impl<const MAX: usize> SecureSanitize for BoundedSecretString<MAX> {
4479 #[inline]
4480 fn secure_sanitize(&mut self) {
4481 self.clear_secret();
4482 }
4483}
4484
4485#[cfg(feature = "alloc")]
4486impl<const MAX: usize> fmt::Debug for BoundedSecretString<MAX> {
4487 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4488 formatter
4489 .debug_struct("BoundedSecretString")
4490 .field("len", &self.len())
4491 .field("max_len", &MAX)
4492 .field("contents", &"<redacted>")
4493 .finish()
4494 }
4495}
4496
4497#[cfg(feature = "alloc")]
4498impl<const MAX: usize> ct::ConstantTimeEq for BoundedSecretString<MAX> {
4499 #[inline]
4500 fn ct_eq(&self, other: &Self) -> ct::Choice {
4501 self.inner.ct_eq(&other.inner)
4502 }
4503}
4504
4505#[cfg(feature = "alloc")]
4506impl<const MAX: usize> ct::ConstantTimeEq<str> for BoundedSecretString<MAX> {
4507 #[inline]
4508 fn ct_eq(&self, other: &str) -> ct::Choice {
4509 self.inner.ct_eq(other)
4510 }
4511}
4512
4513#[cfg(feature = "alloc")]
4514impl<const MAX: usize> From<BoundedSecretString<MAX>> for SecretString {
4515 #[inline]
4516 fn from(secret: BoundedSecretString<MAX>) -> Self {
4517 secret.into_secret_string()
4518 }
4519}
4520
4521#[cfg(feature = "alloc")]
4522impl<const MAX: usize> TryFrom<SecretString> for BoundedSecretString<MAX> {
4523 type Error = SecretStringLimitError;
4524
4525 #[inline]
4526 fn try_from(secret: SecretString) -> Result<Self, Self::Error> {
4527 Self::from_secret_string(secret)
4528 }
4529}
4530
4531#[cfg(feature = "alloc")]
4532impl<const MAX: usize> TryFrom<SecretVec> for BoundedSecretString<MAX> {
4533 type Error = BoundedSecretStringError;
4534
4535 #[inline]
4536 fn try_from(secret: SecretVec) -> Result<Self, Self::Error> {
4537 Self::from_secret_vec(secret)
4538 }
4539}
4540
4541pub struct Secret<T: SecureSanitize> {
4567 inner: T,
4568}
4569
4570impl<T: SecureSanitize> Secret<T> {
4571 #[must_use]
4573 #[inline]
4574 pub const fn new(inner: T) -> Self {
4575 Self { inner }
4576 }
4577
4578 #[inline]
4580 pub fn into_cleared(mut self) {
4581 self.inner.secure_sanitize();
4582 }
4583}
4584
4585impl<T: StableSharedSecretStorage> Secret<T> {
4586 #[inline]
4603 pub fn with_secret<R>(&self, inspect: impl FnOnce(&T) -> R) -> R {
4604 inspect(&self.inner)
4605 }
4606}
4607
4608impl<T: StableMutableSecretStorage> Secret<T> {
4609 #[inline]
4616 pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut T) -> R) -> R {
4617 edit(&mut self.inner)
4618 }
4619}
4620
4621impl<T: SecureSanitize> SecureSanitize for Secret<T> {
4622 #[inline]
4623 fn secure_sanitize(&mut self) {
4624 self.inner.secure_sanitize();
4625 }
4626}
4627
4628impl<T: StableSharedSecretStorage> StableSharedSecretStorage for Secret<T> {}
4629impl<T: StableMutableSecretStorage> StableMutableSecretStorage for Secret<T> {}
4630
4631impl<T: SecureSanitize> Drop for Secret<T> {
4632 #[inline]
4633 fn drop(&mut self) {
4634 self.secure_sanitize();
4635 }
4636}
4637
4638impl<T: SecureSanitize + Default> Default for Secret<T> {
4639 #[inline]
4640 fn default() -> Self {
4641 Self::new(T::default())
4642 }
4643}
4644
4645impl<T: SecureSanitize> fmt::Debug for Secret<T> {
4646 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4647 formatter
4648 .debug_struct("Secret")
4649 .field("contents", &"<redacted>")
4650 .finish()
4651 }
4652}
4653
4654pub struct AllowlistedSecret<T: SecureSanitize, P> {
4690 inner: T,
4691 policy: PhantomData<fn() -> P>,
4692}
4693
4694impl<T, P> AllowlistedSecret<T, P>
4695where
4696 T: SecureSanitize,
4697 P: SecretStoragePolicy<T>,
4698{
4699 #[must_use]
4701 #[inline]
4702 pub const fn new(inner: T) -> Self {
4703 Self {
4704 inner,
4705 policy: PhantomData,
4706 }
4707 }
4708
4709 #[must_use]
4711 #[inline]
4712 pub const fn policy_rationale() -> &'static str {
4713 P::RATIONALE
4714 }
4715
4716 #[inline]
4718 pub fn into_cleared(mut self) {
4719 self.inner.secure_sanitize();
4720 }
4721}
4722
4723impl<T, P> AllowlistedSecret<T, P>
4724where
4725 T: StableSharedSecretStorage,
4726 P: SecretStoragePolicy<T>,
4727{
4728 #[inline]
4730 pub fn with_secret<R>(&self, inspect: impl FnOnce(&T) -> R) -> R {
4731 inspect(&self.inner)
4732 }
4733}
4734
4735impl<T, P> AllowlistedSecret<T, P>
4736where
4737 T: StableMutableSecretStorage,
4738 P: SecretStoragePolicy<T>,
4739{
4740 #[inline]
4742 pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut T) -> R) -> R {
4743 edit(&mut self.inner)
4744 }
4745}
4746
4747impl<T: SecureSanitize, P> SecureSanitize for AllowlistedSecret<T, P> {
4748 #[inline]
4749 fn secure_sanitize(&mut self) {
4750 self.inner.secure_sanitize();
4751 }
4752}
4753
4754impl<T, P> StableSharedSecretStorage for AllowlistedSecret<T, P>
4755where
4756 T: StableSharedSecretStorage,
4757 P: SecretStoragePolicy<T>,
4758{
4759}
4760
4761impl<T, P> StableMutableSecretStorage for AllowlistedSecret<T, P>
4762where
4763 T: StableMutableSecretStorage,
4764 P: SecretStoragePolicy<T>,
4765{
4766}
4767
4768impl<T: SecureSanitize, P> Drop for AllowlistedSecret<T, P> {
4769 #[inline]
4770 fn drop(&mut self) {
4771 self.secure_sanitize();
4772 }
4773}
4774
4775impl<T, P> Default for AllowlistedSecret<T, P>
4776where
4777 T: SecureSanitize + Default,
4778 P: SecretStoragePolicy<T>,
4779{
4780 #[inline]
4781 fn default() -> Self {
4782 Self::new(T::default())
4783 }
4784}
4785
4786impl<T: SecureSanitize, P> fmt::Debug for AllowlistedSecret<T, P> {
4787 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4788 formatter
4789 .debug_struct("AllowlistedSecret")
4790 .field("contents", &"<redacted>")
4791 .finish()
4792 }
4793}
4794
4795#[allow(unsafe_code)]
4796mod consume_once {
4797 use super::{fmt, SecureSanitize, StableMutableSecretStorage, StableSharedSecretStorage};
4798 use core::{
4799 cell::UnsafeCell,
4800 sync::atomic::{AtomicBool, Ordering},
4801 };
4802
4803 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
4805 pub struct AlreadyConsumedError;
4806
4807 impl fmt::Display for AlreadyConsumedError {
4808 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4809 formatter.write_str("consume-once secret already claimed")
4810 }
4811 }
4812
4813 #[cfg(feature = "std")]
4814 impl std::error::Error for AlreadyConsumedError {}
4815
4816 pub struct ConsumeOnceSecret<T: SecureSanitize> {
4829 inner: UnsafeCell<T>,
4830 claimed: AtomicBool,
4831 }
4832
4833 struct ClearOnExit<'a, T: SecureSanitize> {
4834 owner: &'a ConsumeOnceSecret<T>,
4835 }
4836
4837 impl<T: SecureSanitize> Drop for ClearOnExit<'_, T> {
4838 #[inline]
4839 fn drop(&mut self) {
4840 self.owner.clear_inner();
4841 }
4842 }
4843
4844 unsafe impl<T: SecureSanitize + Send> Send for ConsumeOnceSecret<T> {}
4848
4849 unsafe impl<T: SecureSanitize + Send> Sync for ConsumeOnceSecret<T> {}
4854
4855 impl<T: SecureSanitize> ConsumeOnceSecret<T> {
4856 #[must_use]
4858 #[inline]
4859 pub const fn new(inner: T) -> Self {
4860 Self {
4861 inner: UnsafeCell::new(inner),
4862 claimed: AtomicBool::new(false),
4863 }
4864 }
4865
4866 #[inline]
4868 pub fn into_cleared(mut self) {
4869 self.claimed.store(true, Ordering::Release);
4870 self.inner.get_mut().secure_sanitize();
4871 }
4872
4873 #[must_use]
4880 #[inline]
4881 pub fn is_claimed(&self) -> bool {
4882 self.claimed.load(Ordering::Acquire)
4883 }
4884
4885 #[inline]
4886 fn claim(&self) -> Result<ClearOnExit<'_, T>, AlreadyConsumedError> {
4887 if self.claimed.swap(true, Ordering::AcqRel) {
4888 Err(AlreadyConsumedError)
4889 } else {
4890 Ok(ClearOnExit { owner: self })
4891 }
4892 }
4893
4894 #[inline]
4895 fn clear_inner(&self) {
4896 unsafe { (&mut *self.inner.get()).secure_sanitize() };
4900 }
4901 }
4902
4903 impl<T: StableSharedSecretStorage> ConsumeOnceSecret<T> {
4904 #[inline]
4935 pub fn consume<R>(&self, inspect: impl FnOnce(&T) -> R) -> Result<R, AlreadyConsumedError> {
4936 let clear_guard = self.claim()?;
4937 let result = inspect(unsafe { &*self.inner.get() });
4940 drop(clear_guard);
4941 Ok(result)
4942 }
4943 }
4944
4945 impl<T: SecureSanitize> Drop for ConsumeOnceSecret<T> {
4946 #[inline]
4947 fn drop(&mut self) {
4948 self.inner.get_mut().secure_sanitize();
4949 }
4950 }
4951
4952 impl<T: SecureSanitize + Default> Default for ConsumeOnceSecret<T> {
4953 #[inline]
4954 fn default() -> Self {
4955 Self::new(T::default())
4956 }
4957 }
4958
4959 impl<T: SecureSanitize> SecureSanitize for ConsumeOnceSecret<T> {
4960 #[inline]
4961 fn secure_sanitize(&mut self) {
4962 self.claimed.store(true, Ordering::Release);
4963 self.inner.get_mut().secure_sanitize();
4964 }
4965 }
4966
4967 impl<T: StableSharedSecretStorage> StableSharedSecretStorage for ConsumeOnceSecret<T> {}
4968 impl<T: StableMutableSecretStorage> StableMutableSecretStorage for ConsumeOnceSecret<T> {}
4969
4970 impl<T: SecureSanitize> fmt::Debug for ConsumeOnceSecret<T> {
4971 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4972 formatter
4973 .debug_struct("ConsumeOnceSecret")
4974 .field("contents", &"<redacted>")
4975 .finish()
4976 }
4977 }
4978}
4979
4980pub use consume_once::{AlreadyConsumedError, ConsumeOnceSecret};