Skip to content

Commit 4c0788d

Browse files
committed
Fix wrong padding for when no extra zero padding bits are required
This commit fixes incorrect padding calculation for those chunk sizes where no extra (beyond the 0b1000000 right after chunk data) padding bits are correctly required. The incorrect calculation would add 64 bytes of zero padded bits in this case, because 64 modulo 64 is 0 and not 64. To explain, here is how the previous procedure computed how many bytes of zero-padded bits are to be added after the first 0b10000000 (which is always added because we deal with 8-bit bytes): end_padding = end + (64 - ((n_bytes + 1 + 8) mod 64)) (where `end_padding` is the offset at which the zero bytes end and `n_bytes` is the size of the [final] chunk that we're padding) The above works as intended -- calculating how many zero bytes we will have to insert after that first 0b10000000 and before the mandated 8-byte message length at the end of the padded chunk -- but ONLY for when `n_bytes + 1 + 8` is less than 64. If it equals 64 the amount is incorrectly calculated to be 64 instead of the correct value that is 0. Because we don't need any extra zero bytes if the padding including the first padding byte with the value of 0b1000000 and the 8-byte message length at the end of the padding, ends right at the alignment boundary. This commit fixes the above edge case by AND-ing the value of the `64 - ((n_bytes + 1 + 8) mod 64)` with 63, before adding it to `end` to compute `end_padding`.
1 parent f39f553 commit 4c0788d

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

MD5.wat.m4

+9-7
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,15 @@ define(`I', `(i32.xor (local.get $$2) (i32.or (local.get $$1) (i32.xor (local.ge
124124
(local.tee $end (i32.add (local.get $end) (i32.const 1)))
125125
(local.set $end_padding
126126
(i32.add
127-
(i32.sub
128-
(i32.const 64)
129-
(i32.and
130-
(i32.add
131-
(local.get $n_bytes)
132-
(i32.const 9))
133-
(i32.const 63)))))
127+
(i32.and
128+
(i32.sub
129+
(i32.const 64)
130+
(i32.and
131+
(i32.add
132+
(local.get $n_bytes)
133+
(i32.const 9))
134+
(i32.const 63)))
135+
(i32.const 63))))
134136
(loop $pad_with_zero
135137
(if (i32.ne (local.get $end) (local.get $end_padding)) (then
136138
(i32.store (local.get $end) (i32.const 0))

0 commit comments

Comments
 (0)