basic/
basic.rs

1//! Basic example.
2
3use cryptimitives::{aead, kdf::sha256, key::x25519_ristretto};
4use cryptraits::{
5    convert::ToVec,
6    key::{Generate, KeyPair},
7    signature::Sign,
8};
9use rand_core::OsRng;
10use xxxdh::{
11    inmem, IdentityKeyStorage, OnetimeKeyStorage, PreKeyStorage, Protocol, SignatureStorage,
12};
13
14fn main() {
15    // Instantiate Alice protocol.
16
17    let alice_identity = x25519_ristretto::KeyPair::generate_with(OsRng);
18    let alice_prekey = x25519_ristretto::KeyPair::generate_with(OsRng);
19    let alice_signature = alice_identity.sign(&alice_prekey.to_public().to_vec());
20    let mut alice_protocol = Protocol::<
21        x25519_ristretto::SecretKey,
22        x25519_ristretto::EphemeralSecretKey,
23        x25519_ristretto::Signature,
24        inmem::Storage<_, _>,
25        sha256::Kdf,
26        aead::aes_gcm::Aes256Gcm,
27    >::new(alice_identity, alice_prekey, alice_signature, None);
28
29    // Instantiate Bob protocol.
30
31    let onetime_keypair = x25519_ristretto::KeyPair::generate_with(OsRng);
32
33    let bob_identity = x25519_ristretto::KeyPair::generate_with(OsRng);
34    let bob_prekey = x25519_ristretto::KeyPair::generate_with(OsRng);
35    let bob_signature = bob_identity.sign(&bob_prekey.to_public().to_vec());
36    let mut bob_protocol = Protocol::<
37        x25519_ristretto::SecretKey,
38        x25519_ristretto::EphemeralSecretKey,
39        x25519_ristretto::Signature,
40        inmem::Storage<_, _>,
41        sha256::Kdf,
42        aead::aes_gcm::Aes256Gcm,
43    >::new(
44        bob_identity,
45        bob_prekey,
46        bob_signature,
47        Some(vec![onetime_keypair]),
48    );
49
50    // Derive shared secret for Alice and prepare message for Bob.
51
52    let bob_identity = bob_protocol.storage.get_identity_key_pair().to_public();
53    let bob_prekey = bob_protocol.storage.get_prekey_pair().to_public();
54    let bob_signature = bob_protocol
55        .storage
56        .get_signature(&bob_prekey)
57        .unwrap()
58        .unwrap();
59    let onetime_key = bob_protocol.storage.provide_ontime_key().unwrap().unwrap();
60
61    let (alice_identity, alice_ephemeral_key, bob_onetime_key, alice_sk, nonce, ciphertext) =
62        alice_protocol
63            .prepare_init_msg(&bob_identity, &bob_prekey, bob_signature, onetime_key)
64            .unwrap();
65
66    // Derive shared secret for Bob using Alice credentials.
67
68    let bob_sk = bob_protocol
69        .derive_shared_secret(
70            &alice_identity,
71            &alice_ephemeral_key,
72            &bob_onetime_key,
73            &nonce,
74            &ciphertext,
75        )
76        .unwrap();
77
78    println!("Alice shared secret: {:?}", alice_sk);
79    println!("Bob shared secret: {:?}", bob_sk);
80}