From: brian m. carlson Date: Tue, 07 Jul 2026 21:41:00 GMT Subject: Re: [PATCH 4/7] hash: make git_hash_discard() idempotent Message-ID: In-Reply-To: <20260707201808.GD11780@coredump.intra.peff.net> On 2026-07-07 at 20:18:08, Jeff King wrote: > On Tue, Jul 07, 2026 at 09:22:04AM -0700, Junio C Hamano wrote: > > But the change nevertheless looks mostly good except for one "hmph". > > When _init() is called, active gets turned on automatically, and > > either _discard() or _final() turns it off. Only _discard() is > > protected from getting called multiple times. Is this because > > it is already a no-op to call _final() multiple times? > > No, it's a bug to call _final() multiple times. See my response > elsewhere in the thread. This is almost always the case in hash function libraries. Let me explain why. A context for SHA-256 contains the 8 32-bit words in the state, a bit or byte counter (as a 64-bit quantity or two 32-bit quantities), and a 64-byte buffer for unprocessed bytes—and that's it. When finalizing a hash, you must always pad with a 0x80 byte and then optionally some zero bytes, plus a 64-bit counter of bits in the message. That may result in one or two iterations of the hash to process the remaining bytes and the padding, and that almost always updates the state words in the context in place. (SHA-1 functions identically but for the state size.) So if you call the final function multiple times, you're not computing the final value the second time, but instead trying to re-pad and re-compute the final hash value, which results in a _different_, incorrect value. In SHA-256, this is a valid hash value for a different message (which is the original message with the padding and length tacked on and is effectively a length-extension attack), but in hashes that don't allow length-extension attacks, such as SHA-3 and BLAKE2, what you get is simply corrupt data. So most hash function libraries that allocate memory are going to free it in the final function because you can't really call final multiple times and get a sensible response. If you want to do that, then you need to clone the context and call final on each context once. Our Rust code makes calling final a second time impossible because finalization takes `self`, not `&mut self`, so the object is _moved_ into the final method and you no longer have access to it after that. -- brian m. carlson (they/them) Toronto, Ontario, CA