shake.go 5.9 KB

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