hasher

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 18 Imported by: 14 modules, 14 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

github.com/carabiner-dev/hasher

A simple go module to hash data focused on simplicity, performance and ease of use.

Install the Module

To install in your project simply use go get:

go get github.com/carabiner-dev/hasher

Examples

The hasher object can hash lists of io.Reader or a list of file paths:

package main

import (
    "github.com/carabiner-dev/hasher"
    intoto "github.com/in-toto/attestation/go/v1"
)

// Simple program to compute checksums of files
func main() {
    h := hasher.New()

    // Configure the algorithms hasher will use (optional):
    h.Options.Algorithms = []intoto.HashAlgorithm{
		intoto.AlgorithmSHA256, intoto.AlgorithmSHA512,
	}

    // Configure how many files to hash at once:
    h.Options.MaxParallel = 2

    // Run the hasher:
    hashes, err := h.HashFiles([]string{
        "hello.txt", "README.md",
    })
    if err != nil {
        os.Exit(1)
    }

    // Print the results:
    for path, hs := range hashes {
        fmt.Println(path + ":")
        for algo, value := range hs {
            fmt.Printf("  %s:%s\n", algo, value)
        }
    }
}

The resulting types can be natively converted to in-toto Resource Descriptors to easily use them when building attestations:

  // Hash a bunch of files:
  hashes, err := h.HashFiles([]string{"hello.txt", "README.md",})

  // Convert to a slice of intoto.ResourceDescriptor:
  descriptors = hashes.ToResourceDescriptors()

Implementation

The hasher implementation runs the hashing processes in parallel. While the sums for each algorithm are computed serially, hasher handles four input streams at the same time by default. Set MaxParallel in the options to change it.

The supported hashes are those of the hashing algorithms recognized in the in-toto project that are computed from a stream of bytes: the MD5, SHA-1, SHA-2 and SHA-3 families and gitBlob, the name git gives to a blob with the data. The gitCommit, gitTag, gitTree and dirHash algorithms of the catalog are not computed from the bytes of a file and asking for them is an error.

gitBlob is computed with SHA-1, as most repositories name their objects. Set GitSHA256 in the options to get the name of the blob in the sha256 object format.

Checking hashes

CheckReader hashes a stream in the algorithms of a set of expected hashes and compares them:

  err := h.CheckReader(f, &hasher.HashSet{
      intoto.AlgorithmSHA256: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
  })

  var mismatch *hasher.MismatchError
  if errors.As(err, &mismatch) {
      // The data has other hashes: mismatch.Algorithms names which,
      // mismatch.Expected and mismatch.Computed have the values.
  }

It returns nil when every hash matches. Any error other than a MismatchError means the data could not be checked. VerifyReader does the same check and returns a bool.

Files are opened as their turn to be hashed comes, so hashing a list of paths never holds more files open than streams are handled at a time.

License

This module is open source, licensed under the Apache 2.0 license

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNilReader = errors.New("unable to hash: reader is nil")

ErrNilReader is returned when asked to hash a reader that is nil.

HasherFactory is a preconfigured hasher map with the algorithms of the in-toto catalog that are computed from a stream of bytes.

The rest of the catalog is left out, as the bytes of a file are not what they are computed from: gitCommit, gitTag and gitTree name git objects built from other objects and dirHash is computed over a directory.

Functions

This section is empty.

Types

type FileHashSet

type FileHashSet map[string]HashSet

FileHashSet captures a set of hashes of the same artifact indexed by its path.

func (*FileHashSet) ToResourceDescriptors

func (fhs *FileHashSet) ToResourceDescriptors() []*intoto.ResourceDescriptor

ToResourceDescriptors returns a resource descriptor for each file of the set, with its hashes, its path as the URI and its base name as the name. The descriptors are sorted by path, so the same set always gives the same list.

type HashSet

type HashSet map[intoto.HashAlgorithm]string

HashSet captures a set of hashes of the same artifact.

