sha3.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. import (
  6. "encoding/binary"
  7. )
  8. // spongeDirection indicates the direction bytes are flowing through the sponge.
  9. type spongeDirection int
  10. const (
  11. // spongeAbsorbing indicates that the sponge is absorbing input.
  12. spongeAbsorbing spongeDirection = iota
  13. // spongeSqueezing indicates that the sponge is being squeezed.
  14. spongeSqueezing
  15. )
  16. const (
  17. // maxRate is the maximum size of the internal buffer. SHAKE-256
  18. // currently needs the largest buffer.
  19. maxRate = 168
  20. )
  21. type state struct {
  22. // Generic sponge components.
  23. a [25]uint64 // main state of the hash
  24. buf []byte // points into storage
  25. rate int // the number of bytes of state to use
  26. // dsbyte contains the "domain separation" value and the first bit of
  27. // the padding. In sections 6.1 and 6.2 of [1], the SHA-3 and SHAKE
  28. // functions are defined with bits appended to the message: SHA-3
  29. // functions have 01 and SHAKE functions have 1111. Because of the way
  30. // that bits are numbered from the LSB upwards, that ends up as
  31. // 00000010b and 00001111b, respectively. Then the padding rule from
  32. // section 5.1 is applied to pad to a multiple of the rate, which
  33. // involves adding a 1 bit, zero or more zero bits and then a final one
  34. // bit. The first one bit from the padding is merged into the dsbyte
  35. // value giving 00000110b (0x06) and 00011111b (0x1f), respectively.
  36. //
  37. // [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf,
  38. dsbyte byte
  39. storage [maxRate]byte
  40. // Specific to SHA-3 and SHAKE.
  41. fixedOutput bool // whether this is a fixed-ouput-length instance
  42. outputLen int // the default output size in bytes
  43. state spongeDirection // current direction of the sponge
  44. }
  45. // BlockSize returns the rate of sponge underlying this hash function.
  46. func (d *state) BlockSize() int { return d.rate }
  47. // Size returns the output size of the hash function in bytes.
  48. func (d *state) Size() int { return d.outputLen }
  49. // Reset clears the internal state by zeroing the sponge state and
  50. // the byte buffer, and setting Sponge.state to absorbing.
  51. func (d *state) Reset() {
  52. // Zero the permutation's state.
  53. for i := range d.a {
  54. d.a[i] = 0
  55. }
  56. d.state = spongeAbsorbing
  57. d.buf = d.storage[:0]
  58. }
  59. func (d *state) clone() *state {
  60. ret := *d
  61. if ret.state == spongeAbsorbing {
  62. ret.buf = ret.storage[:len(ret.buf)]
  63. } else {
  64. ret.buf = ret.storage[d.rate-cap(d.buf) : d.rate]
  65. }
  66. return &ret
  67. }
  68. // xorIn xors a buffer into the state, byte-swapping to
  69. // little-endian as necessary; it returns the number of bytes
  70. // copied, including any zeros appended to the bytestring.
  71. func (d *state) xorIn(buf []byte) {
  72. n := len(buf) / 8
  73. for i := 0; i < n; i++ {
  74. a := binary.LittleEndian.Uint64(buf)
  75. d.a[i] ^= a
  76. buf = buf[8:]
  77. }
  78. if len(buf) != 0 {
  79. // XOR in the last partial ulint64.
  80. a := uint64(0)
  81. for i, v := range buf {
  82. a |= uint64(v) << uint64(8*i)
  83. }
  84. d.a[n] ^= a
  85. }
  86. }
  87. // copyOut copies ulint64s to a byte buffer.
  88. func (d *state) copyOut(b []byte) {
  89. for i := 0; len(b) >= 8; i++ {
  90. binary.LittleEndian.PutUint64(b, d.a[i])
  91. b = b[8:]
  92. }
  93. }
  94. // permute applies the KeccakF-1600 permutation. It handles
  95. // any input-output buffering.
  96. func (d *state) permute() {
  97. switch d.state {
  98. case spongeAbsorbing:
  99. // If we're absorbing, we need to xor the input into the state
  100. // before applying the permutation.
  101. d.xorIn(d.buf)
  102. d.buf = d.storage[:0]
  103. keccakF1600(&d.a)
  104. case spongeSqueezing:
  105. // If we're squeezing, we need to apply the permutatin before
  106. // copying more output.
  107. keccakF1600(&d.a)
  108. d.buf = d.storage[:d.rate]
  109. d.copyOut(d.buf)
  110. }
  111. }
  112. // pads appends the domain separation bits in dsbyte, applies
  113. // the multi-bitrate 10..1 padding rule, and permutes the state.
  114. func (d *state) padAndPermute(dsbyte byte) {
  115. if d.buf == nil {
  116. d.buf = d.storage[:0]
  117. }
  118. // Pad with this instance's domain-separator bits. We know that there's
  119. // at least one byte of space in d.buf because, if it were full,
  120. // permute would have been called to empty it. dsbyte also contains the
  121. // first one bit for the padding. See the comment in the state struct.
  122. d.buf = append(d.buf, dsbyte)
  123. zerosStart := len(d.buf)
  124. d.buf = d.storage[:d.rate]
  125. for i := zerosStart; i < d.rate; i++ {
  126. d.buf[i] = 0
  127. }
  128. // This adds the final one bit for the padding. Because of the way that
  129. // bits are numbered from the LSB upwards, the final bit is the MSB of
  130. // the last byte.
  131. d.buf[d.rate-1] ^= 0x80
  132. // Apply the permutation
  133. d.permute()
  134. d.state = spongeSqueezing
  135. d.buf = d.storage[:d.rate]
  136. d.copyOut(d.buf)
  137. }
  138. // Write absorbs more data into the hash's state. It produces an error
  139. // if more data is written to the ShakeHash after writing
  140. func (d *state) Write(p []byte) (written int, err error) {
  141. if d.state != spongeAbsorbing {
  142. panic("sha3: write to sponge after read")
  143. }
  144. if d.buf == nil {
  145. d.buf = d.storage[:0]
  146. }
  147. written = len(p)
  148. for len(p) > 0 {
  149. if len(d.buf) == 0 && len(p) >= d.rate {
  150. // The fast path; absorb a full "rate" bytes of input and apply the permutation.
  151. d.xorIn(p[:d.rate])
  152. p = p[d.rate:]
  153. keccakF1600(&d.a)
  154. } else {
  155. // The slow path; buffer the input until we can fill the sponge, and then xor it in.
  156. todo := d.rate - len(d.buf)
  157. if todo > len(p) {
  158. todo = len(p)
  159. }
  160. d.buf = append(d.buf, p[:todo]...)
  161. p = p[todo:]
  162. // If the sponge is full, apply the permutation.
  163. if len(d.buf) == d.rate {
  164. d.permute()
  165. }
  166. }
  167. }
  168. return
  169. }
  170. // Read squeezes an arbitrary number of bytes from the sponge.
  171. func (d *state) Read(out []byte) (n int, err error) {
  172. // If we're still absorbing, pad and apply the permutation.
  173. if d.state == spongeAbsorbing {
  174. d.padAndPermute(d.dsbyte)
  175. }
  176. n = len(out)
  177. // Now, do the squeezing.
  178. for len(out) > 0 {
  179. n := copy(out, d.buf)
  180. d.buf = d.buf[n:]
  181. out = out[n:]
  182. // Apply the permutation if we've squeezed the sponge dry.
  183. if len(d.buf) == 0 {
  184. d.permute()
  185. }
  186. }
  187. return
  188. }
  189. // Sum applies padding to the hash state and then squeezes out the desired
  190. // number of output bytes.
  191. func (d *state) Sum(in []byte) []byte {
  192. // Make a copy of the original hash so that caller can keep writing
  193. // and summing.
  194. dup := d.clone()
  195. hash := make([]byte, dup.outputLen)
  196. dup.Read(hash)
  197. return append(in, hash...)
  198. }