Add compare_ct function which will return Result of bool or UnkownCryptoError
use rand::{OsRng, RngCore};
use errors;
+use constant_time_eq::constant_time_eq;
#[inline(never)]
/// Return a random byte vector of a given length. This uses the [rand](https://crates.io/crates/rand) crate,
@@ -43,6 +44,18 @@ pub fn gen_rand_key(len: usize) -> Result<Vec<u8>, errors::UnknownCryptoError> {
}
}
+pub fn compare_ct(a: &[u8], b: &[u8]) -> Result<bool, errors::UnknownCryptoError> {
+
+ if a.len() != b.len() {
+ return Err(errors::UnknownCryptoError)
+ }
+
+ match constant_time_eq(a, b) {
+ true => Ok(true),
+ false => Err(errors::UnknownCryptoError)
+ }
+}
+
#[test]
fn rand_key_len_ok() {
@@ -58,3 +71,34 @@ fn rand_key_error() {
assert_eq!(err, errors::UnknownCryptoError);
}
+
+#[test]
+fn test_ct_eq_ok() {
+ let buf_1 = vec![0x06; 10];
+ let buf_2 = vec![0x06; 10];
+
+ assert_eq!(compare_ct(&buf_1, &buf_2).unwrap(), true);
+ assert_eq!(compare_ct(&buf_2, &buf_1).unwrap(), true);
+}
+
+#[test]
+fn test_ct_eq_wrong_len() {
+
+ let buf_1 = vec![0x06; 10];
+ let buf_2 = vec![0x06; 5];
+
+ assert!(compare_ct(&buf_1, &buf_2).is_err());
+ assert!(compare_ct(&buf_2, &buf_1).is_err());
+
+}
+
+#[test]
+fn test_ct_eq_err() {
+
+ let buf_1 = vec![0x06; 10];
+ let buf_2 = vec![0x76; 10];
+
+ assert!(compare_ct(&buf_1, &buf_2).is_err());
+ assert!(compare_ct(&buf_2, &buf_1).is_err());
+
+}
\ No newline at end of file