func NewHashSet added in v0.2.1

func NewHashSet[K ~string, T ~string](data map[K]T) *HashSet

NewHashSet returns a new hashset from any map of string-like things

func (*HashSet) ToResourceDescriptor

func (hs *HashSet) ToResourceDescriptor() *intoto.ResourceDescriptor

ToResourceDescriptor returns a resource descriptor with the hashes of the set as its digest.

type HashSetList

type HashSetList []HashSet

HashSetList is an array of HashSets.

func (*HashSetList) ToResourceDescriptors

func (hsl *HashSetList) ToResourceDescriptors() []*intoto.ResourceDescriptor

ToResourceDescriptors returns a resource descriptor with the hashes of each set of the list, in the same order.

type Hasher

type Hasher struct {
	Options Options
}

Hasher is an object that has methods to hash data.

func New

func New() *Hasher

New returns a new Hasher configured with the default options

func (*Hasher) CheckReader added in v0.3.0

func (h *Hasher) CheckReader(r io.Reader, set *HashSet) error

CheckReader hashes the data read from r in the algorithms of the set and compares the results with it. It returns nil when every hash matches and a *MismatchError naming the algorithms that do not when some differ.

Any other error means the data could not be checked: the set is empty, it has an algorithm the hasher cannot compute or reading failed.

Hashes are compared ignoring case. A gitBlob hash of the size of a SHA-256 is compared with the name of the blob in the sha256 object format of git.

func (*Hasher) HashFiles

func (h *Hasher) HashFiles(paths []string) (*FileHashSet, error)

HashFiles gets a list of paths and returns the hashes of the files indexed by path. A path repeated in the list is hashed each time it appears and included once in the result.

Each file is opened when its turn to be hashed comes and closed when it is done, so no more than Options.MaxParallel files are open at a time.

func (*Hasher) HashReaders

func (h *Hasher) HashReaders(readers []io.Reader) (*HashSetList, error)

HashReaders hashes the data of a list of readers and returns their hashes in the same order. Up to Options.MaxParallel readers are read at a time.

func (*Hasher) VerifyReader added in v0.2.0

func (h *Hasher) VerifyReader(r io.Reader, set *HashSet) (bool, error)

VerifyReader compares a set of hashes against a reader data. If all match then it returns true. If a hash mismatches, it returns false. To learn which hashes did not match use CheckReader.

type HasherFactoryMap

type HasherFactoryMap map[intoto.HashAlgorithm]func() hash.Hash

HasherFactoryMap is a map that can create hash.Hash objects for all the recognized algorithm types.

func (*HasherFactoryMap) GetHasher

func (hf *HasherFactoryMap) GetHasher(algo intoto.HashAlgorithm) hash.Hash

type MismatchError added in v0.3.0

type MismatchError struct {
	// Algorithms lists the algorithms whose hash did not match, sorted.
	Algorithms []intoto.HashAlgorithm

	// Expected and Computed hold, for each of those algorithms, the hash
	// that was expected and the one the data has.
	Expected HashSet
	Computed HashSet
}

MismatchError is returned by CheckReader when the data does not have one or more of the expected hashes.

func (*MismatchError) Error added in v0.3.0

func (e *MismatchError) Error() string

type OptFn added in v0.2.0

type OptFn func(*Options) error

func WithAlgorithms added in v0.2.0

func WithAlgorithms[T ~string](algos []T) OptFn

func WithGitSHA256 added in v0.3.0

func WithGitSHA256(useSHA256 bool) OptFn

WithGitSHA256 sets the object format gitBlob is computed in: SHA-256 when true, SHA-1, the format of most repositories, when false.

type Options

type Options struct {
	Algorithms  []intoto.HashAlgorithm
	MaxParallel int

	// GitSHA256 computes gitBlob as repositories created with the sha256
	// object format name their blobs, with SHA-256 in place of SHA-1.
	GitSHA256 bool
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL