github.com/cloudflare/circl@v1.5.0/xof/xof.go (about)

     1  // Package xof provides an interface for eXtendable-Output Functions.
     2  //
     3  // # Available Functions
     4  //
     5  // SHAKE functions are defined in FIPS-202, see https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf.
     6  // BLAKE2Xb and BLAKE2Xs are defined in https://www.blake2.net/blake2x.pdf.
     7  package xof
     8  
     9  import (
    10  	"io"
    11  
    12  	"github.com/cloudflare/circl/internal/sha3"
    13  	"github.com/cloudflare/circl/xof/k12"
    14  
    15  	"golang.org/x/crypto/blake2b"
    16  	"golang.org/x/crypto/blake2s"
    17  )
    18  
    19  // XOF defines the interface to hash functions that support arbitrary-length output.
    20  type XOF interface {
    21  	// Write absorbs more data into the XOF's state. It panics if called
    22  	// after Read.
    23  	io.Writer
    24  
    25  	// Read reads more output from the XOF. It returns io.EOF if the limit
    26  	// has been reached.
    27  	io.Reader
    28  
    29  	// Clone returns a copy of the XOF in its current state.
    30  	Clone() XOF
    31  
    32  	// Reset restores the XOF to its initial state and discards all data appended by Write.
    33  	Reset()
    34  }
    35  
    36  type ID uint
    37  
    38  const (
    39  	SHAKE128 ID = iota + 1
    40  	SHAKE256
    41  	BLAKE2XB
    42  	BLAKE2XS
    43  	K12D10
    44  )
    45  
    46  func (x ID) New() XOF {
    47  	switch x {
    48  	case SHAKE128:
    49  		s := sha3.NewShake128()
    50  		return shakeBody{&s}
    51  	case SHAKE256:
    52  		s := sha3.NewShake256()
    53  		return shakeBody{&s}
    54  	case BLAKE2XB:
    55  		x, _ := blake2b.NewXOF(blake2b.OutputLengthUnknown, nil)
    56  		return blake2xb{x}
    57  	case BLAKE2XS:
    58  		x, _ := blake2s.NewXOF(blake2s.OutputLengthUnknown, nil)
    59  		return blake2xs{x}
    60  	case K12D10:
    61  		x := k12.NewDraft10([]byte{})
    62  		return k12d10{&x}
    63  	default:
    64  		panic("crypto: requested unavailable XOF function")
    65  	}
    66  }
    67  
    68  type shakeBody struct{ sha3.ShakeHash }
    69  
    70  func (s shakeBody) Clone() XOF { return shakeBody{s.ShakeHash.Clone()} }
    71  
    72  type blake2xb struct{ blake2b.XOF }
    73  
    74  func (s blake2xb) Clone() XOF { return blake2xb{s.XOF.Clone()} }
    75  
    76  type blake2xs struct{ blake2s.XOF }
    77  
    78  func (s blake2xs) Clone() XOF { return blake2xs{s.XOF.Clone()} }
    79  
    80  type k12d10 struct{ *k12.State }
    81  
    82  func (s k12d10) Clone() XOF {
    83  	x := s.State.Clone()
    84  	return k12d10{&x}
    85  }