Skip to content

Commit

Permalink
Fix wrong padding for when no extra zero padding bits are required
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
amn committed Feb 19, 2022
1 parent f39f553 commit 4c0788d
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions MD5.wat.m4
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,15 @@ define(`I', `(i32.xor (local.get $$2) (i32.or (local.get $$1) (i32.xor (local.ge
(local.tee $end (i32.add (local.get $end) (i32.const 1)))
(local.set $end_padding
(i32.add
(i32.sub
(i32.const 64)
(i32.and
(i32.add
(local.get $n_bytes)
(i32.const 9))
(i32.const 63)))))
(i32.and
(i32.sub
(i32.const 64)
(i32.and
(i32.add
(local.get $n_bytes)
(i32.const 9))
(i32.const 63)))
(i32.const 63))))
(loop $pad_with_zero
(if (i32.ne (local.get $end) (local.get $end_padding)) (then
(i32.store (local.get $end) (i32.const 0))
Expand Down

0 comments on commit 4c0788d

Please sign in to comment.