Skip to content

Commit

Permalink
feat: simplify zeroizing and add test to DHKE (#197)
Browse files Browse the repository at this point in the history
Simplifies the implementation of zeroizing support for Diffie-Hellman
key exchanges and improves test coverage.

Currently, the `DiffieHellmanSharedSecret` struct has manual
implementations of `zeroize` and `drop` to handle zeroizing. Now that we
have a more modern version of `zeroize` as a dependency, we can do
better. This PR uses that crate's `Zeroize` and `ZeroizeOnDrop` derived
traits to handle this more cleanly. It also adds a sanity check that the
byte representations of both sides of a key exchange match, which
improves test coverage.

Partially addresses #196.
  • Loading branch information
SWvheerden authored Aug 21, 2023
2 parents 2aa46d0 + 1f77623 commit 1e6f603
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions src/dhke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@

use core::ops::Mul;

use zeroize::Zeroize;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::keys::PublicKey;

/// A type to hold a DH secret key.
/// The result of a Diffie-Hellman key exchange
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct DiffieHellmanSharedSecret<P>(P)
where P: Zeroize;

Expand All @@ -35,20 +36,31 @@ where
}
}

impl<P> Zeroize for DiffieHellmanSharedSecret<P>
where P: Zeroize
{
/// Zeroize the shared secret's underlying public key
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg(test)]
mod test {
use rand_core::OsRng;

impl<P> Drop for DiffieHellmanSharedSecret<P>
where P: Zeroize
{
/// Zeroize the shared secret when out of scope or otherwise dropped
fn drop(&mut self) {
self.zeroize();
use super::DiffieHellmanSharedSecret;
use crate::{
keys::{PublicKey, SecretKey},
ristretto::{RistrettoPublicKey, RistrettoSecretKey},
};

#[test]
fn test_dhke() {
// Generate two key pairs
let mut rng = OsRng;

let sk1 = RistrettoSecretKey::random(&mut rng);
let pk1 = RistrettoPublicKey::from_secret_key(&sk1);

let sk2 = RistrettoSecretKey::random(&mut rng);
let pk2 = RistrettoPublicKey::from_secret_key(&sk2);

// Assert that both sides of a key exchange match
let left = DiffieHellmanSharedSecret::<RistrettoPublicKey>::new(&sk1, &pk2);
let right = DiffieHellmanSharedSecret::<RistrettoPublicKey>::new(&sk2, &pk1);

assert_eq!(left.as_bytes(), right.as_bytes());
}
}

0 comments on commit 1e6f603

Please sign in to comment.