dcrypt-algorithms 4.0.0

Cryptographic primitives for the dcrypt library
Documentation
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Counter (CTR) mode with proper error propagation and secure memory handling
//!
//! Counter mode turns a block cipher into a stream cipher by encrypting
//! successive values of a counter and XORing the result with the plaintext.
//!
//! This implementation follows NIST SP 800-38A recommendations for CTR mode,
//! using a flexible nonce-counter format with secure memory handling.

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use dcrypt_internal::zeroing::{
    boxed_bytes_zeroed, Zeroize, ZeroizeOnDrop, Zeroizing, ZeroizingBytes,
};

use super::super::BlockCipher;
use crate::error::{validate, Result};
use crate::types::nonce::AesCtrCompatible;
use crate::types::Nonce;

// Import security types for memory safety
use dcrypt_common::security::barrier;

/// Counter position within the counter block
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CounterPosition {
    /// Counter is placed at the beginning of the block (bytes 0 to counter_size-1)
    /// This is common in some implementations, especially with 8-byte counters
    Prefix,

    /// Counter is placed at the end of the block (last counter_size bytes)
    /// This is the most common arrangement for AES-CTR
    Postfix,

    /// Counter is placed at a specific offset within the block
    /// Allows for custom layouts
    Custom(usize),
}

/// Counter mode implementation with secure memory handling
#[derive(Clone)]
pub struct Ctr<B: BlockCipher + Zeroize> {
    cipher: B,
    counter_block: ZeroizingBytes,
    counter_position: usize,
    counter_size: usize,
    keystream: ZeroizingBytes,
    keystream_pos: usize,
}

impl<B: BlockCipher + Zeroize> Zeroize for Ctr<B> {
    fn zeroize(&mut self) {
        self.cipher.zeroize();
        self.counter_block.zeroize();
        self.counter_position.zeroize();
        self.counter_size.zeroize();
        self.keystream.zeroize();
        self.keystream_pos.zeroize();
    }
}

impl<B: BlockCipher + Zeroize> Drop for Ctr<B> {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl<B: BlockCipher + Zeroize> ZeroizeOnDrop for Ctr<B> {}

impl<B: BlockCipher + Zeroize> Ctr<B> {
    /// Creates a new CTR mode instance with the default configuration
    ///
    /// * `cipher` - The block cipher to use
    /// * `nonce` - The nonce (must be compatible with CTR mode)
    ///
    /// This creates a standard CTR mode with the counter in the last 4 bytes
    /// and the nonce filling the beginning of the counter block.
    pub fn new<const N: usize>(cipher: B, nonce: &Nonce<N>) -> Result<Self>
    where
        Nonce<N>: AesCtrCompatible,
    {
        // Standard CTR mode with 4-byte counter at the end
        Self::with_counter_params(cipher, nonce, CounterPosition::Postfix, 4)
    }

    /// Creates a new CTR mode instance with custom counter parameters
    ///
    /// * `cipher` - The block cipher to use
    /// * `nonce` - The nonce (must be compatible with CTR mode)
    /// * `counter_pos` - Position of the counter within the counter block
    /// * `counter_size` - Size of the counter in bytes (1-8)
    ///
    /// This allows for flexible counter block layouts to match different standards
    /// and implementations.
    pub fn with_counter_params<const N: usize>(
        cipher: B,
        nonce: &Nonce<N>,
        counter_pos: CounterPosition,
        counter_size: usize,
    ) -> Result<Self>
    where
        Nonce<N>: AesCtrCompatible,
    {
        let block_size = B::block_size();

        // Validate counter size (1-8 bytes for u64 counter)
        validate::parameter(
            counter_size > 0 && counter_size <= 8,
            "counter_size",
            "Counter size must be between 1 and 8 bytes",
        )?;

        // Determine the counter position
        let position = match counter_pos {
            CounterPosition::Prefix => 0,
            CounterPosition::Postfix => block_size - counter_size,
            CounterPosition::Custom(offset) => {
                validate::parameter(
                    offset + counter_size <= block_size,
                    "counter_position",
                    "Counter with specified size doesn't fit at offset in block",
                )?;
                offset
            }
        };

        // Create and initialize the counter block with Zeroizing
        let mut counter_block = Zeroizing::new(boxed_bytes_zeroed(block_size));

        // Handle nonce according to its size
        let max_nonce_size = block_size - counter_size;

        // If nonce is too large, truncate it
        let effective_nonce = if N > max_nonce_size {
            &nonce.as_ref()[0..max_nonce_size]
        } else {
            nonce.as_ref()
        };

        // Fill in the nonce
        if position == 0 {
            // Counter is at the beginning, place nonce after it
            counter_block[counter_size..counter_size + effective_nonce.len()]
                .copy_from_slice(effective_nonce);
        } else {
            // Counter is elsewhere, place nonce at the beginning by default
            counter_block[0..effective_nonce.len()].copy_from_slice(effective_nonce);
        }

        Ok(Self {
            cipher,
            counter_block,
            counter_position: position,
            counter_size,
            keystream: Zeroizing::new(boxed_bytes_zeroed(0)),
            keystream_pos: 0,
        })
    }

