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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! # Authenticated encryption functions
//!
//! Implements libsodium's secret-key authenticated crypto boxes.
//!
//! For details, refer to [libsodium docs](https://libsodium.gitbook.io/doc/secret-key_cryptography/secretbox).
//!
//! ## Classic API example
//!
//! ```
//! use dryoc::classic::crypto_secretbox::{
//!     crypto_secretbox_easy, crypto_secretbox_keygen, crypto_secretbox_open_easy, Key, Nonce,
//! };
//! use dryoc::constants::{CRYPTO_SECRETBOX_MACBYTES, CRYPTO_SECRETBOX_NONCEBYTES};
//! use dryoc::rng::randombytes_buf;
//! use dryoc::types::*;
//!
//! let key: Key = crypto_secretbox_keygen();
//! let nonce = Nonce::gen();
//!
//! let message = "I Love Doge!";
//!
//! // Encrypt
//! let mut ciphertext = vec![0u8; message.len() + CRYPTO_SECRETBOX_MACBYTES];
//! crypto_secretbox_easy(&mut ciphertext, message.as_bytes(), &nonce, &key)
//!     .expect("encrypt failed");
//!
//! // Decrypt
//! let mut decrypted = vec![0u8; ciphertext.len() - CRYPTO_SECRETBOX_MACBYTES];
//! crypto_secretbox_open_easy(&mut decrypted, &ciphertext, &nonce, &key).expect("decrypt failed");
//!
//! assert_eq!(decrypted, message.as_bytes());
//! ```

use crate::classic::crypto_secretbox_impl::*;
use crate::constants::{
    CRYPTO_SECRETBOX_KEYBYTES, CRYPTO_SECRETBOX_MACBYTES, CRYPTO_SECRETBOX_NONCEBYTES,
};
use crate::error::Error;
use crate::rng::copy_randombytes;
use crate::types::*;

/// Secret box message authentication code.
pub type Mac = [u8; CRYPTO_SECRETBOX_MACBYTES];
/// Nonce for secret key authenticated boxes.
pub type Nonce = [u8; CRYPTO_SECRETBOX_NONCEBYTES];
/// Key (or secret) for secret key authenticated boxes.
pub type Key = [u8; CRYPTO_SECRETBOX_KEYBYTES];

/// In-place variant of [`crypto_secretbox_keygen`]
pub fn crypto_secretbox_keygen_inplace(key: &mut Key) {
    copy_randombytes(key)
}

/// Generates a random key using
/// [`copy_randombytes`](crate::rng::copy_randombytes).
pub fn crypto_secretbox_keygen() -> Key {
    Key::gen()
}

/// Detached version of [`crypto_secretbox_easy`].
///
/// Compatible with libsodium's `crypto_secretbox_detached`.
pub fn crypto_secretbox_detached(
    ciphertext: &mut [u8],
    mac: &mut Mac,
    message: &[u8],
    nonce: &Nonce,
    key: &Key,
) {
    ciphertext[..message.len()].copy_from_slice(message);
    crypto_secretbox_detached_inplace(ciphertext, mac, nonce, key);
}

/// Detached version of [`crypto_secretbox_open_easy`].
///
/// Compatible with libsodium's `crypto_secretbox_open_detached`.
pub fn crypto_secretbox_open_detached(
    message: &mut [u8],
    mac: &Mac,
    ciphertext: &[u8],
    nonce: &Nonce,
    key: &Key,
) -> Result<(), Error> {
    let c_len = ciphertext.len();
    message[..c_len].copy_from_slice(ciphertext);
    crypto_secretbox_open_detached_inplace(message, mac, nonce, key)
}

/// Encrypts `message` with `nonce` and `key`.
///
/// Compatible with libsodium's `crypto_secretbox_easy`.
pub fn crypto_secretbox_easy(
    ciphertext: &mut [u8],
    message: &[u8],
    nonce: &Nonce,
    key: &Key,
) -> Result<(), Error> {
    let mut mac = Mac::default();
    crypto_secretbox_detached(
        &mut ciphertext[CRYPTO_SECRETBOX_MACBYTES..],
        &mut mac,
        message,
        nonce,
        key,
    );

    ciphertext[..CRYPTO_SECRETBOX_MACBYTES].copy_from_slice(&mac);

    Ok(())
}

/// Decrypts `ciphertext` with `nonce` and `key`.
///
/// Compatible with libsodium's `crypto_secretbox_open_easy`.
pub fn crypto_secretbox_open_easy(
    message: &mut [u8],
    ciphertext: &[u8],
    nonce: &Nonce,
    key: &Key,
) -> Result<(), Error> {
    if ciphertext.len() < CRYPTO_SECRETBOX_MACBYTES {
        Err(dryoc_error!(format!(
            "Impossibly small box ({} < {}",
            ciphertext.len(),
            CRYPTO_SECRETBOX_MACBYTES
        )))
    } else {
        let (mac, ciphertext) = ciphertext.split_at(CRYPTO_SECRETBOX_MACBYTES);
        let mac = mac.as_array();
        crypto_secretbox_open_detached(message, mac, ciphertext, nonce, key)
    }
}

