diff --git a/benches/x25519.rs b/benches/x25519.rs index e5d77d2..fee3fa9 100644 --- a/benches/x25519.rs +++ b/benches/x25519.rs @@ -25,12 +25,12 @@ use x25519_dalek::EphemeralSecret; use x25519_dalek::PublicKey; fn bench_diffie_hellman(c: &mut Criterion) { - let bob_secret = EphemeralSecret::new(&mut OsRng); + let bob_secret = EphemeralSecret::new(OsRng); let bob_public = PublicKey::from(&bob_secret); c.bench_function("diffie_hellman", move |b| { b.iter_with_setup( - || EphemeralSecret::new(&mut OsRng), + || EphemeralSecret::new(OsRng), |alice_secret| alice_secret.diffie_hellman(&bob_public), ) }); diff --git a/src/x25519.rs b/src/x25519.rs index ed4fe9d..01b22bb 100644 --- a/src/x25519.rs +++ b/src/x25519.rs @@ -60,6 +60,14 @@ impl PublicKey { } } +impl AsRef<[u8]> for PublicKey { + /// View this public key as a byte array. + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + /// A short-lived Diffie-Hellman secret key that can only be used to compute a single /// [`SharedSecret`]. /// @@ -174,7 +182,7 @@ impl StaticSecret { /// Perform a Diffie-Hellman key agreement between `self` and /// `their_public` key to produce a `SharedSecret`. pub fn diffie_hellman(&self, their_public: &PublicKey) -> SharedSecret { - SharedSecret(&self.0 * their_public.0) + SharedSecret(self.0 * their_public.0) } /// Generate an x25519 key. @@ -187,9 +195,16 @@ impl StaticSecret { } /// Extract this key's bytes for serialization. + #[inline] pub fn to_bytes(&self) -> [u8; 32] { self.0.to_bytes() } + + /// View this key as a byte array. + #[inline] + pub fn as_bytes(&self) -> &[u8; 32] { + self.0.as_bytes() + } } impl From<[u8; 32]> for StaticSecret { @@ -206,6 +221,14 @@ impl<'a> From<&'a StaticSecret> for PublicKey { } } +impl AsRef<[u8]> for StaticSecret { + /// View this key as a byte array. + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + /// The result of a Diffie-Hellman key exchange. /// /// Each party computes this using their [`EphemeralSecret`] or [`StaticSecret`] and their @@ -266,6 +289,14 @@ impl SharedSecret { } } +impl AsRef<[u8]> for SharedSecret { + /// View this shared secret key as a byte array. + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + /// "Decode" a scalar from a 32-byte array. /// /// By "decode" here, what is really meant is applying key clamping by twiddling