Skip to content

Commit 48734d3

Browse files
committed
Restore panic upon ChaCha counter overflow
This was turned into a wrapping operation by accident.
1 parent 039c2a8 commit 48734d3

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

std/src/std/crypto/chacha.inko

+6-8
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,7 @@ type pub inline ChaCha {
357357
#
358358
# # Panics
359359
#
360-
# This method panics if the value doesn't fit in the range valid for an
361-
# unsigned 32-bits integer.
360+
# This method panics if `value` is less than zero.
362361
fn pub mut counter=(value: Int) {
363362
if value < 0 { counter_size_error(value) } else { @matrix.set(12, value) }
364363
}
@@ -385,10 +384,10 @@ type pub inline ChaCha {
385384
i += 1
386385
}
387386

388-
# This in itself can't overflow, as the Int type is a 64-bits signed
389-
# integer, and below we limit it to the range that fits in a 32-bits
390-
# unsigned integer.
391-
let new_size = @matrix.get(12).wrapping_add(1)
387+
# The chance of this overflowing is practically zero, but we use checked
388+
# arithmetic just in case so the counter doesn't silently overflow and
389+
# potentially mess things up.
390+
let new_size = @matrix.get(12) + 1
392391

393392
@matrix.set(12, new_size)
394393

@@ -512,8 +511,7 @@ type pub inline XChaCha {
512511
#
513512
# # Panics
514513
#
515-
# This method panics if the value doesn't fit in the range valid for an
516-
# unsigned 32-bits integer.
514+
# This method panics if `value` is less than zero.
517515
fn pub mut counter=(value: Int) {
518516
@chacha.counter = value
519517
}

std/test/std/crypto/test_chacha.inko

+9
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,15 @@ fn pub tests(t: mut Tests) {
388388
t.equal(secret.to_string, 'hello')
389389
})
390390

391+
t.panic('ChaCha.encrypt with a counter that overflows', fn {
392+
let key = ByteArray.filled(with: 1, times: 32)
393+
let nonce = ByteArray.filled(with: 1, times: 12)
394+
let cipher = ChaCha.new(key, nonce)
395+
396+
cipher.counter = INT_MAX
397+
cipher.encrypt('hello'.to_byte_array)
398+
})
399+
391400
t.test('chacha.hchacha20', fn (t) {
392401
let key = ByteArray.from_array(
393402
[

0 commit comments

Comments
 (0)