Skip to content

Commit

Permalink
Add multihasher for computing multiple hashes at once
Browse files Browse the repository at this point in the history
Signed-off-by: Cody Soyland <codysoyland@github.com>
  • Loading branch information
codysoyland committed Dec 18, 2024
1 parent 3cda2ea commit f148b5d
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
34 changes: 34 additions & 0 deletions pkg/verify/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,37 @@ func verifyMessageSignatureWithArtifactDigest(verifier signature.Verifier, msg M

return nil
}

type multihasher struct {
hashfuncs []crypto.Hash
hashes []hash.Hash
}

func newMultihasher(hashfuncs []crypto.Hash) *multihasher {
hashes := make([]hash.Hash, len(hashfuncs))
for i := range hashfuncs {
hashes[i] = hashfuncs[i].New()
}
return &multihasher{
hashfuncs: hashfuncs,
hashes: hashes,
}
}

func (m *multihasher) Write(p []byte) (n int, err error) {
for i := range m.hashes {
n, err = m.hashes[i].Write(p)
if err != nil {
return
}
}
return
}

func (m *multihasher) Sum(b []byte) map[crypto.Hash][]byte {
sums := make(map[crypto.Hash][]byte, len(m.hashes))
for i := range m.hashes {
sums[m.hashfuncs[i]] = m.hashes[i].Sum(b)
}
return sums
}
40 changes: 40 additions & 0 deletions pkg/verify/signature_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package verify

import (
"crypto"
"crypto/sha256"
"crypto/sha512"
"testing"

"github.com/stretchr/testify/assert"
)

func TestMultiHasher(t *testing.T) {
testBytes := []byte("Hello, world!")
hash256 := sha256.Sum256(testBytes)
hash512 := sha512.Sum512(testBytes)

hasher := newMultihasher([]crypto.Hash{crypto.SHA256, crypto.SHA512})
_, err := hasher.Write(testBytes)
assert.NoError(t, err)

hashes := hasher.Sum(nil)

assert.Equal(t, 2, len(hashes))
assert.EqualValues(t, hash256[:], hashes[crypto.SHA256])
assert.EqualValues(t, hash512[:], hashes[crypto.SHA512])
}

0 comments on commit f148b5d

Please sign in to comment.