iroh_base/key/
encryption.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//! The private and public keys of a node.

use std::fmt::Debug;

use aead::Buffer;
use anyhow::{anyhow, ensure, Context, Result};

pub(crate) const NONCE_LEN: usize = 24;

pub(super) fn public_ed_box(key: &ed25519_dalek::VerifyingKey) -> crypto_box::PublicKey {
    crypto_box::PublicKey::from(key.to_montgomery())
}

pub(super) fn secret_ed_box(key: &ed25519_dalek::SigningKey) -> crypto_box::SecretKey {
    crypto_box::SecretKey::from(key.to_scalar())
}

/// Shared Secret.
pub struct SharedSecret(crypto_box::ChaChaBox);

impl Debug for SharedSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SharedSecret(crypto_box::ChaChaBox)")
    }
}

impl SharedSecret {
    fn new(this: &crypto_box::SecretKey, other: &crypto_box::PublicKey) -> Self {
        SharedSecret(crypto_box::ChaChaBox::new(other, this))
    }

    /// Seals the provided cleartext.
    pub fn seal(&self, buffer: &mut dyn Buffer) {
        use aead::{AeadCore, AeadInPlace, OsRng};

        let nonce = crypto_box::ChaChaBox::generate_nonce(&mut OsRng);
        self.0
            .encrypt_in_place(&nonce, &[], buffer)
            .expect("encryption failed");

        buffer.extend_from_slice(&nonce).expect("buffer too small");
    }

    /// Opens the ciphertext, which must have been created using `Self::seal`, and places the clear text into the provided buffer.
    pub fn open(&self, buffer: &mut dyn Buffer) -> Result<()> {
        use aead::AeadInPlace;
        ensure!(buffer.len() > NONCE_LEN, "too short");

        let offset = buffer.len() - NONCE_LEN;
        let nonce: [u8; NONCE_LEN] = buffer.as_ref()[offset..]
            .try_into()
            .context("nonce wrong length")?;

        buffer.truncate(offset);
        self.0
            .decrypt_in_place(&nonce.into(), &[], buffer)
            .map_err(|e| anyhow!("decryption failed: {:?}", e))?;

        Ok(())
    }
}

impl crate::key::SecretKey {
    /// Returns the shared key for communication between this key and `other`.
    pub fn shared(&self, other: &crate::key::PublicKey) -> SharedSecret {
        let secret_key = self.secret_crypto_box();
        let public_key = other.public_crypto_box();

        SharedSecret::new(secret_key, &public_key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_seal_open_roundtrip() {
        let key_a = crate::key::SecretKey::generate();
        let key_b = crate::key::SecretKey::generate();

        seal_open_roundtrip(&key_a, &key_b);
        seal_open_roundtrip(&key_b, &key_a);
        seal_open_roundtrip(&key_a, &key_a);
    }

    fn seal_open_roundtrip(key_a: &crate::key::SecretKey, key_b: &crate::key::SecretKey) {
        let msg = b"super secret message!!!!".to_vec();
        let shared_a = key_a.shared(&key_b.public());
        let mut sealed_message = msg.clone();
        shared_a.seal(&mut sealed_message);
        let shared_b = key_b.shared(&key_a.public());
        let mut decrypted_message = sealed_message.clone();
        shared_b.open(&mut decrypted_message).unwrap();
        assert_eq!(&msg[..], &decrypted_message);
    }

    #[test]
    fn test_roundtrip_public_key() {
        let key = crypto_box::SecretKey::generate(&mut rand::thread_rng());
        let public_bytes = *key.public_key().as_bytes();
        let public_key_back = crypto_box::PublicKey::from(public_bytes);
        assert_eq!(key.public_key(), public_key_back);
    }

    #[test]
    fn test_same_public_key_api() {
        let key = crate::key::SecretKey::generate();
        let public_key1: crypto_box::PublicKey = public_ed_box(&key.public().public());
        let public_key2: crypto_box::PublicKey = secret_ed_box(&key.secret).public_key();

        assert_eq!(public_key1, public_key2);
    }

    #[test]
    fn test_same_public_key_low_level() {
        let mut rng = rand::thread_rng();
        let key = ed25519_dalek::SigningKey::generate(&mut rng);
        let public_key1 = {
            let m = key.verifying_key().to_montgomery();
            crypto_box::PublicKey::from(m)
        };

        let public_key2 = {
            let s = key.to_scalar();
            let cs = crypto_box::SecretKey::from(s);
            cs.public_key()
        };

        assert_eq!(public_key1, public_key2);
    }
}