1 // Copyright 2020 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 #![cfg(any(not(target_arch = "wasm32"), feature = "wasm32_c"))]
16 use ring::{constant_time, error, rand};
17
18 #[cfg(target_arch = "wasm32")]
19 use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
20
21 #[cfg(target_arch = "wasm32")]
22 wasm_bindgen_test_configure!(run_in_browser);
23
24 // This logic is loosly based on BoringSSL's `TEST(ConstantTimeTest, MemCmp)`.
25 #[test]
test_verify_slices_are_equal()26 fn test_verify_slices_are_equal() {
27 let initial: [u8; 256] = rand::generate(&rand::SystemRandom::new()).unwrap().expose();
28
29 {
30 let copy = initial;
31 for len in 0..copy.len() {
32 // Not equal because the lengths do not match.
33 assert_eq!(
34 constant_time::verify_slices_are_equal(&initial, ©[..len]),
35 Err(error::Unspecified)
36 );
37 // Equal lengths and equal contents.
38 assert_eq!(
39 constant_time::verify_slices_are_equal(&initial[..len], ©[..len]),
40 Ok(())
41 );
42 }
43 // Equal lengths and equal contents.
44 assert_eq!(
45 constant_time::verify_slices_are_equal(&initial, ©),
46 Ok(())
47 );
48 }
49
50 for i in 0..initial.len() {
51 for bit in 0..8 {
52 let mut copy = initial;
53 copy[i] ^= 1u8 << bit;
54
55 for len in 0..=initial.len() {
56 // We flipped at least one bit in `copy`.
57 assert_ne!(&initial[..], ©[..]);
58
59 let a = &initial[..len];
60 let b = ©[..len];
61
62 let expected_result = if i < len {
63 // The flipped bit is within `b` so `a` and `b` are not equal.
64 Err(error::Unspecified)
65 } else {
66 // The flipped bit is outside of `b` so `a` and `b` are equal.
67 Ok(())
68 };
69 assert_eq!(a == b, expected_result.is_ok()); // Sanity check.
70 assert_eq!(
71 constant_time::verify_slices_are_equal(&a, &b),
72 expected_result
73 );
74 assert_eq!(
75 constant_time::verify_slices_are_equal(&b, &a),
76 expected_result
77 );
78 }
79 }
80 }
81 }
82