1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright(c) 2018 3NSoft Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! This module provides constant time comparison utility, analogous to
//! crypto_verify/.../ref/verify.c

/// Compare 16-byte arrays in constant time.
pub fn compare_v16(x: &[u8], y: &[u8]) -> bool {
	let mut differentbits = 0;
	for i in 0..16 {
		differentbits |= x[i] ^ y[i];
	}
	differentbits == 0
}

/// Compare 32-byte arrays in constant time.
pub fn compare_v32(x: &[u8], y: &[u8]) -> bool {
	let mut differentbits = 0;
	for i in 0..32 {
		differentbits |= x[i] ^ y[i];
	}
	differentbits == 0
}

/// Compare byte arrays in constant time.
pub fn compare(x: &[u8], y: &[u8]) -> bool {
	let len = x.len();
	if (len ^ y.len()) != 0 { return false; }
	let mut differentbits = 0;
	for i in 0..len {
		differentbits |= x[i] ^ y[i];
	}
	differentbits == 0
}


#[cfg(test)]
mod tests {
	
	use super::{ compare_v16, compare_v32, compare };

	#[test]
	fn constant_time_comparisons() {

		let x: [u8; 55] = [4; 55];
		let mut y: [u8; 55] = [4; 55];

		assert!(compare(&x, &y));
		assert!(compare_v16(&x[0..16], &y[0..16]));
		assert!(compare_v32(&x[0..32], &y[0..32]));

		y[3] += 1;

		assert!(!compare(&x, &y));
		assert!(!compare_v16(&x[0..16], &y[0..16]));
		assert!(!compare_v32(&x[0..32], &y[0..32]));

	}

}