From 155efbbeeb532473c0ac3cc93f9a8a7597322157 Mon Sep 17 00:00:00 2001 From: qiulaidongfeng <2645477756@qq.com> Date: Thu, 23 Oct 2025 17:20:10 +0800 Subject: [PATCH] crypto/sha3: make the zero value of SHA3 useable Fixes #75154 Change-Id: I860ab0b4bd5d64e1f58aa5dfbab19d77e2925430 Reviewed-on: https://go-review.googlesource.com/c/go/+/714120 LUCI-TryBot-Result: Go LUCI Reviewed-by: Mark Freeman Reviewed-by: Sean Liao Reviewed-by: Junyang Shao --- src/crypto/sha3/sha3.go | 15 +++++++++++++++ src/crypto/sha3/sha3_test.go | 9 +++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/crypto/sha3/sha3.go b/src/crypto/sha3/sha3.go index 2a1b3ca700..9bdc914098 100644 --- a/src/crypto/sha3/sha3.go +++ b/src/crypto/sha3/sha3.go @@ -97,6 +97,7 @@ func sumSHAKE256(out, data []byte, length int) []byte { } // SHA3 is an instance of a SHA-3 hash. It implements [hash.Hash]. +// The zero value is a usable SHA3-256 hash. type SHA3 struct { s sha3.Digest } @@ -126,43 +127,57 @@ func New512() *SHA3 { return &SHA3{*sha3.New512()} } +func (s *SHA3) init() { + if s.s.Size() == 0 { + *s = *New256() + } +} + // Write absorbs more data into the hash's state. func (s *SHA3) Write(p []byte) (n int, err error) { + s.init() return s.s.Write(p) } // Sum appends the current hash to b and returns the resulting slice. func (s *SHA3) Sum(b []byte) []byte { + s.init() return s.s.Sum(b) } // Reset resets the hash to its initial state. func (s *SHA3) Reset() { + s.init() s.s.Reset() } // Size returns the number of bytes Sum will produce. func (s *SHA3) Size() int { + s.init() return s.s.Size() } // BlockSize returns the hash's rate. func (s *SHA3) BlockSize() int { + s.init() return s.s.BlockSize() } // MarshalBinary implements [encoding.BinaryMarshaler]. func (s *SHA3) MarshalBinary() ([]byte, error) { + s.init() return s.s.MarshalBinary() } // AppendBinary implements [encoding.BinaryAppender]. func (s *SHA3) AppendBinary(p []byte) ([]byte, error) { + s.init() return s.s.AppendBinary(p) } // UnmarshalBinary implements [encoding.BinaryUnmarshaler]. func (s *SHA3) UnmarshalBinary(data []byte) error { + s.init() return s.s.UnmarshalBinary(data) } diff --git a/src/crypto/sha3/sha3_test.go b/src/crypto/sha3/sha3_test.go index 15ee877236..2c2e5c98ff 100644 --- a/src/crypto/sha3/sha3_test.go +++ b/src/crypto/sha3/sha3_test.go @@ -22,10 +22,11 @@ const testString = "brekeccakkeccak koax koax" // with output-length equal to the KAT length for SHA-3, Keccak // and SHAKE instances. var testDigests = map[string]func() *SHA3{ - "SHA3-224": New224, - "SHA3-256": New256, - "SHA3-384": New384, - "SHA3-512": New512, + "SHA3-224": New224, + "SHA3-256": New256, + "SHA3-384": New384, + "SHA3-512": New512, + "SHA3-Zero": func() *SHA3 { return &SHA3{} }, } // testShakes contains functions that return *sha3.SHAKE instances for -- 2.52.0