From 7101472677283577ec8aa3dc4976fbd70ad6a702 Mon Sep 17 00:00:00 2001 From: Mike <45243121+tankf33der@users.noreply.github.com> Date: Thu, 25 Sep 2025 17:49:30 +0300 Subject: [PATCH] x.crypto.ascon: fix encryption when the remainder of dividing the message length by 16 is greater than or equal to 8 (#25385) --- vlib/x/crypto/ascon/aead128.v | 18 ++++++------------ vlib/x/crypto/ascon/aead128_test.v | 13 +++++++++++++ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/vlib/x/crypto/ascon/aead128.v b/vlib/x/crypto/ascon/aead128.v index 73031fc8d..9e93f360f 100644 --- a/vlib/x/crypto/ascon/aead128.v +++ b/vlib/x/crypto/ascon/aead128.v @@ -370,18 +370,12 @@ fn aead128_process_msg(mut out []u8, mut s State, msg []u8) int { } // process partial block if it exists if mlen >= 8 { - mut first_block := unsafe { msg[midx..] } - s.e0 ^= load_bytes(first_block[0..8], 8) - binary.little_endian_put_u64(mut out[pos..pos + 8], s.e0) - - // Is there are reminder bytes to process on? - last_block := unsafe { msg[midx + 8..] } - if last_block.len > 0 { - // We use `load_bytes` to handle length < 8 - s.e1 ^= load_bytes(last_block, last_block.len) - store_bytes(mut out[pos + 8..], s.e1, last_block.len) - s.e1 ^= pad(last_block.len) - } + mut block := unsafe { msg[midx..] } + s.e0 ^= load_bytes(block[0..8], 8) + s.e1 ^= load_bytes(block[8..], mlen - 8) + store_bytes(mut out[pos..], s.e0, 8) + store_bytes(mut out[pos + 8..], s.e1, mlen - 8) + s.e1 ^= pad(mlen - 8) } else { last_block := unsafe { msg[midx..] } s.e0 ^= load_bytes(last_block, last_block.len) diff --git a/vlib/x/crypto/ascon/aead128_test.v b/vlib/x/crypto/ascon/aead128_test.v index 06dba8a99..8ae477c01 100644 --- a/vlib/x/crypto/ascon/aead128_test.v +++ b/vlib/x/crypto/ascon/aead128_test.v @@ -5,6 +5,7 @@ module ascon import encoding.hex +import rand // This test materials was taken and adapted into v from references implementation of Ascon-aead128 // especially for the known answer test data, but, its not all fully-taken, just randomly choosen item. @@ -246,3 +247,15 @@ const aead128_kat_tests_data = [ ct: 'fabe2cb1e7eba6329a30080f26e7dc72503dfc57f4de06a334b7ebadca03b44b73e9' }, ] + +fn test_ascon_aead128_loop() { + for n in 0 .. 256 { + key := []u8{len: 16, init: rand.u8()} + nonce := []u8{len: 16, init: rand.u8()} + ad := []u8{len: int(rand.u8()), init: rand.u8()} + txt := []u8{len: n, init: rand.u8()} + e := encrypt(key, nonce, ad, txt)! + d := decrypt(key, nonce, ad, e)! + assert txt == d + } +} -- 2.39.5