...

Source file src/golang.org/x/crypto/sha3/shake.go

Documentation: golang.org/x/crypto/sha3

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sha3
     6  
     7  // This file defines the ShakeHash interface, and provides
     8  // functions for creating SHAKE and cSHAKE instances, as well as utility
     9  // functions for hashing bytes to arbitrary-length output.
    10  //
    11  //
    12  // SHAKE implementation is based on FIPS PUB 202 [1]
    13  // cSHAKE implementations is based on NIST SP 800-185 [2]
    14  //
    15  // [1] https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
    16  // [2] https://doi.org/10.6028/NIST.SP.800-185
    17  
    18  import (
    19  	"bytes"
    20  	"encoding/binary"
    21  	"errors"
    22  	"hash"
    23  	"io"
    24  	"math/bits"
    25  )
    26  
    27  // ShakeHash defines the interface to hash functions that support
    28  // arbitrary-length output. When used as a plain [hash.Hash], it
    29  // produces minimum-length outputs that provide full-strength generic
    30  // security.
    31  type ShakeHash interface {
    32  	hash.Hash
    33  
    34  	// Read reads more output from the hash; reading affects the hash's
    35  	// state. (ShakeHash.Read is thus very different from Hash.Sum)
    36  	// It never returns an error, but subsequent calls to Write or Sum
    37  	// will panic.
    38  	io.Reader
    39  
    40  	// Clone returns a copy of the ShakeHash in its current state.
    41  	Clone() ShakeHash
    42  }
    43  
    44  // cSHAKE specific context
    45  type cshakeState struct {
    46  	*state // SHA-3 state context and Read/Write operations
    47  
    48  	// initBlock is the cSHAKE specific initialization set of bytes. It is initialized
    49  	// by newCShake function and stores concatenation of N followed by S, encoded
    50  	// by the method specified in 3.3 of [1].
    51  	// It is stored here in order for Reset() to be able to put context into
    52  	// initial state.
    53  	initBlock []byte
    54  }
    55  
    56  func bytepad(data []byte, rate int) []byte {
    57  	out := make([]byte, 0, 9+len(data)+rate-1)
    58  	out = append(out, leftEncode(uint64(rate))...)
    59  	out = append(out, data...)
    60  	if padlen := rate - len(out)%rate; padlen < rate {
    61  		out = append(out, make([]byte, padlen)...)
    62  	}
    63  	return out
    64  }
    65  
    66  func leftEncode(x uint64) []byte {
    67  	// Let n be the smallest positive integer for which 2^(8n) > x.
    68  	n := (bits.Len64(x) + 7) / 8
    69  	if n == 0 {
    70  		n = 1
    71  	}
    72  	// Return n || x with n as a byte and x an n bytes in big-endian order.
    73  	b := make([]byte, 9)
    74  	binary.BigEndian.PutUint64(b[1:], x)
    75  	b = b[9-n-1:]
    76  	b[0] = byte(n)
    77  	return b
    78  }
    79  
    80  func newCShake(N, S []byte, rate, outputLen int, dsbyte byte) ShakeHash {
    81  	c := cshakeState{state: &state{rate: rate, outputLen: outputLen, dsbyte: dsbyte}}
    82  	c.initBlock = make([]byte, 0, 9+len(N)+9+len(S)) // leftEncode returns max 9 bytes
    83  	c.initBlock = append(c.initBlock, leftEncode(uint64(len(N))*8)...)
    84  	c.initBlock = append(c.initBlock, N...)
    85  	c.initBlock = append(c.initBlock, leftEncode(uint64(len(S))*8)...)
    86  	c.initBlock = append(c.initBlock, S...)
    87  	c.Write(bytepad(c.initBlock, c.rate))
    88  	return &c
    89  }
    90  
    91  // Reset resets the hash to initial state.
    92  func (c *cshakeState) Reset() {
    93  	c.state.Reset()
    94  	c.Write(bytepad(c.initBlock, c.rate))
    95  }
    96  
    97  // Clone returns copy of a cSHAKE context within its current state.
    98  func (c *cshakeState) Clone() ShakeHash {
    99  	b := make([]byte, len(c.initBlock))
   100  	copy(b, c.initBlock)
   101  	return &cshakeState{state: c.clone(), initBlock: b}
   102  }
   103  
   104  // Clone returns copy of SHAKE context within its current state.
   105  func (c *state) Clone() ShakeHash {
   106  	return c.clone()
   107  }
   108  
   109  func (c *cshakeState) MarshalBinary() ([]byte, error) {
   110  	return c.AppendBinary(make([]byte, 0, marshaledSize+len(c.initBlock)))
   111  }
   112  
   113  func (c *cshakeState) AppendBinary(b []byte) ([]byte, error) {
   114  	b, err := c.state.AppendBinary(b)
   115  	if err != nil {
   116  		return nil, err
   117  	}
   118  	b = append(b, c.initBlock...)
   119  	return b, nil
   120  }
   121  
   122  func (c *cshakeState) UnmarshalBinary(b []byte) error {
   123  	if len(b) <= marshaledSize {
   124  		return errors.New("sha3: invalid hash state")
   125  	}
   126  	if err := c.state.UnmarshalBinary(b[:marshaledSize]); err != nil {
   127  		return err
   128  	}
   129  	c.initBlock = bytes.Clone(b[marshaledSize:])
   130  	return nil
   131  }
   132  
   133  // NewShake128 creates a new SHAKE128 variable-output-length ShakeHash.
   134  // Its generic security strength is 128 bits against all attacks if at
   135  // least 32 bytes of its output are used.
   136  func NewShake128() ShakeHash {
   137  	return newShake128()
   138  }
   139  
   140  // NewShake256 creates a new SHAKE256 variable-output-length ShakeHash.
   141  // Its generic security strength is 256 bits against all attacks if
   142  // at least 64 bytes of its output are used.
   143  func NewShake256() ShakeHash {
   144  	return newShake256()
   145  }
   146  
   147  func newShake128Generic() *state {
   148  	return &state{rate: rateK256, outputLen: 32, dsbyte: dsbyteShake}
   149  }
   150  
   151  func newShake256Generic() *state {
   152  	return &state{rate: rateK512, outputLen: 64, dsbyte: dsbyteShake}
   153  }
   154  
   155  // NewCShake128 creates a new instance of cSHAKE128 variable-output-length ShakeHash,
   156  // a customizable variant of SHAKE128.
   157  // N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is
   158  // desired. S is a customization byte string used for domain separation - two cSHAKE
   159  // computations on same input with different S yield unrelated outputs.
   160  // When N and S are both empty, this is equivalent to NewShake128.
   161  func NewCShake128(N, S []byte) ShakeHash {
   162  	if len(N) == 0 && len(S) == 0 {
   163  		return NewShake128()
   164  	}
   165  	return newCShake(N, S, rateK256, 32, dsbyteCShake)
   166  }
   167  
   168  // NewCShake256 creates a new instance of cSHAKE256 variable-output-length ShakeHash,
   169  // a customizable variant of SHAKE256.
   170  // N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is
   171  // desired. S is a customization byte string used for domain separation - two cSHAKE
   172  // computations on same input with different S yield unrelated outputs.
   173  // When N and S are both empty, this is equivalent to NewShake256.
   174  func NewCShake256(N, S []byte) ShakeHash {
   175  	if len(N) == 0 && len(S) == 0 {
   176  		return NewShake256()
   177  	}
   178  	return newCShake(N, S, rateK512, 64, dsbyteCShake)
   179  }
   180  
   181  // ShakeSum128 writes an arbitrary-length digest of data into hash.
   182  func ShakeSum128(hash, data []byte) {
   183  	h := NewShake128()
   184  	h.Write(data)
   185  	h.Read(hash)
   186  }
   187  
   188  // ShakeSum256 writes an arbitrary-length digest of data into hash.
   189  func ShakeSum256(hash, data []byte) {
   190  	h := NewShake256()
   191  	h.Write(data)
   192  	h.Read(hash)
   193  }
   194  

View as plain text