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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
mod tables;

use std::convert::TryInto;

type Key = [u8; 32];
type Subkey = u128;
type Subkeys = [Subkey; ROUNDS + 1];

const PHI: u32 = 0x9e37_79b9;
const ROUNDS: usize = 32;

fn apply_s(s_idx: usize, nibble: u8) -> u8 {
    tables::SBOX[s_idx % 8][nibble as usize]
}

fn apply_s_inv(s_idx: usize, nibble: u8) -> u8 {
    tables::SBOX_INV[s_idx % 8][nibble as usize]
}

fn apply_s_hat(s_idx: usize, source: u128) -> u128 {
    let mut res = 0u128;
    for i in 0..32 {
        let src_nibble = (source >> (i * 4)) as u8 & 0xf;
        let res_nibble = u128::from(apply_s(s_idx, src_nibble));
        res |= res_nibble << (i * 4);
    }
    res
}

fn apply_s_hat_inv(s_idx: usize, source: u128) -> u128 {
    let mut res = 0u128;
    for i in 0..32 {
        let src_nibble = (source >> (i * 4)) as u8 & 0xf;
        let res_nibble = u128::from(apply_s_inv(s_idx, src_nibble));
        res |= res_nibble << (i * 4);
    }
    res
}

fn apply_permutation(table: &tables::Permutation, input: u128) -> u128 {
    let mut output = 0u128;
    for (p, in_shift) in table.iter().enumerate() {
        let bit = (input >> in_shift) & 1;
        output |= bit << p;
    }
    output
}

fn apply_xor_table(table: &tables::XorTable, input: u128) -> u128 {
    let mut output = 0u128;
    for (i, indices) in table.iter().enumerate() {
        let mut bit = 0u8;
        for bit_idx in *indices {
            bit ^= (input >> bit_idx) as u8 & 1;
        }
        output |= u128::from(bit) << i;
    }
    output
}

pub struct Serpent {
    subkeys: Subkeys,
}

impl Serpent {
    pub fn with_binary_key(key: &[u8]) -> Option<Serpent> {
        let expanded_key = expand_key(key, key.len() * 8)?;
        Some(Serpent {
            subkeys: derive_subkeys(expanded_key),
        })
    }

    pub fn with_text_key(key: &str) -> Option<Serpent> {
        let binary_key = parse_text_key(key)?;
        Serpent::with_binary_key(&binary_key)
    }

    pub fn encrypt_block(&self, block: u128) -> u128 {
        let mut b_hat = apply_permutation(&tables::IP, block);
        for i in 0..ROUNDS {
            b_hat = do_round(i, b_hat, &self.subkeys);
        }
        apply_permutation(&tables::FP, b_hat)
    }

    pub fn decrypt_block(&self, block: u128) -> u128 {
        let mut b_hat = apply_permutation(&tables::IP, block);
        for i in (0..ROUNDS).rev() {
            b_hat = do_round_inv(i, b_hat, &self.subkeys);
        }
        apply_permutation(&tables::FP, b_hat)
    }
}

fn do_round(i: usize, b_hat_i: u128, k_hat: &Subkeys) -> u128 {
    let xored = b_hat_i ^ k_hat[i];
    let s_hat_i = apply_s_hat(i, xored);
    if i <= ROUNDS - 2 {
        apply_xor_table(&tables::LT, s_hat_i)
    } else {
        s_hat_i ^ k_hat[ROUNDS]
    }
}

fn do_round_inv(i: usize, b_hat_i_plus_1: u128, k_hat: &Subkeys) -> u128 {
    let s_hat_i = if i <= ROUNDS - 2 {
        apply_xor_table(&tables::LT_INV, b_hat_i_plus_1)
    } else {
        b_hat_i_plus_1 ^ k_hat[ROUNDS]
    };
    let xored = apply_s_hat_inv(i, s_hat_i);
    xored ^ k_hat[i]
}

fn parse_text_key(key: &str) -> Option<Vec<u8>> {
    if !key.is_ascii() {
        return None;
    }
    let bytes = key.as_bytes();
    if bytes.iter().any(|b| !b.is_ascii_hexdigit()) {
        return None;
    }
    let len = bytes.len();
    let len_bits = len * 4;
    if len_bits > 256 {
        return None;
    }
    let mut key = bytes
        .iter()
        .rev()
        .enumerate()
        .fold([0u8; 32], |mut k, (place, digit)| {
            let nibble = match digit {
                b'0'..=b'9' => digit - b'0',
                b'a'..=b'f' => digit - b'a' + 10,
                b'A'..=b'F' => digit - b'A' + 10,
                _ => unreachable!(),
            } as u8;
            let offset = (place & 1) * 4;
            k[place / 2] |= nibble << offset;
            k
        });

    if len_bits < 256 {
        let offset = (len & 1) * 4;
        key[len / 2] |= 1 << offset;
    }
    Some(key[..].into())
}

