1use crate::{c, error};
18
19pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
24 if a.len() != b.len() {
25 return Err(error::Unspecified);
26 }
27 let result = unsafe { CRYPTO_memcmp(a.as_ptr(), b.as_ptr(), a.len()) };
28 match result {
29 0 => Ok(()),
30 _ => Err(error::Unspecified),
31 }
32}
33
34prefixed_extern! {
35 fn CRYPTO_memcmp(a: *const u8, b: *const u8, len: c::size_t) -> c::int;
36}
37
38pub(crate) fn xor<const N: usize>(mut a: [u8; N], b: [u8; N]) -> [u8; N] {
39 a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a ^= *b);
42 a
43}
44
45#[inline(always)]
48pub(crate) fn xor_assign_at_start<'a>(
49 a: impl IntoIterator<Item = &'a mut u8>,
50 b: impl IntoIterator<Item = &'a u8>,
51) {
52 a.into_iter().zip(b).for_each(|(a, b)| *a ^= *b);
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::limb::LimbMask;
59 use crate::{bssl, error, rand};
60
61 #[test]
62 fn test_constant_time() -> Result<(), error::Unspecified> {
63 prefixed_extern! {
64 fn bssl_constant_time_test_main() -> bssl::Result;
65 }
66 Result::from(unsafe { bssl_constant_time_test_main() })
67 }
68
69 #[test]
70 fn constant_time_conditional_memcpy() -> Result<(), error::Unspecified> {
71 let rng = rand::SystemRandom::new();
72 for _ in 0..100 {
73 let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
74 let input = rand::generate::<[u8; 256]>(&rng)?.expose();
75
76 let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) == 0;
78
79 let ref_in = input;
80 let ref_out = if b { input } else { out };
81
82 prefixed_extern! {
83 fn bssl_constant_time_test_conditional_memcpy(dst: &mut [u8; 256], src: &[u8; 256], b: LimbMask);
84 }
85 unsafe {
86 bssl_constant_time_test_conditional_memcpy(
87 &mut out,
88 &input,
89 if b { LimbMask::True } else { LimbMask::False },
90 )
91 }
92 assert_eq!(ref_in, input);
93 assert_eq!(ref_out, out);
94 }
95
96 Ok(())
97 }
98
99 #[test]
100 fn constant_time_conditional_memxor() -> Result<(), error::Unspecified> {
101 let rng = rand::SystemRandom::new();
102 for _ in 0..256 {
103 let mut out = rand::generate::<[u8; 256]>(&rng)?.expose();
104 let input = rand::generate::<[u8; 256]>(&rng)?.expose();
105
106 let b = (rand::generate::<[u8; 1]>(&rng)?.expose()[0] & 0x0f) != 0;
108
109 let ref_in = input;
110 let ref_out = if b { xor(out, ref_in) } else { out };
111
112 prefixed_extern! {
113 fn bssl_constant_time_test_conditional_memxor(dst: &mut [u8; 256], src: &[u8; 256], b: LimbMask);
114 }
115 unsafe {
116 bssl_constant_time_test_conditional_memxor(
117 &mut out,
118 &input,
119 if b { LimbMask::True } else { LimbMask::False },
120 );
121 }
122
123 assert_eq!(ref_in, input);
124 assert_eq!(ref_out, out);
125 }
126
127 Ok(())
128 }
129}