Diff
Not logged in

Differences From Artifact [111ef93e4f]:

To Artifact [a3fd22b031]:


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
20
21
22
23
24
25
26







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
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
..
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
//! combination of Salsa20 and Poly1305 specified in
//! [Cryptography in `NaCl`](http://nacl.cr.yp.to/valid.html).
//!
//! This function is conjectured to meet the standard notions of privacy and
//! authenticity.

use ffi;
use marshal::marshal;
use randombytes::randombytes_into;
#[cfg(feature = "rustc-serialize")]
use rustc_serialize;

/// Number of bytes in `Key`.
pub const KEYBYTES: usize = ffi::crypto_secretbox_xsalsa20poly1305_KEYBYTES;

................................................................................
new_type! {
    /// `Key` for symmetric authenticated encryption
    ///
    /// When a `Key` goes out of scope its contents
    /// will be zeroed out
    secret Key(KEYBYTES);
}








new_type! {
    /// `Nonce` for symmetric authenticated encryption
    nonce Nonce(NONCEBYTES);
}

const ZEROBYTES: usize = 32;
const BOXZEROBYTES: usize = 16;

/// Number of bytes in the authenticator tag of an encrypted message
/// i.e. the number of bytes by which the ciphertext is larger than the
/// plaintext.
pub const MACBYTES: usize = ffi::crypto_secretbox_xsalsa20poly1305_MACBYTES;

/// `gen_key()` randomly generates a secret key
///
................................................................................
    randombytes_into(&mut nonce);
    Nonce(nonce)
}

/// `seal()` encrypts and authenticates a message `m` using a secret key `k` and a
/// nonce `n`.  It returns a ciphertext `c`.
pub fn seal(m: &[u8], &Nonce(ref n): &Nonce, &Key(ref k): &Key) -> Vec<u8> {
    let (c, _) = marshal(m, ZEROBYTES, BOXZEROBYTES, |dst, src, len| unsafe {
        ffi::crypto_secretbox_xsalsa20poly1305(dst, src, len, n.as_ptr(), k.as_ptr())
    });








    c
}

















/// `open()` verifies and decrypts a ciphertext `c` using a secret key `k` and a nonce `n`.
/// It returns a plaintext `Ok(m)`.
/// If the ciphertext fails verification, `open()` returns `Err(())`.
pub fn open(c: &[u8], &Nonce(ref n): &Nonce, &Key(ref k): &Key) -> Result<Vec<u8>, ()> {
    if c.len() < BOXZEROBYTES {
        return Err(());
    }
    let (m, ret) =
        marshal(c, BOXZEROBYTES, ZEROBYTES, |dst, src, len| unsafe {
            ffi::crypto_secretbox_xsalsa20poly1305_open(dst, src, len, n.as_ptr(), k.as_ptr())






        });
    if ret == 0 { Ok(m) } else { Err(()) }
}





















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

    #[test]
    fn test_seal_open() {
................................................................................
        assert!(::init());
        for i in 0..256usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let c = seal(&m, &n, &k);
            let opened = open(&c, &n, &k);
            assert!(Ok(m) == opened);
        }
    }

    #[test]
    #[cfg_attr(feature="cargo-clippy", allow(needless_range_loop))]
    fn test_seal_open_tamper() {
        use randombytes::randombytes;
        assert!(::init());
        for i in 0..32usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let mut c = seal(&m, &n, &k);
            for i in 0..c.len() {
                c[i] ^= 0x20;

                assert!(Err(()) == open(&c, &n, &k));



                c[i] ^= 0x20;
            }
        }
    }

























































































    #[test]
    fn test_vector_1() {
        assert!(::init());
        let firstkey = Key([0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85, 0xd4, 0x62, 0xcd, 0x51,
                            0x19, 0x7a, 0x9a, 0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac, 0x64,
                            0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08, 0x44, 0xf6, 0x83, 0x89]);







<







 







>
>
>
>
>
>
>






<
<
<







 







|
|
<
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|


|
|
|
>
>
>
>
>
>
|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







<







>
|
>
>
>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2
3
4
5
6
7
8

9
10
11
12
13
14
15
..
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
..
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
...
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
265
266
267
268
269
270
//! combination of Salsa20 and Poly1305 specified in
//! [Cryptography in `NaCl`](http://nacl.cr.yp.to/valid.html).
//!
//! This function is conjectured to meet the standard notions of privacy and
//! authenticity.

use ffi;

use randombytes::randombytes_into;
#[cfg(feature = "rustc-serialize")]
use rustc_serialize;

/// Number of bytes in `Key`.
pub const KEYBYTES: usize = ffi::crypto_secretbox_xsalsa20poly1305_KEYBYTES;

................................................................................
new_type! {
    /// `Key` for symmetric authenticated encryption
    ///
    /// When a `Key` goes out of scope its contents
    /// will be zeroed out
    secret Key(KEYBYTES);
}

new_type! {
    /// Authentication `Tag` for the detached encryption mode
    ///
    /// In the combined mode, the tag occupies the first MACBYTES bytes of the ciphertext.
    public Tag(MACBYTES);
}

new_type! {
    /// `Nonce` for symmetric authenticated encryption
    nonce Nonce(NONCEBYTES);
}




/// Number of bytes in the authenticator tag of an encrypted message
/// i.e. the number of bytes by which the ciphertext is larger than the
/// plaintext.
pub const MACBYTES: usize = ffi::crypto_secretbox_xsalsa20poly1305_MACBYTES;

/// `gen_key()` randomly generates a secret key
///
................................................................................
    randombytes_into(&mut nonce);
    Nonce(nonce)
}

