8
8
import std.crypto.cipher (Cipher)
9
9
import std.crypto.math (rotate_left_u32, to_u32)
10
10
import std.endian.little
11
+ import std.int (MAX as INT_MAX)
11
12
12
13
# The ChaCha key size in bytes.
13
14
let KEY_SIZE = 256 / 8
@@ -24,9 +25,6 @@ let XCHACHA_NONCE_SIZE = 192 / 8
24
25
# The size in bytes of a ChaCha block.
25
26
let BLOCK_SIZE = 64
26
27
27
- # The maximum value of the block counter.
28
- let MAX_COUNTER = 2 ** 32 - 1
29
-
30
28
# The number of values in a matrix.
31
29
let MATRIX_SIZE = 16
32
30
@@ -45,11 +43,7 @@ fn nonce_size_error(expected: Int, size: Int) -> Never {
45
43
}
46
44
47
45
fn counter_size_error(value: Int) -> Never {
48
- panic('the block counter (${value}) must be between 0 and ${MAX_COUNTER}')
49
- }
50
-
51
- fn counter_overflow_error(value: Int) -> Never {
52
- panic('the block counter (${value}) overflowed after ${MAX_COUNTER} blocks')
46
+ panic('the block counter (${value}) must be between 0 and ${INT_MAX}')
53
47
}
54
48
55
49
# Derives a sub-key from a secret key and nonce, using the HChaCha20 algorithm.
@@ -334,11 +328,7 @@ type pub inline ChaCha {
334
328
# This method panics if the value doesn't fit in the range valid for an
335
329
# unsigned 32-bits integer.
336
330
fn pub mut counter=(value: Int) {
337
- if value < 0 or value > MAX_COUNTER {
338
- counter_size_error(value)
339
- } else {
340
- @matrix.set(12, value)
341
- }
331
+ if value < 0 { counter_size_error(value) } else { @matrix.set(12, value) }
342
332
}
343
333
344
334
fn mut apply(bytes: mut ByteArray) {
@@ -362,15 +352,6 @@ type pub inline ChaCha {
362
352
# unsigned integer.
363
353
let new_size = @matrix.get(12) + 1
364
354
365
- # The original implementation makes no attempt at protecting the user from
366
- # overflowing the counter, as it's unlikely to happen in the first place.
367
- # Since we use a 32-bits counter it's still highly unlikely, but more
368
- # likely compared to using a 64-bits counter. Because it's so unlikely for
369
- # this to happen in practise we simply panic, instead of complicating the
370
- # API by forcing the user to handle errors that won't occur in 99.99999%
371
- # of all use cases.
372
- if new_size > MAX_COUNTER { counter_overflow_error(new_size) }
373
-
374
355
@matrix.set(12, new_size)
375
356
376
357
if len <= BLOCK_SIZE {
0 commit comments