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
use nettle_sys::{
    nettle_salsa20_128_set_key, nettle_salsa20_256_set_key,
    nettle_salsa20_set_nonce, nettle_salsa20r12_crypt, salsa20_ctx,
};
use std::cmp::min;
use std::mem::{MaybeUninit, transmute};

use crate::{Error, Result};

#[allow(non_camel_case_types)]
/// 128 bit variant of D.J. Bernstein's Salsa20/12 block cipher.
/// # Note
/// Salsa20/12 it a reduced round version of Salsa20.
pub struct Salsa20R12_128 {
    context: Box<salsa20_ctx>,
}

impl_zeroing_drop_for!(Salsa20R12_128);

impl Salsa20R12_128 {
    /// Salsa20/12 block size in bytes.
    pub const BLOCK_SIZE: usize = ::nettle_sys::SALSA20_BLOCK_SIZE as usize;

    /// Salsa20/12 key size in bytes.
    pub const KEY_SIZE: usize = ::nettle_sys::SALSA20_128_KEY_SIZE as usize;

    /// Salsa20/12 nonce size in bytes.
    pub const NONCE_SIZE: usize = ::nettle_sys::SALSA20_NONCE_SIZE as usize;

    /// Create a new instance with `key`.
    pub fn with_key_and_nonce(key: &[u8], nonce: &[u8]) -> Result<Self> {
        if key.len() != Salsa20R12_128::KEY_SIZE {
            return Err(Error::InvalidArgument { argument_name: "key" });
        }
        if nonce.len() != Salsa20R12_128::NONCE_SIZE {
            return Err(Error::InvalidArgument { argument_name: "nonce" });
        }

        let context = unsafe {
            let mut ctx = Box::new(MaybeUninit::uninit());
            nettle_salsa20_128_set_key(ctx.as_mut_ptr(), key.as_ptr());
            nettle_salsa20_set_nonce(ctx.as_mut_ptr(), nonce.as_ptr());
            transmute(ctx)
        };

        Ok(Salsa20R12_128 { context })
    }

    /// Encrypt/decrypt data from `src` to `dst`.
    pub fn crypt(&mut self, dst: &mut [u8], src: &[u8]) {
        unsafe {
            nettle_salsa20r12_crypt(
                self.context.as_mut() as *mut _,
                min(src.len(), dst.len()),
                dst.as_mut_ptr(),
                src.as_ptr(),
            )
        };
    }
}

#[allow(non_camel_case_types)]
/// 256 bit variant of D.J. Bernstein's Salsa20/12 block cipher.
/// # Note
/// Salsa20/12 it a reduced round version of Salsa20.
pub struct Salsa20R12_256 {
    context: Box<salsa20_ctx>,
}

impl_zeroing_drop_for!(Salsa20R12_256);

impl Salsa20R12_256 {
    /// Salsa20/12 block size in bytes.
    pub const BLOCK_SIZE: usize = ::nettle_sys::SALSA20_BLOCK_SIZE as usize;

    /// Salsa20/12 key size in bytes.
    pub const KEY_SIZE: usize = ::nettle_sys::SALSA20_256_KEY_SIZE as usize;

    /// Salsa20/12 nonce size in bytes.
    pub const NONCE_SIZE: usize = ::nettle_sys::SALSA20_NONCE_SIZE as usize;

    /// Create a new instance with `key`.
    pub fn with_key_and_nonce(key: &[u8], nonce: &[u8]) -> Result<Self> {
        if key.len() != Salsa20R12_256::KEY_SIZE {
            return Err(Error::InvalidArgument { argument_name: "key" });
        }
        if nonce.len() != Salsa20R12_256::NONCE_SIZE {
            return Err(Error::InvalidArgument { argument_name: "nonce" });
        }

        let context = unsafe {
            let mut ctx = Box::new(MaybeUninit::uninit());
            nettle_salsa20_256_set_key(ctx.as_mut_ptr(), key.as_ptr());
            nettle_salsa20_set_nonce(ctx.as_mut_ptr(), nonce.as_ptr());
            transmute(ctx)
        };

        Ok(Salsa20R12_256 { context })
    }

    /// Encrypt/decrypt data from `src` to `dst`.
    pub fn crypt(&mut self, dst: &mut [u8], src: &[u8]) {
        assert_eq!(dst.len(), src.len());
        unsafe {
            nettle_salsa20r12_crypt(
                self.context.as_mut() as *mut _,
                dst.len(),
                dst.as_mut_ptr(),
                src.as_ptr(),
            )
        };
    }
}

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

    #[test]
    fn salsa128_set_key_and_nonce() {
        let key = vec![0; 16];
        let nonce = vec![1; 8];

        let _ = Salsa20R12_128::with_key_and_nonce(&key, &nonce).unwrap();
    }

    #[test]
    fn salsa128_round_trip() {
        let key = vec![0; 16];
        let nonce = vec![1; 8];
        let input = vec![
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11,
            0x12, 0x13, 0x14, 0x15, 0x16,
        ];
        let mut cipher = vec![0; 16];
        let mut output = vec![0; 16];

        let mut enc = Salsa20R12_128::with_key_and_nonce(&key, &nonce).unwrap();
        let mut dec = Salsa20R12_128::with_key_and_nonce(&key, &nonce).unwrap();

        enc.crypt(&mut cipher, &input);
        dec.crypt(&mut output, &cipher);

        assert_eq!(output, input);
    }

    #[test]
    fn salsa256_set_key_and_nonce() {
        let key = vec![0; 32];
        let nonce = vec![1; 8];

        let _ = Salsa20R12_256::with_key_and_nonce(&key, &nonce).unwrap();
    }

    #[test]
    fn salsa256_round_trip() {
        let key = vec![0; 32];
        let nonce = vec![1; 8];
        let input = vec![
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11,
            0x12, 0x13, 0x14, 0x15, 0x16,
        ];
        let mut cipher = vec![0; 16];
        let mut output = vec![0; 16];

        let mut enc = Salsa20R12_256::with_key_and_nonce(&key, &nonce).unwrap();
        let mut dec = Salsa20R12_256::with_key_and_nonce(&key, &nonce).unwrap();

        enc.crypt(&mut cipher, &input);
        dec.crypt(&mut output, &cipher);

        assert_eq!(output, input);
    }
}