hash

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 11 Imported by: 7

README

Cryptographic Hash Functions

hash Go Reference codecov OpenSSF Best Practices OpenSSF Scorecard

  import "github.com/bytemare/hash"

This package exposes a simple API to seamlessly use a variety of cryptographic functions. It aims at minimum code adaptation in your code, and easy parameterization. It completely relies on built-ins.

It attempts to offer a single API for fixed and extensible-output functions, Merkle–Damgård construction (e.g. SHA-1, SHA-2), sponge functions (e.g. SHA-3, SHAKE), and HAIFA structures (e.g. Blake2). This API also provides useful metadata like block size, security, and output size when relevant.

Documentation Go Reference

You can find the documentation and usage examples in the package doc and the project wiki .

Versioning

SemVer is used for versioning. For the versions available, see the tags on the repository.

Contributing

Please read CONTRIBUTING.md for details on the code of conduct, and the process for submitting pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package hash is a small wrapper around built-in cryptographic hash functions to make their usage easier.

Example (Crypto)

Example_Crypto shows how to use this package if you already have a hash identifier from the built-in crypto package.

package main

import (
	"crypto"
	"encoding/hex"
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	input := []byte("input")

	output := hash.FromCrypto(crypto.SHA256).Hash(input)
	fmt.Printf("%s of %q = %s\n", hash.FromCrypto(crypto.SHA256), input, hex.EncodeToString(output))

}
Output:

SHA-256 of "input" = c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20
Example (Hashing)

Example_Hashing shows how to hash an input.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	input := []byte("input")

	output := hash.SHA256.Hash(input)
	fmt.Printf("%s of %q = %s\n", hash.SHA256, input, hex.EncodeToString(output))

}
Output:

SHA-256 of "input" = c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20
Example (Hkdf)

Example_HKDF shows how to derive a key with HKDF from an input secret, salt, and additional info.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	secret := []byte("secret")
	salt := []byte("salt")
	info := []byte("info")
	outputLength := 32
	h := hash.SHA256

	hkdf := h.GetHashFunction().HKDF(secret, salt, info, outputLength)
	fmt.Printf(
		"HKDF(%s) of (%s,%s,%s) for %d bytes = %s\n",
		h,
		secret,
		salt,
		info,
		outputLength,
		hex.EncodeToString(hkdf),
	)

}
Output:

HKDF(SHA-256) of (secret,salt,info) for 32 bytes = f6d2fcc47cb939deafe3853a1e641a27e6924aff7a63d09cb04ccfffbe4776ef
Example (Hkdf_extract_expand)

Example_HKDF_Extract_Expand shows how to derive multiple keys with HKDF-Extract-and-Expand from an input secret, salt, and additional info for each key.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	secret := []byte("secret")
	salt := []byte("salt")
	keyInfo := []string{"key1", "key2", "key3", "key4"}
	outputLength := 32
	h := hash.SHA256.GetHashFunction()

	prk := h.HKDFExtract(secret, salt)

	fmt.Printf(
		"HKDF-Expanded output keys from extracted pseudorandom key %q on %d bytes\n",
		hex.EncodeToString(prk),
		outputLength,
	)
	for _, info := range keyInfo {
		key := h.HKDFExpand(prk, []byte(info), outputLength)
		fmt.Printf("%s = %s\n", info, hex.EncodeToString(key))
	}

}
Output:

HKDF-Expanded output keys from extracted pseudorandom key "98e5340f0f4f96d2b80c2a90da0d03cf46c35e9492918cc7af73d9a39efa5981" on 32 bytes
key1 = f490601be934fe13381586ba657fae4534c0921345d41b97b804bf76ba29664b
key2 = cca6ff4021287207e49c5e8297bea41b405eed697f78ef1174707a0bfcf70da7
key3 = a9d11fb5ce71802b6a4c19e7bb45c51aa7e131ea3b673e1fb77a6698babbf1ea
key4 = ff0330c4aaf9cc58db65a5346b0e97050856649e2cc0a256038133c30b420bfc
Example (Hmac)

Example_Hmac shows how to compute a HMAC for a message and key.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	message := []byte("message")
	key := []byte("key")
	h := hash.SHA256

	hmac := h.GetHashFunction().Hmac(message, key)
	fmt.Printf("HMAC(%s) of (%s,%s) = %s\n", h, message, key, hex.EncodeToString(hmac))

}
Output:

HMAC(SHA-256) of (message,key) = 6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a
Example (Info)

Example_Info shows what hash function metadata is available.

package main

import (
	"fmt"

	"github.com/bytemare/hash"
)