    /// Generate keystream for CTR mode with secure memory handling
    fn generate_keystream(&mut self) -> Result<()> {
        let block_size = B::block_size();

        // Create a new zeroizing keystream buffer
        self.keystream = Zeroizing::new(boxed_bytes_zeroed(block_size));

        // Use memory barrier to prevent optimization
        barrier::compiler_fence_seq_cst();

        // Copy current counter block to keystream
        self.keystream.copy_from_slice(&self.counter_block);

        // Encrypt the counter value
        self.cipher.encrypt_block(&mut self.keystream)?;

        // Increment the counter based on its size
        self.increment_counter();

        self.keystream_pos = 0;

        // Use memory barrier after operation
        barrier::compiler_fence_seq_cst();

        Ok(())
    }

    /// Increment the counter in the counter block
    fn increment_counter(&mut self) {
        match self.counter_size {
            8 => {
                let mut counter = [0u8; 8];
                counter.copy_from_slice(
                    &self.counter_block[self.counter_position..self.counter_position + 8],
                );
                let value = u64::from_be_bytes(counter);
                counter.copy_from_slice(&value.wrapping_add(1).to_be_bytes());
                self.counter_block[self.counter_position..self.counter_position + 8]
                    .copy_from_slice(&counter);

                // Zeroize the temporary counter array
                counter.zeroize();
            }
            4 => {
                let mut counter = [0u8; 4];
                counter.copy_from_slice(
                    &self.counter_block[self.counter_position..self.counter_position + 4],
                );
                let value = u32::from_be_bytes(counter);
                counter.copy_from_slice(&value.wrapping_add(1).to_be_bytes());
                self.counter_block[self.counter_position..self.counter_position + 4]
                    .copy_from_slice(&counter);

                // Zeroize the temporary counter array
                counter.zeroize();
            }
            // For other counter sizes, we'll read/write the appropriate number of bytes
            size => {
                let mut value: u64 = 0;

                // Read counter value (big-endian)
                for i in 0..size {
                    value = (value << 8) | (self.counter_block[self.counter_position + i] as u64);
                }

                // Increment counter
                value = value.wrapping_add(1);

                // Write counter value back (big-endian)
                for i in 0..size {
                    self.counter_block[self.counter_position + size - 1 - i] = (value & 0xff) as u8;
                    value >>= 8;
                }
            }
        }
    }

    /// Encrypts a message using CTR mode
    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
        let mut ciphertext = Zeroizing::new(boxed_bytes_zeroed(plaintext.len()));

        // Use memory barrier before sensitive operations
        barrier::compiler_fence_seq_cst();

        for (output, &byte) in ciphertext.iter_mut().zip(plaintext) {
            if self.keystream_pos >= self.keystream.len() {
                self.generate_keystream()?;
            }

            *output = byte ^ self.keystream[self.keystream_pos];
            self.keystream_pos += 1;
        }

        // Use memory barrier after sensitive operations
        barrier::compiler_fence_seq_cst();

        Ok(ciphertext.into_inner().into_vec())
    }

