1use rand_core::{OsRng, RngCore};
2use x25519_dalek::{PublicKey as X25519PublicKey, SharedSecret, StaticSecret};
3
4pub use x25519_dalek::PublicKey;
6
7pub struct KeyPair {
9 pub secret: StaticSecret,
10 pub public: X25519PublicKey,
11}
12
13pub fn generate_key_pair() -> KeyPair {
14 let secret = StaticSecret::random_from_rng(OsRng);
15 let public = X25519PublicKey::from(&secret);
16 KeyPair { secret, public }
17}
18
19pub fn derive_shared_secret(secret: &StaticSecret, their_public: &X25519PublicKey) -> SharedSecret {
20 secret.diffie_hellman(their_public)
21}
22
23pub fn generate_random_bytes<const N: usize>() -> [u8; N] {
24 let mut bytes = [0u8; N];
25 OsRng.fill_bytes(&mut bytes);
26 bytes
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn test_key_exchange() {
35 let alice = generate_key_pair();
36 let bob = generate_key_pair();
37
38 let alice_shared = derive_shared_secret(&alice.secret, &bob.public);
39 let bob_shared = derive_shared_secret(&bob.secret, &alice.public);
40
41 assert_eq!(alice_shared.as_bytes(), bob_shared.as_bytes());
42 }
43}