func main() {
	ids := []hash.Hash{hash.SHA512, hash.BLAKE2XS}

	for _, id := range ids {
		fmt.Printf("Hash function: %s\n", id)
		fmt.Printf("Is available? %v\n", id.Available())
		fmt.Printf("Hash type: %s\n", id.Type())
		fmt.Printf("Security level (bits): %d\n", id.SecurityLevel())
		fmt.Printf("Standard output size (bytes): %d\n", id.Size())
		fmt.Printf("Underlying block size (bytes): %d\n", id.BlockSize())
	}

	fmt.Printf("NOTE that the block size is only relevant for fixed output length functions, and is set to 0 for XOF")

}
Output:

Hash function: SHA-512
Is available? true
Hash type: fixed
Security level (bits): 256
Standard output size (bytes): 64
Underlying block size (bytes): 128
Hash function: BLAKE2XS
Is available? true
Hash type: extendable-output-function
Security level (bits): 128
Standard output size (bytes): 32
Underlying block size (bytes): 0
NOTE that the block size is only relevant for fixed output length functions, and is set to 0 for XOF

Index

Examples

Constants

View Source
const (
	// SHA256 identifies the Sha2 hashing function with 256 bit output.
	SHA256 = Hash(crypto.SHA256)

	// SHA384 identifies the Sha2 hashing function with 384 bit output.
	SHA384 = Hash(crypto.SHA384)

	// SHA512 identifies the Sha2 hashing function with 512 bit output.
	SHA512 = Hash(crypto.SHA512)

	// SHA3_256 identifies the Sha3 hashing function with 256 bit output.
	SHA3_256 = Hash(crypto.SHA3_256)

	// SHA3_384 identifies the Sha3 hashing function with 384 bit output.
	SHA3_384 = Hash(crypto.SHA3_384)

	// SHA3_512 identifies the Sha3 hashing function with 512 bit output.
	SHA3_512 = Hash(crypto.SHA3_512)

	// SHAKE128 identifies the SHAKE128 Extendable-Output Function.
	SHAKE128 Hash = maxFixed + 1

	// SHAKE256 identifies the SHAKE256 Extendable-Output Function.
	SHAKE256 Hash = maxFixed + 2

	// BLAKE2XB identifies the BLAKE2XB Extendable-Output Function.
	BLAKE2XB Hash = maxFixed + 3

	// BLAKE2XS identifies the BLAKE2XS Extendable-Output Function.
	BLAKE2XS Hash = maxFixed + 4
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ExtendableHash

type ExtendableHash struct {
	// contains filtered or unexported fields
}

ExtendableHash offers easy an easy-to-use API for common cryptographic hash operations of extendable output functions.

func (*ExtendableHash) Algorithm added in v0.2.0

func (h *ExtendableHash) Algorithm() Hash

Algorithm returns the Hash function identifier.

func (*ExtendableHash) BlockSize added in v0.2.0

func (h *ExtendableHash) BlockSize() int

BlockSize returns the hash's underlying block size.

func (*ExtendableHash) GetHashFunction added in v0.2.0

func (h *ExtendableHash) GetHashFunction() *Fixed

GetHashFunction returns nil.

func (*ExtendableHash) GetXOF added in v0.2.0

func (h *ExtendableHash) GetXOF() *ExtendableHash

GetXOF returns the underlying ExtendableHash Hasher.

func (*ExtendableHash) Hash

func (h *ExtendableHash) Hash(size uint, input ...[]byte) []byte

Hash returns the hash of the input argument with size output length.

func (*ExtendableHash) Read

func (h *ExtendableHash) Read(size int) []byte

Read consumes and returns size bytes from the current hash.

func (*ExtendableHash) Reset

func (h *ExtendableHash) Reset()

Reset resets the hash to its initial state.

func (*ExtendableHash) Size added in v0.2.0

func (h *ExtendableHash) Size() int

Size returns the number of bytes Hash will return.

func (*ExtendableHash) Sum added in v0.2.0

func (h *ExtendableHash) Sum(prefix []byte) []byte

Sum appends the current hash to b and returns the resulting slice.

func (*ExtendableHash) Write

func (h *ExtendableHash) Write(input []byte) (int, error)

Write implements io.Writer.

type Fixed added in v0.2.0

type Fixed struct {
	// contains filtered or unexported fields
}

Fixed offers easy an easy-to-use API for common cryptographic hash operations of the SHA family.

func (*Fixed) Algorithm added in v0.2.0

func (h *Fixed) Algorithm() Hash

Algorithm returns the Hash function identifier.

func (*Fixed) BlockSize added in v0.2.0

func (h *Fixed) BlockSize() int

BlockSize returns the hash's underlying block size.

func (*Fixed) GetHashFunction added in v0.2.0

func (h *Fixed) GetHashFunction() *Fixed

GetHashFunction returns the underlying Fixed Hasher.

func (*Fixed) GetXOF added in v0.2.0

func (h *Fixed) GetXOF() *ExtendableHash

GetXOF returns nil.

func (*Fixed) HKDF added in v0.2.0

func (h *Fixed) HKDF(secret, salt, info []byte, length int) []byte

HKDF is an "extract-then-expand" HMAC based Key derivation function, where info is the specific usage identifying information.

func (*Fixed) HKDFExpand added in v0.2.0

func (h *Fixed) HKDFExpand(pseudorandomKey, info []byte, length int) []byte

HKDFExpand is an "expand" only HKDF, where the key should be an already random/hashed input, and info specific key usage identifying information.

func (*Fixed) HKDFExtract added in v0.2.0

func (h *Fixed) HKDFExtract(secret, salt []byte) []byte

HKDFExtract is an "extract" only HKDF, where the secret and salt are used to generate a pseudorandom key. This key can then be used in multiple HKDFExpand calls to derive individual different keys.

func (*Fixed) Hash added in v0.2.0

func (h *Fixed) Hash(_ uint, input ...[]byte) []byte

Hash hashes the concatenation of input and returns size bytes. The size is ignored as the output size is standard.

func (*Fixed) Hmac added in v0.2.0

func (h *Fixed) Hmac(message, key []byte) []byte

Hmac wraps the built-in hmac.

func (*Fixed) Read added in v0.2.0

func (h *Fixed) Read(_ int) []byte

Read returns size bytes from the current hash. It does not change the underlying hash state.

func (*Fixed) Reset added in v0.2.0

func (h *Fixed) Reset()

Reset resets the hash to its initial state.

func (*Fixed) Size added in v0.2.0

func (h *Fixed) Size() int

Size returns the number of bytes Hash will return.

func (*Fixed) Sum added in v0.2.0

func (h *Fixed) Sum(prefix []byte) []byte

Sum appends the current hash to b and returns the resulting slice. It does not change the underlying hash state.

func (*Fixed) Write added in v0.2.0

func (h *Fixed) Write(input []byte) (int, error)

Write implements io.Writer.

type Hash

type Hash uint8

func FromCrypto

func FromCrypto(h crypto.Hash) Hash

FromCrypto returns a Hashing identifier given a hash function defined in the built-in crypto, if it has been registered.

func (Hash) Available added in v0.2.0

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

func (Hash) BlockSize added in v0.2.0

func (h Hash) BlockSize() int

BlockSize returns the hash's underlying block size in bytes.

func (Hash) GetHashFunction added in v0.2.0

func (h Hash) GetHashFunction() *Fixed

GetHashFunction returns the underlying Fixed Hasher for FixedOutputLength functions, and nil otherwise.

func (Hash) GetXOF added in v0.2.0

func (h Hash) GetXOF() *ExtendableHash

GetXOF returns the underlying ExtendableHash Hasher for ExtendableOutputFunction functions, and nil otherwise.

func (Hash) Hash

func (h Hash) Hash(input ...[]byte) []byte

Hash returns the hash of the concatenated input.

func (Hash) New added in v0.2.0

func (h Hash) New() Hasher

New returns the underlying Hasher function.

func (Hash) SecurityLevel added in v0.2.0

func (h Hash) SecurityLevel() int

SecurityLevel returns the hash function's security level in bits.

func (Hash) Size added in v0.2.0

func (h Hash) Size() int

Size returns the standard number of bytes returned by Hash.

func (Hash) String added in v0.2.0

func (h Hash) String() string

String returns the Hash functions name.

func (Hash) Type added in v0.2.0

func (h Hash) Type() Type

Type returns the hash function's type.

type Hasher added in v0.2.0

type Hasher interface {
	// Algorithm returns the Hash function identifier.
	Algorithm() Hash

	// Hash hashes the concatenation of input and returns size bytes. The size is ignored for fixed output length hashes
	// as their output size is standard.
	Hash(size uint, input ...[]byte) []byte

	// Read returns size bytes from the current hash.
	// The underlying hash state is not modified for Merkle–Damgård constructions, and size bytes will be consumed
	// for extendable output functions.
	Read(size int) []byte

	// Writer (via the embedded io.Writer interface) adds more data to the running hash.
	// It never returns an error.
	io.Writer

	// Sum appends the current hash to b and returns the resulting slice.
	Sum(prefix []byte) []byte

	// Reset resets the hash to its initial state.
	Reset()

	// Size returns the number of bytes Hash will return.
	Size() int

	// BlockSize returns the hash's underlying block size.
	BlockSize() int

	// GetHashFunction returns the underlying Fixed Hasher for FixedOutputLength functions, and nil otherwise.
	GetHashFunction() *Fixed

	// GetXOF returns the underlying ExtendableHash Hasher for ExtendableOutputFunction functions, and nil otherwise.
	GetXOF() *ExtendableHash
}

type Type added in v0.2.0

type Type string

Type identifies the hash function types.

var (
	// FixedOutputLength identifies fixed output length hash functions.
	FixedOutputLength Type = "fixed"

	// ExtendableOutputFunction identifies extendable output length functions.
	ExtendableOutputFunction Type = "extendable-output-function"
)

Jump to

Keyboard shortcuts

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