Skip to content

Commit

Permalink
add constructor from bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
SWvheerden committed Jun 28, 2024
1 parent 13cd141 commit bef9db3
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/dhke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@
use core::ops::Mul;

use subtle::{Choice, ConstantTimeEq};
use tari_utilities::ByteArrayError;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::keys::PublicKey;

/// The result of a Diffie-Hellman key exchange
#[derive(PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct DiffieHellmanSharedSecret<P>(pub P)
pub struct DiffieHellmanSharedSecret<P>(P)
where P: PublicKey;

impl<P> DiffieHellmanSharedSecret<P>
Expand All @@ -31,6 +32,12 @@ where
Self(sk * pk)
}

// Constructs a new Diffie-Hellman key exchange from an already created Diffie-Hellman key exchange
pub fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError> {
let pk = P::from_canonical_bytes(bytes)?;
Ok(Self(pk))
}

/// Get the shared secret as a byte array
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
Expand Down Expand Up @@ -71,5 +78,9 @@ mod test {
let right = DiffieHellmanSharedSecret::<RistrettoPublicKey>::new(&sk2, &pk1);

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

let left_bytes = left.as_bytes();
let new_left = DiffieHellmanSharedSecret::<RistrettoPublicKey>::from_canonical_bytes(left_bytes).unwrap();
assert_eq!(left.as_bytes(), new_left.as_bytes());
}
}

0 comments on commit bef9db3

Please sign in to comment.