Skip to content

Commit 43c45d9

Browse files
authored
crypto.cipher: fix decryption in CBC mode, add test (#25584)
1 parent 2572ec1 commit 43c45d9

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

‎vlib/crypto/cipher/aes_cbc_test.v‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,30 @@
44
import crypto.aes
55
import crypto.cipher
66

7+
fn test_aes_cbc_double() {
8+
orig1 := []u8{len: 64, init: index}
9+
orig2 := []u8{len: 16, init: index}
10+
key := []u8{len: 16}
11+
iv := []u8{len: 16}
12+
13+
mut block := aes.new_cipher(key)
14+
mut en_cbc := cipher.new_cbc(block, iv)
15+
mut cip1 := []u8{len: orig1.len}
16+
mut cip2 := []u8{len: orig2.len}
17+
en_cbc.encrypt_blocks(mut cip1, orig1)
18+
en_cbc.encrypt_blocks(mut cip2, orig2)
19+
20+
mut block2 := aes.new_cipher(key)
21+
mut dec_cbc := cipher.new_cbc(block2, iv)
22+
mut plain1 := []u8{len: orig1.len}
23+
mut plain2 := []u8{len: orig2.len}
24+
dec_cbc.decrypt_blocks(mut plain1, cip1)
25+
dec_cbc.decrypt_blocks(mut plain2, cip2)
26+
27+
assert plain1 == orig1
28+
assert plain2 == orig2
29+
}
30+
731
fn test_aes_cbc() {
832
key := '6368616e676520746869732070617373'.bytes()
933
iv := '1234567890123456'.bytes()

‎vlib/crypto/cipher/cbc.v‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,7 @@ pub fn (mut x Cbc) decrypt_blocks(mut dst []u8, src []u8) {
122122
x.b.decrypt(mut (*dst)[start..end], src_chunk)
123123
xor_bytes(mut (*dst)[start..end], (*dst)[start..end], x.iv)
124124
// Set the new iv to the first block we copied earlier.
125-
x.iv = x.tmp
126-
x.tmp = x.iv
125+
x.iv, x.tmp = x.tmp, x.iv
127126
}
128127

129128
fn (mut x Cbc) set_iv(iv []u8) {

0 commit comments

Comments
 (0)