@@ -94,9 +94,19 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
94
94
( x & 1 )
95
95
}
96
96
97
- /// Check equality of two 32-byte arrays in constant time.
97
+ /// Check equality of two arrays, `a` and `b`, in constant time.
98
98
///
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,
100
110
/// `0u8` will be returned:
101
111
///
102
112
/// ```
@@ -110,7 +120,7 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
110
120
/// # }
111
121
/// ```
112
122
///
113
- /// If the contents *do* match, `1u8` is returned:
123
+ /// And finally, if the contents *do* match, `1u8` is returned:
114
124
///
115
125
/// ```
116
126
/// # extern crate curve25519_dalek;
@@ -131,11 +141,27 @@ pub fn byte_is_nonzero(b: u8) -> u8 {
131
141
///
132
142
/// Returns `1u8` if `a == b` and `0u8` otherwise.
133
143
#[ 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
+
135
147
let mut x: u8 = 0 ;
136
148
137
- for i in 0 .. 32 {
149
+ for i in 0 .. a . len ( ) {
138
150
x |= a[ i] ^ b[ i] ;
139
151
}
140
152
bytes_equal_ct ( x, 0 )
141
153
}
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