/// Encrypts `message` with `nonce` and `key` in-place, without allocating
/// additional memory for the ciphertext.
pub fn crypto_secretbox_easy_inplace(
    data: &mut [u8],
    nonce: &Nonce,
    key: &Key,
) -> Result<(), Error> {
    data.rotate_right(CRYPTO_SECRETBOX_MACBYTES);
    let (mac, data) = data.split_at_mut(CRYPTO_SECRETBOX_MACBYTES);
    let mac = mac.as_mut_array();

    crypto_secretbox_detached_inplace(data, mac, nonce, key);

    Ok(())
}

/// Decrypts `ciphertext` with `nonce` and `key` in-place, without allocating
/// additional memory for the message.
pub fn crypto_secretbox_open_easy_inplace(
    ciphertext: &mut [u8],
    nonce: &Nonce,
    key: &Key,
) -> Result<(), Error> {
    if ciphertext.len() < CRYPTO_SECRETBOX_MACBYTES {
        Err(dryoc_error!(format!(
            "Impossibly small box ({} < {}",
            ciphertext.len(),
            CRYPTO_SECRETBOX_MACBYTES
        )))
    } else {
        let (mac, data) = ciphertext.split_at_mut(CRYPTO_SECRETBOX_MACBYTES);
        let mac = mac.as_array();

        crypto_secretbox_open_detached_inplace(data, mac, nonce, key)?;

        ciphertext.rotate_left(CRYPTO_SECRETBOX_MACBYTES);

        Ok(())
    }
}

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

    #[test]
    fn test_crypto_secretbox_easy() {
        for i in 0..20 {
            use base64::engine::general_purpose;
            use base64::Engine as _;
            use sodiumoxide::crypto::secretbox;
            use sodiumoxide::crypto::secretbox::{Key as SOKey, Nonce as SONonce};

            let key: Key = crypto_secretbox_keygen();
            let nonce = Nonce::gen();

            let words = vec!["love Doge".to_string(); i];
            let message = words.join(" <3 ");

            let mut ciphertext = vec![0u8; message.len() + CRYPTO_SECRETBOX_MACBYTES];
            crypto_secretbox_easy(&mut ciphertext, message.as_bytes(), &nonce, &key)
                .expect("encrypt failed");
            let so_ciphertext = secretbox::seal(
                message.as_bytes(),
                &SONonce::from_slice(&nonce).unwrap(),
                &SOKey::from_slice(&key).unwrap(),
            );
            assert_eq!(
                general_purpose::STANDARD.encode(&ciphertext),
                general_purpose::STANDARD.encode(&so_ciphertext)
            );

            let mut decrypted = vec![0u8; message.len()];
            crypto_secretbox_open_easy(&mut decrypted, &ciphertext, &nonce, &key)
                .expect("decrypt failed");
            let so_decrypted = secretbox::open(
                &ciphertext,
                &SONonce::from_slice(&nonce).unwrap(),
                &SOKey::from_slice(&key).unwrap(),
            )
            .unwrap();

            assert_eq!(decrypted, message.as_bytes());
            assert_eq!(decrypted, so_decrypted);
        }
    }

    #[test]
    fn test_crypto_secretbox_easy_inplace() {
        for i in 0..20 {
            use base64::engine::general_purpose;
            use base64::Engine as _;
            use sodiumoxide::crypto::secretbox;
            use sodiumoxide::crypto::secretbox::{Key as SOKey, Nonce as SONonce};

            let key = crypto_secretbox_keygen();
            let nonce = Nonce::gen();

            let words = vec!["love Doge".to_string(); i];
            let message: Vec<u8> = words.join(" <3 ").into();
            let message_copy = message.clone();

            let mut ciphertext = message.clone();
            ciphertext.resize(message.len() + CRYPTO_SECRETBOX_MACBYTES, 0);
            crypto_secretbox_easy_inplace(&mut ciphertext, &nonce, &key).expect("encrypt failed");
            let so_ciphertext = secretbox::seal(
                &message_copy,
                &SONonce::from_slice(&nonce).unwrap(),
                &SOKey::from_slice(&key).unwrap(),
            );
            assert_eq!(
                general_purpose::STANDARD.encode(&ciphertext),
                general_purpose::STANDARD.encode(&so_ciphertext)
            );

            let mut decrypted = ciphertext.clone();
            crypto_secretbox_open_easy_inplace(&mut decrypted, &nonce, &key)
                .expect("decrypt failed");
            decrypted.resize(ciphertext.len() - CRYPTO_SECRETBOX_MACBYTES, 0);
            let so_decrypted = secretbox::open(
                &ciphertext,
                &SONonce::from_slice(&nonce).unwrap(),
                &SOKey::from_slice(&key).unwrap(),
            )
            .expect("decrypt failed");

            assert_eq!(&decrypted, &message_copy);
            assert_eq!(decrypted, so_decrypted);
        }
    }
}