From 43c45d95824f378b9edc46017e3c2382ccb54bc9 Mon Sep 17 00:00:00 2001 From: Mike <45243121+tankf33der@users.noreply.github.com> Date: Fri, 24 Oct 2025 22:46:01 +0300 Subject: [PATCH] crypto.cipher: fix decryption in CBC mode, add test (#25584) --- vlib/crypto/cipher/aes_cbc_test.v | 24 ++++++++++++++++++++++++ vlib/crypto/cipher/cbc.v | 3 +-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/vlib/crypto/cipher/aes_cbc_test.v b/vlib/crypto/cipher/aes_cbc_test.v index d7ab8d7b4..b94334fdc 100644 --- a/vlib/crypto/cipher/aes_cbc_test.v +++ b/vlib/crypto/cipher/aes_cbc_test.v @@ -4,6 +4,30 @@ import crypto.aes import crypto.cipher +fn test_aes_cbc_double() { + orig1 := []u8{len: 64, init: index} + orig2 := []u8{len: 16, init: index} + key := []u8{len: 16} + iv := []u8{len: 16} + + mut block := aes.new_cipher(key) + mut en_cbc := cipher.new_cbc(block, iv) + mut cip1 := []u8{len: orig1.len} + mut cip2 := []u8{len: orig2.len} + en_cbc.encrypt_blocks(mut cip1, orig1) + en_cbc.encrypt_blocks(mut cip2, orig2) + + mut block2 := aes.new_cipher(key) + mut dec_cbc := cipher.new_cbc(block2, iv) + mut plain1 := []u8{len: orig1.len} + mut plain2 := []u8{len: orig2.len} + dec_cbc.decrypt_blocks(mut plain1, cip1) + dec_cbc.decrypt_blocks(mut plain2, cip2) + + assert plain1 == orig1 + assert plain2 == orig2 +} + fn test_aes_cbc() { key := '6368616e676520746869732070617373'.bytes() iv := '1234567890123456'.bytes() diff --git a/vlib/crypto/cipher/cbc.v b/vlib/crypto/cipher/cbc.v index 0f49af436..a8c277054 100644 --- a/vlib/crypto/cipher/cbc.v +++ b/vlib/crypto/cipher/cbc.v @@ -122,8 +122,7 @@ pub fn (mut x Cbc) decrypt_blocks(mut dst []u8, src []u8) { x.b.decrypt(mut (*dst)[start..end], src_chunk) xor_bytes(mut (*dst)[start..end], (*dst)[start..end], x.iv) // Set the new iv to the first block we copied earlier. - x.iv = x.tmp - x.tmp = x.iv + x.iv, x.tmp = x.tmp, x.iv } fn (mut x Cbc) set_iv(iv []u8) { -- 2.39.5