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
//! Secret-key authenticated encryption
//!
//! A single key is used both to encrypt/sign and verify/decrypt messages. For this reason, it is critical to keep the key confidential.
//!
//! # Examples
//! ```
//! let key_data =[64,33,195,234,107,63,107,237,113,199,
//!     183,130,203,194,247,31,76,51,203,163,
//!     126,238,206,125,225,74,103,105,133,181,
//!     61,189];
//!
//! let key         = libhydrogen::secretbox::Key::from(key_data);
//! let context     = libhydrogen::secretbox::Context::default();
//! let ciphertext  = libhydrogen::secretbox::encrypt(b"hello world", 1, &context, &key);
//!
//! let decrypted   = libhydrogen::secretbox::decrypt(&ciphertext, 1, &context, &key).unwrap();
//!
//! println!("{}", String::from_utf8(decrypted).unwrap());
//! ```

use super::ensure_initialized;
use crate::errors::*;
use crate::ffi;
use crate::utils;
use std::mem;

pub const CONTEXTBYTES: usize = ffi::hydro_secretbox_CONTEXTBYTES as usize;
pub const HEADERBYTES: usize = ffi::hydro_secretbox_HEADERBYTES as usize;
pub const KEYBYTES: usize = ffi::hydro_secretbox_KEYBYTES as usize;
pub const PROBEBYTES: usize = ffi::hydro_secretbox_PROBEBYTES as usize;

#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
pub struct Context([u8; CONTEXTBYTES]);

#[derive(Debug, Clone)]
pub struct Key([u8; KEYBYTES]);

#[derive(Debug, Clone)]
pub struct Probe([u8; PROBEBYTES]);

pub fn encrypt(input: &[u8], msg_id: u64, context: &Context, key: &Key) -> Vec<u8> {
    let out_len = HEADERBYTES + input.len();
    let mut out = Vec::with_capacity(out_len);
    unsafe {
        out.set_len(out_len);
        ffi::hydro_secretbox_encrypt(
            out.as_mut_ptr(),
            input.as_ptr() as *const _,
            input.len(),
            msg_id,
            context.0.as_ptr() as *const _,
            key.0.as_ptr(),
        );
    }
    out
}

pub fn decrypt(
    input: &[u8],
    msg_id: u64,
    context: &Context,
    key: &Key,
) -> Result<Vec<u8>, HydroError> {
    if input.len() < HEADERBYTES {
        return Err(HydroError::DecryptionError);
    }
    let out_len = input.len() - HEADERBYTES;
    let mut out: Vec<u8> = Vec::with_capacity(out_len);
    unsafe {
        out.set_len(out_len);
        if ffi::hydro_secretbox_decrypt(
            out.as_mut_ptr() as *mut _,
            input.as_ptr(),
            input.len(),
            msg_id,
            context.0.as_ptr() as *const _,
            key.0.as_ptr(),
        ) != 0
        {
            return Err(HydroError::DecryptionError);
        }
    }
    Ok(out)
}

impl Probe {
    pub fn create(input: &[u8], context: &Context, key: &Key) -> Probe {
        if input.len() < HEADERBYTES {
            panic!("A probe cannot be created for an impossible ciphertext")
        }
        unsafe {
            let mut probe: Probe = mem::uninitialized();
            ffi::hydro_secretbox_probe_create(
                probe.0.as_mut_ptr(),
                input.as_ptr(),
                input.len(),
                context.0.as_ptr() as *const _,
                key.0.as_ptr(),
            );
            probe
        }
    }

    pub fn verify(&self, input: &[u8], context: &Context, key: &Key) -> Result<(), HydroError> {
        if unsafe {
            ffi::hydro_secretbox_probe_verify(
                self.0.as_ptr(),
                input.as_ptr(),
                input.len(),
                context.0.as_ptr() as *const _,
                key.0.as_ptr(),
            )
        } != 0
        {
            return Err(HydroError::InvalidProbe);
        }
        Ok(())
    }
}

impl Drop for Key {
    fn drop(&mut self) {
        utils::memzero(self)
    }
}

impl From<[u8; KEYBYTES]> for Key {
    #[inline]
    fn from(key: [u8; KEYBYTES]) -> Key {
        Key(key)
    }
}

impl Into<[u8; KEYBYTES]> for Key {
    #[inline]
    fn into(self) -> [u8; KEYBYTES] {
        self.0
    }
}

impl AsRef<[u8]> for Key {
    fn as_ref(&self) -> &[u8] {
        &self.0 as &[u8]
    }
}

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool {
        utils::equal(self, other)
    }
}

impl Eq for Key {}

impl Key {
    pub fn gen() -> Key {
        ensure_initialized();
        unsafe {
            let mut key: Key = mem::uninitialized();
            ffi::hydro_kdf_keygen(key.0.as_mut_ptr());
            key
        }
    }
}

impl Drop for Probe {
    fn drop(&mut self) {
        utils::memzero(self)
    }
}

impl From<[u8; PROBEBYTES]> for Probe {
    #[inline]
    fn from(probe: [u8; PROBEBYTES]) -> Probe {
        Probe(probe)
    }
}

impl Into<[u8; PROBEBYTES]> for Probe {
    #[inline]
    fn into(self) -> [u8; PROBEBYTES] {
        self.0
    }
}

impl AsRef<[u8]> for Probe {
    fn as_ref(&self) -> &[u8] {
        &self.0 as &[u8]
    }
}

impl PartialEq for Probe {
    fn eq(&self, other: &Self) -> bool {
        utils::equal(self, other)
    }
}

impl Eq for Probe {}

impl From<&'static str> for Context {
    fn from(context_str: &'static str) -> Context {
        let context_str_u8 = context_str.as_bytes();
        let context_str_u8_len = context_str_u8.len();
        if context_str_u8_len > CONTEXTBYTES {
            panic!("Context too long");
        }
        let mut context = Context::default();
        context.0[..context_str_u8_len].copy_from_slice(context_str_u8);
        context
    }
}

impl From<[u8; CONTEXTBYTES]> for Context {
    #[inline]
    fn from(context: [u8; CONTEXTBYTES]) -> Context {
        Context(context)
    }
}

impl Into<[u8; CONTEXTBYTES]> for Context {
    #[inline]
    fn into(self) -> [u8; CONTEXTBYTES] {
        self.0
    }
}

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

    #[test]
    fn test_secretbox() {
        init().unwrap();

        let context = "tests".into();
        let key = secretbox::Key::gen();

        let ciphertext = secretbox::encrypt(b"test message", 1, &context, &key);
        let decrypted = secretbox::decrypt(&ciphertext, 1, &context, &key).unwrap();
        assert_eq!(decrypted, b"test message");

        let probe = secretbox::Probe::create(&ciphertext, &context, &key);
        probe.verify(&ciphertext, &context, &key).unwrap();

        let contextx: [u8; secretbox::CONTEXTBYTES] = context.into();
        let contexty: secretbox::Context = contextx.into();
        assert_eq!(context, contexty);
    }
}