Skip to content

Commit b5f87b5

Browse files
plotskogwqisislovecruft
authored andcommitted
Make arrays_equal() work for any size &[u8], as long as sizes are equal.
1 parent 55bad33 commit b5f87b5

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

src/subtle.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,19 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
9494
(x & 1)
9595
}
9696

97-
/// Check equality of two 32-byte arrays in constant time.
97+
/// Check equality of two arrays, `a` and `b`, in constant time.
9898
///
99-
/// If the contents of the arrays do *not* match,
99+
/// There is a `debug_assert!` that the two arrays are of equal length. For
100+
/// example, the following code will panic:
101+
///
102+
/// ```rust,ignore
103+
/// let a: [u8; 3] = [0, 0, 0];
104+
/// let b: [u8; 4] = [0, 0, 0, 0];
105+
///
106+
/// assert!(arrays_equal(&a, &b) == 1);
107+
/// ```
108+
///
109+
/// However, if the arrays are equal length, but their contents do *not* match,
100110
/// `0u8` will be returned:
101111
///
102112
/// ```
@@ -110,7 +120,7 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
110120
/// # }
111121
/// ```
112122
///
113-
/// If the contents *do* match, `1u8` is returned:
123+
/// And finally, if the contents *do* match, `1u8` is returned:
114124
///
115125
/// ```
116126
/// # extern crate curve25519_dalek;
@@ -131,11 +141,27 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
131141
///
132142
/// Returns `1u8` if `a == b` and `0u8` otherwise.
133143
#[inline(always)]
134-
pub fn arrays_equal(a: &[u8; 32], b: &[u8; 32]) -> u8 {
144+
pub fn arrays_equal(a: &[u8], b: &[u8]) -> u8 {
145+
debug_assert!(a.len() == b.len());
146+
135147
let mut x: u8 = 0;
136148

137-
for i in 0..32 {
149+
for i in 0 .. a.len() {
138150
x |= a[i] ^ b[i];
139151
}
140152
bytes_equal_ct(x, 0)
141153
}
154+
155+
#[cfg(test)]
156+
mod test {
157+
use super::*;
158+
159+
#[test]
160+
#[should_panic]
161+
fn arrays_equal_different_lengths() {
162+
let a: [u8; 3] = [0, 0, 0];
163+
let b: [u8; 4] = [0, 0, 0, 0];
164+
165+
assert!(arrays_equal(&a, &b) == 1);
166+
}
167+
}

0 commit comments

Comments
 (0)