/// `seal()` encrypts and authenticates a message `m` using a secret key `k` and a
/// nonce `n`.  It returns a ciphertext `c`.
pub fn seal(m: &[u8], &Nonce(ref n): &Nonce, &Key(ref k): &Key) -> Vec<u8> {
    let clen = m.len() + MACBYTES;
    let mut c = Vec::with_capacity(clen);

    unsafe {
        c.set_len(clen);
        let _ = ffi::crypto_secretbox_easy(c.as_mut_ptr(),
                                           m.as_ptr(),
                                           m.len() as u64,
                                           n.as_ptr(),
                                           k.as_ptr());
    }
    c
}

/// `seal_detached()` encrypts and authenticates a message `m` using a secret key `k` and a nonce
/// `n`.  `m` is encrypted in place, so after this function returns it will contain the ciphertext.
/// The detached authentication tag is returned by value.
pub fn seal_detached(m: &mut [u8], &Nonce(ref n): &Nonce, &Key(ref k): &Key) -> Tag {
    let mut tag = [0; MACBYTES];
    unsafe {
        let _ = ffi::crypto_secretbox_detached(m.as_mut_ptr(),
                                               tag.as_mut_ptr(),
                                               m.as_ptr(),
                                               m.len() as u64,
                                               n.as_ptr(),
                                               k.as_ptr());
    };
    Tag(tag)
}

/// `open()` verifies and decrypts a ciphertext `c` using a secret key `k` and a nonce `n`.
/// It returns a plaintext `Ok(m)`.
/// If the ciphertext fails verification, `open()` returns `Err(())`.
pub fn open(c: &[u8], &Nonce(ref n): &Nonce, &Key(ref k): &Key) -> Result<Vec<u8>, ()> {
    if c.len() < MACBYTES {
        return Err(());
    }
    let mlen = c.len() - MACBYTES;
    let mut m = Vec::with_capacity(mlen);
    let ret = unsafe {
        m.set_len(mlen);
        ffi::crypto_secretbox_open_easy(m.as_mut_ptr(),
                                        c.as_ptr(),
                                        c.len() as u64,
                                        n.as_ptr(),
                                        k.as_ptr())
    };
    if ret == 0 { Ok(m) } else { Err(()) }
}

