Merge pull request #96 from dlblv/fix/add-secret-as-bytes

Add `.as_bytes()` method for `StaticSecret`
This commit is contained in:
Tony Arcieri 2023-02-17 09:52:53 -07:00 committed by GitHub
commit 3194759f6e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 3 deletions

View file

@ -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),
)
});

View file

@ -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