fn expand_key(source: &[u8], len_bits: usize) -> Option<Key> {
    let source_bits = source.len() * 8;

    // Bail out if the key material is too long or if the stated bit length
    // mismatches the byte length.
    if source_bits > 256 || len_bits > 256 || source_bits < len_bits {
        return None;
    }

    let mut key = [0u8; 32];
    key[..source.len()].copy_from_slice(&source);
    if len_bits < 256 {
        let byte_index = len_bits / 8;
        let bit_index = len_bits % 8;
        key[byte_index] |= 1 << bit_index;
    }

    Some(key)
}

fn gather_nibble(words: &[u32; 4], bit_idx: usize) -> u8 {
    let mut output = 0u8;
    for (i, word) in words.iter().enumerate() {
        let bit = ((word >> bit_idx) & 1) as u8;
        output |= bit << i;
    }
    output
}

fn scatter_nibble(nibble: u8, words: &mut [u32; 4], out_bit_idx: usize) {
    assert_eq!(words.len(), 4);
    for (i, word) in words.iter_mut().enumerate() {
        let bit = u32::from((nibble >> i) & 1);
        *word |= bit << out_bit_idx;
    }
}

fn derive_subkeys(key: Key) -> [Subkey; ROUNDS + 1] {
    use byteorder::{ByteOrder, LE};
    let mut w = [0u32; 140];
    LE::read_u32_into(&key, &mut w[..8]);

    for i in 0..132 {
        let slot = i + 8;
        w[slot] = (w[slot - 8] ^ w[slot - 5] ^ w[slot - 3] ^ w[slot - 1] ^ PHI ^ i as u32)
            .rotate_left(11);
    }

    let w = &w[8..];
    let mut k = [0u32; 132];
    for i in 0..=ROUNDS {
        let s_idx = (ROUNDS + 3 - i) % ROUNDS;
        for j in 0..32 {
            let src = (&w[4 * i..4 * i + 4]).try_into().unwrap();
            let input = gather_nibble(src, j);
            let output = apply_s(s_idx, input);

            let dst = (&mut k[4 * i..4 * i + 4]).try_into().unwrap();
            scatter_nibble(output, dst, j);
        }
    }
    // distribute 32-bit values k[] into 128-bit subkeys
    let mut subkeys = [0u128; ROUNDS + 1];
    for i in 0..33 {
        subkeys[i] = u128::from(k[4 * i])
            | u128::from(k[4 * i + 1]) << 32
            | u128::from(k[4 * i + 2]) << 64
            | u128::from(k[4 * i + 3]) << 96;
    }

    // apply IP to the key
    for subkey in &mut subkeys[..] {
        *subkey = apply_permutation(&tables::IP, *subkey);
    }

    subkeys
}

pub use block_cipher_trait;
pub use block_cipher_trait::generic_array;
pub use generic_array::typenum;

use block_cipher_trait::BlockCipher;
use generic_array::GenericArray;
use typenum::{U1, U16, U32};

impl BlockCipher for Serpent {
    type KeySize = U32;
    type BlockSize = U16;
    type ParBlocks = U1;

    fn new(key: &GenericArray<u8, U32>) -> Self {
        Serpent::with_binary_key(&key).unwrap()
    }

    fn encrypt_block(&self, block: &mut GenericArray<u8, Self::BlockSize>) {
        let input = u128::from_le_bytes(block.as_slice().try_into().unwrap());
        let output = self.encrypt_block(input);
        block.copy_from_slice(&u128::to_le_bytes(output));
    }

    fn decrypt_block(&self, block: &mut GenericArray<u8, Self::BlockSize>) {
        let input = u128::from_le_bytes(block.as_slice().try_into().unwrap());
        let output = self.decrypt_block(input);
        block.copy_from_slice(&u128::to_le_bytes(output));
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn parse_keys() {
        // 128 bits, observe 0b0001 nibble halfway through output and rest 0b0000
        let binary_key = super::parse_text_key("0123456789abcdef0123456789abcdef").unwrap();
        assert_eq!(
            binary_key,
            [
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
            ]
        );

        // 252 bits, observe 0b0001 nibble in most significant nibble
        let binary_key = super::parse_text_key(
            "123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
        )
        .unwrap();
        assert_eq!(
            binary_key,
            [
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x11, //
            ]
        );

        // 256 bits, observe full key represented
        let binary_key = super::parse_text_key(
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
        )
        .unwrap();
        assert_eq!(
            binary_key,
            [
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
                0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, //
            ]
        );
    }
}