From 0a66954a57450910742eb80a887c59532ac9d894 Mon Sep 17 00:00:00 2001
From: Aaron Feickert <66188213+AaronFeickert@users.noreply.github.com>
Date: Mon, 15 Jan 2024 16:39:45 -0600
Subject: [PATCH] Add constant-time trait bounds
---
Cargo.toml | 4 +++-
src/dhke.rs | 15 ++++++++++++---
src/keys.rs | 7 +++++--
src/ristretto/ristretto_keys.rs | 23 ++++++++++++++++++-----
4 files changed, 38 insertions(+), 11 deletions(-)
diff --git a/Cargo.toml b/Cargo.toml
index 8be02791..0f16442e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,6 +24,7 @@ rand_core = { version = "0.6" , default-features = false}
serde = { version = "1.0", optional = true }
sha3 = { version = "0.10", default-features = false }
snafu = { version = "0.7", default-features = false}
+subtle = { version = "2.5.0", default-features = false }
zeroize = {version = "1" , default-features = false}
[dev-dependencies]
@@ -48,6 +49,7 @@ std = [
"serde?/std",
"sha3/std",
"snafu/std",
+ "subtle/std",
"tari_utilities/std",
"zeroize/std",
]
@@ -61,4 +63,4 @@ crate-type = ["lib", "cdylib"]
[[bench]]
name = "benches"
path = "benches/mod.rs"
-harness = false
\ No newline at end of file
+harness = false
diff --git a/src/dhke.rs b/src/dhke.rs
index 41c08c93..2282ab89 100644
--- a/src/dhke.rs
+++ b/src/dhke.rs
@@ -11,18 +11,19 @@
use core::ops::Mul;
+use subtle::{Choice, ConstantTimeEq};
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::keys::PublicKey;
/// The result of a Diffie-Hellman key exchange
-#[derive(Zeroize, ZeroizeOnDrop)]
+#[derive(PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct DiffieHellmanSharedSecret
(P)
-where P: Zeroize;
+where P: PublicKey;
impl
DiffieHellmanSharedSecret
where
- P: PublicKey + Zeroize,
+ P: PublicKey,
for<'a> &'a
::K: Mul<&'a P, Output = P>,
{
/// Perform a Diffie-Hellman key exchange
@@ -36,6 +37,14 @@ where
}
}
+impl
ConstantTimeEq for DiffieHellmanSharedSecret
+where P: PublicKey
+{
+ fn ct_eq(&self, other: &DiffieHellmanSharedSecret
) -> Choice {
+ self.0.ct_eq(&other.0)
+ }
+}
+
#[cfg(test)]
mod test {
use rand_core::OsRng;
diff --git a/src/keys.rs b/src/keys.rs
index b1692f26..5032ed55 100644
--- a/src/keys.rs
+++ b/src/keys.rs
@@ -9,6 +9,7 @@
use core::ops::Add;
use rand_core::{CryptoRng, RngCore};
+use subtle::ConstantTimeEq;
use tari_utilities::{ByteArray, ByteArrayError};
use zeroize::{Zeroize, ZeroizeOnDrop};
@@ -27,7 +28,7 @@ use zeroize::{Zeroize, ZeroizeOnDrop};
/// let p = RistrettoPublicKey::from_secret_key(&k);
/// ```
pub trait SecretKey:
- ByteArray + Clone + PartialEq + Eq + Add