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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use crate::{
    constants::TAGLEN,
    error::{Error, InitStage, StateProblem},
    types::Cipher,
};

pub(crate) struct CipherState {
    cipher:  Box<dyn Cipher>,
    n:       u64,
    has_key: bool,
}

impl CipherState {
    pub fn new(cipher: Box<dyn Cipher>) -> Self {
        Self { cipher, n: 0, has_key: false }
    }

    pub fn name(&self) -> &'static str {
        self.cipher.name()
    }

    pub fn set(&mut self, key: &[u8], n: u64) {
        self.cipher.set(key);
        self.n = n;
        self.has_key = true;
    }

    pub fn encrypt_ad(
        &mut self,
        authtext: &[u8],
        plaintext: &[u8],
        out: &mut [u8],
    ) -> Result<usize, Error> {
        if !self.has_key {
            return Err(StateProblem::MissingKeyMaterial.into());
        }

        validate_nonce(self.n)?;
        let len = self.cipher.encrypt(self.n, authtext, plaintext, out);

        // We have validated this will not wrap around.
        self.n += 1;

        Ok(len)
    }

    pub fn decrypt_ad(
        &mut self,
        authtext: &[u8],
        ciphertext: &[u8],
        out: &mut [u8],
    ) -> Result<usize, Error> {
        if (ciphertext.len() < TAGLEN) || out.len() < (ciphertext.len() - TAGLEN) {
            return Err(Error::Decrypt);
        }

        if !self.has_key {
            return Err(StateProblem::MissingKeyMaterial.into());
        }

        validate_nonce(self.n)?;
        let len = self.cipher.decrypt(self.n, authtext, ciphertext, out)?;

        // We have validated this will not wrap around.
        self.n += 1;

        Ok(len)
    }

    pub fn encrypt(&mut self, plaintext: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        self.encrypt_ad(&[0u8; 0], plaintext, out)
    }

    pub fn decrypt(&mut self, ciphertext: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        self.decrypt_ad(&[0u8; 0], ciphertext, out)
    }

    pub fn rekey(&mut self) {
        self.cipher.rekey();
    }

    pub fn rekey_manually(&mut self, key: &[u8]) {
        self.cipher.set(key);
    }

    pub fn nonce(&self) -> u64 {
        self.n
    }

    pub fn set_nonce(&mut self, nonce: u64) {
        self.n = nonce;
    }
}

pub(crate) struct CipherStates(pub CipherState, pub CipherState);

impl CipherStates {
    pub fn new(initiator: CipherState, responder: CipherState) -> Result<Self, Error> {
        if initiator.name() != responder.name() {
            return Err(InitStage::ValidateCipherTypes.into());
        }

        Ok(CipherStates(initiator, responder))
    }

    pub fn rekey_initiator(&mut self) {
        self.0.rekey()
    }

    pub fn rekey_initiator_manually(&mut self, key: &[u8]) {
        self.0.rekey_manually(key)
    }

    pub fn rekey_responder(&mut self) {
        self.1.rekey()
    }

    pub fn rekey_responder_manually(&mut self, key: &[u8]) {
        self.1.rekey_manually(key)
    }
}

pub(crate) struct StatelessCipherState {
    cipher:  Box<dyn Cipher>,
    has_key: bool,
}

impl StatelessCipherState {
    pub fn encrypt_ad(
        &self,
        nonce: u64,
        authtext: &[u8],
        plaintext: &[u8],
        out: &mut [u8],
    ) -> Result<usize, Error> {
        if !self.has_key {
            return Err(StateProblem::MissingKeyMaterial.into());
        }

        validate_nonce(nonce)?;

        Ok(self.cipher.encrypt(nonce, authtext, plaintext, out))
    }

    pub fn decrypt_ad(
        &self,
        nonce: u64,
        authtext: &[u8],
        ciphertext: &[u8],
        out: &mut [u8],
    ) -> Result<usize, Error> {
        if (ciphertext.len() < TAGLEN) || out.len() < (ciphertext.len() - TAGLEN) {
            return Err(Error::Decrypt);
        }

        if !self.has_key {
            return Err(StateProblem::MissingKeyMaterial.into());
        }

        validate_nonce(nonce)?;

        self.cipher.decrypt(nonce, authtext, ciphertext, out)
    }

    pub fn encrypt(&self, nonce: u64, plaintext: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        self.encrypt_ad(nonce, &[], plaintext, out)
    }

    pub fn decrypt(&self, nonce: u64, ciphertext: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        self.decrypt_ad(nonce, &[], ciphertext, out)
    }

    pub fn rekey(&mut self) {
        self.cipher.rekey()
    }

    pub fn rekey_manually(&mut self, key: &[u8]) {
        self.cipher.set(key);
    }
}

/// Validates that a nonce value has not exceeded the maximum
/// defined by the Noise spec.
fn validate_nonce(current: u64) -> Result<(), Error> {
    // 2^64-1 is reserved and may not be used in the state machine (5.1).
    //
    // It is used by the default cipher rekey function (4.2).
    if current == u64::MAX {
        Err(Error::State(StateProblem::Exhausted))
    } else {
        Ok(())
    }
}

impl From<CipherState> for StatelessCipherState {
    fn from(other: CipherState) -> Self {
        Self { cipher: other.cipher, has_key: other.has_key }
    }
}

pub(crate) struct StatelessCipherStates(pub StatelessCipherState, pub StatelessCipherState);

impl From<CipherStates> for StatelessCipherStates {
    fn from(other: CipherStates) -> Self {
        StatelessCipherStates(other.0.into(), other.1.into())
    }
}

impl StatelessCipherStates {
    pub fn rekey_initiator(&mut self) {
        self.0.rekey()
    }

    pub fn rekey_initiator_manually(&mut self, key: &[u8]) {
        self.0.rekey_manually(key)
    }

    pub fn rekey_responder(&mut self) {
        self.1.rekey()
    }

    pub fn rekey_responder_manually(&mut self, key: &[u8]) {
        self.1.rekey_manually(key)
    }
}