/// `open_detached()` verifies and decrypts a ciphertext `c` and and authentication tag `tag`,
/// using a secret key `k` and a nonce `n`. `c` is decrypted in place, so if this function is
/// successful it will contain the plaintext. If the ciphertext fails verification,
/// `open_detached()` returns `Err(())`, and the ciphertext is not modified.
pub fn open_detached(c: &mut [u8],
                     tag: &Tag,
                     &Nonce(ref n): &Nonce,
                     &Key(ref k): &Key)
                     -> Result<(), ()> {
    let ret = unsafe {
        ffi::crypto_secretbox_open_detached(c.as_mut_ptr(),
                                            c.as_ptr(),
                                            tag.0.as_ptr(),
                                            c.len() as u64,
                                            n.as_ptr(),
                                            k.as_ptr())
    };
    if ret == 0 { Ok(()) } else { Err(()) }
}

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

    #[test]
    fn test_seal_open() {
................................................................................
        assert!(::init());
        for i in 0..256usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let c = seal(&m, &n, &k);
            let opened = open(&c, &n, &k);
            assert_eq!(Ok(m), opened);
        }
    }

    #[test]
    #[cfg_attr(feature="cargo-clippy", allow(needless_range_loop))]
    fn test_seal_open_tamper() {
        use randombytes::randombytes;

        for i in 0..32usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let mut c = seal(&m, &n, &k);
            for i in 0..c.len() {
                c[i] ^= 0x20;
                // Test the combined mode.
                assert_eq!(Err(()), open(&c, &n, &k));
                // Test the detached mode.
                let tag = Tag::from_slice(&c[..MACBYTES]).unwrap();
                assert_eq!(Err(()), open_detached(&mut c[MACBYTES..], &tag, &n, &k));
                c[i] ^= 0x20;
            }
        }
    }

    #[test]
    fn test_seal_open_detached() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let mut buf = m.clone();
            let tag = seal_detached(&mut buf, &n, &k);
            open_detached(&mut buf, &tag, &n, &k).unwrap();
            assert_eq!(m, buf);
        }
    }

    #[test]
    fn test_seal_combined_then_open_detached() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let mut c = seal(&m, &n, &k);
            let tag = Tag::from_slice(&c[..MACBYTES]).unwrap();
            let buf = &mut c[MACBYTES..];
            open_detached(buf, &tag, &n, &k).unwrap();
            assert_eq!(buf, &*m);
        }
    }

    #[test]
    fn test_seal_detached_then_open_combined() {
        use randombytes::randombytes;
        for i in 0..256usize {
            let k = gen_key();
            let m = randombytes(i);
            let n = gen_nonce();
            let mut buf = vec![0; MACBYTES];
            buf.extend_from_slice(&m);
            let tag = seal_detached(&mut buf[MACBYTES..], &n, &k);
            buf[..MACBYTES].copy_from_slice(&tag.0[..]);
            let opened = open(&buf, &n, &k);
            assert_eq!(Ok(m), opened);
        }
    }


    #[test]
    #[cfg_attr(feature="cargo-clippy", allow(needless_range_loop))]
    fn test_seal_open_detached_tamper() {
        use randombytes::randombytes;
        assert!(::init());
        for i in 0..32usize {
            let k = gen_key();
            let mut m = randombytes(i);
            let n = gen_nonce();
            let mut tag = seal_detached(&mut m, &n, &k);
            for j in 0..m.len() {
                m[j] ^= 0x20;
                assert_eq!(Err(()), open_detached(&mut m, &tag, &n, &k));
                m[j] ^= 0x20;
            }
            for j in 0..tag.0.len() {
                tag.0[j] ^= 0x20;
                assert_eq!(Err(()), open_detached(&mut m, &tag, &n, &k));
                tag.0[j] ^= 0x20;
            }
        }
    }

    #[test]
    fn test_open_detached_failure_does_not_modify() {
        let mut buf = b"hello world".to_vec();
        let k = gen_key();
        let n = gen_nonce();
        let tag = seal_detached(&mut buf, &n, &k);
        // Flip the last bit in the ciphertext, to break authentication.
        *buf.last_mut().unwrap() ^= 1;
        // Make a copy that we can compare against after the failure below.
        let copy = buf.clone();
        // Now try to open the message. This will fail.
        let failure = open_detached(&mut buf, &tag, &n, &k);
        assert!(failure.is_err());
        // Make sure the input hasn't been touched.
        assert_eq!(buf,
                   copy,
                   "input should not be modified if authentication fails");
    }

    #[test]
    fn test_vector_1() {
        assert!(::init());
        let firstkey = Key([0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85, 0xd4, 0x62, 0xcd, 0x51,
                            0x19, 0x7a, 0x9a, 0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac, 0x64,
                            0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08, 0x44, 0xf6, 0x83, 0x89]);