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 <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
This commit is contained in:
qiulaidongfeng
2025-10-23 17:20:10 +08:00
committed by Sean Liao
parent 6f16669e34
commit 155efbbeeb
2 changed files with 20 additions and 4 deletions

View File

@@ -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)
}

View File

@@ -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