    /// Decrypts a message using CTR mode
    /// In CTR mode, encryption and decryption are the same operation
    pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
        self.encrypt(ciphertext)
    }

    /// Process data in place (encrypt or decrypt)
    pub fn process(&mut self, data: &mut [u8]) -> Result<()> {
        // Use memory barrier before sensitive operations
        barrier::compiler_fence_seq_cst();

        for byte in data.iter_mut() {
            // Generate new keystream block if needed
            if self.keystream_pos >= self.keystream.len() {
                self.generate_keystream()?;
            }

            // XOR data with keystream
            *byte ^= self.keystream[self.keystream_pos];
            self.keystream_pos += 1;
        }

        // Use memory barrier after sensitive operations
        barrier::compiler_fence_seq_cst();

        Ok(())
    }

    /// Generate keystream directly into an output buffer
    pub fn keystream(&mut self, output: &mut [u8]) -> Result<()> {
        // Zero the output buffer
        for byte in output.iter_mut() {
            *byte = 0;
        }

        // Force generation from a block boundary (ignore any leftover position)
        self.keystream_pos = self.keystream.len();

        // Then run the encryption pass to copy the keystream
        self.process(output)
    }

    /// Seek to a specific block position
    ///
    /// `block_offset` is the number of full blocks that have been consumed;
    /// after seeking, the next generated block will be at `block_offset + 1`.
    pub fn seek(&mut self, block_offset: u32) {
        // Calculate the counter value based on the offset
        let mut counter_value = [0u8; 8];
        counter_value[4..].copy_from_slice(&block_offset.wrapping_add(1).to_be_bytes());

        // Update counter in the counter block
        for i in 0..self.counter_size {
            let idx = self.counter_position + self.counter_size - 1 - i;
            self.counter_block[idx] = counter_value[7 - i];
        }

        // Force regeneration on next use
        self.keystream_pos = self.keystream.len();

        // Clear any old keystream with Zeroizing
        self.keystream = Zeroizing::new(boxed_bytes_zeroed(0));

        // Zeroize the temporary counter value
        counter_value.zeroize();
    }

    /// Set the counter value directly
    ///
    /// This allows for manual control of the counter, which can be useful for
    /// seeking to specific positions in the stream.
    ///
    /// # Arguments
    /// * `counter` - The new counter value
    pub fn set_counter(&mut self, counter: u32) {
        // Update counter in the counter block
        let counter_pos = self.counter_position;

        // Write the counter value in big-endian format
        // This handles various counter sizes (1-8 bytes)
        let counter_bytes = counter.to_be_bytes();
        let start_idx = 4 - self.counter_size;

        for i in 0..self.counter_size {
            if start_idx + i < 4 {
                // Only copy if within counter_bytes bounds
                self.counter_block[counter_pos + i] = counter_bytes[start_idx + i];
            }
        }

        // Force regeneration of keystream on next use
        self.keystream_pos = self.keystream.len();
    }

    /// Reset to initial state with the same key and nonce
    ///
    /// This resets the counter to 0 and clears any buffered keystream.
    ///
    /// # Arguments
    /// * `nonce` - Optional new nonce to use (if not provided, keeps the current nonce)
    /// * `counter` - Optional initial counter value (defaults to 0)
    pub fn reset<const N: usize>(&mut self, nonce: Option<&Nonce<N>>, counter: u32) -> Result<()>
    where
        Nonce<N>: AesCtrCompatible,
    {
        // Use memory barrier before sensitive operations
        barrier::compiler_fence_seq_cst();

        // Update nonce if provided
        if let Some(new_nonce) = nonce {
            let block_size = B::block_size();
            let max_nonce_size = block_size - self.counter_size;

            // If nonce is too large, truncate it
            let effective_nonce = if N > max_nonce_size {
                &new_nonce.as_ref()[0..max_nonce_size]
            } else {
                new_nonce.as_ref()
            };

            // Clear the counter block
            for b in &mut *self.counter_block {
                *b = 0;
            }

            // Fill in the nonce
            let counter_pos = match self.counter_position {
                0 => self.counter_size, // Counter is at beginning, nonce follows
                _ => 0,                 // Otherwise nonce is at beginning
            };

            // Copy the new nonce
            self.counter_block[counter_pos..counter_pos + effective_nonce.len()]
                .copy_from_slice(effective_nonce);
        }

        // Set the counter value
        self.set_counter(counter);

        // Clear keystream
        self.keystream = Zeroizing::new(boxed_bytes_zeroed(0));
        self.keystream_pos = 0;

        // Use memory barrier after sensitive operations
        barrier::compiler_fence_seq_cst();

        Ok(())
    }
}

#[cfg(test)]
mod tests;