You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

224 lines
9.1 KiB

  1. // Copyright 2013 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 implements the SHA3 hash algorithm (formerly called Keccak) chosen by NIST in 2012.
  5. // This file provides a SHA3 implementation which implements the standard hash.Hash interface.
  6. // Writing input data, including padding, and reading output data are computed in this file.
  7. // Note that the current implementation can compute the hash of an integral number of bytes only.
  8. // This is a consequence of the hash interface in which a buffer of bytes is passed in.
  9. // The internals of the Keccak-f function are computed in keccakf.go.
  10. // For the detailed specification, refer to the Keccak web site (http://keccak.noekeon.org/).
  11. package sha3
  12. import (
  13. "encoding/binary"
  14. "hash"
  15. )
  16. // laneSize is the size in bytes of each "lane" of the internal state of SHA3 (5 * 5 * 8).
  17. // Note that changing this size would requires using a type other than uint64 to store each lane.
  18. const laneSize = 8
  19. // sliceSize represents the dimensions of the internal state, a square matrix of
  20. // sliceSize ** 2 lanes. This is the size of both the "rows" and "columns" dimensions in the
  21. // terminology of the SHA3 specification.
  22. const sliceSize = 5
  23. // numLanes represents the total number of lanes in the state.
  24. const numLanes = sliceSize * sliceSize
  25. // stateSize is the size in bytes of the internal state of SHA3 (5 * 5 * WSize).
  26. const stateSize = laneSize * numLanes
  27. // digest represents the partial evaluation of a checksum.
  28. // Note that capacity, and not outputSize, is the critical security parameter, as SHA3 can output
  29. // an arbitrary number of bytes for any given capacity. The Keccak proposal recommends that
  30. // capacity = 2*outputSize to ensure that finding a collision of size outputSize requires
  31. // O(2^{outputSize/2}) computations (the birthday lower bound). Future standards may modify the
  32. // capacity/outputSize ratio to allow for more output with lower cryptographic security.
  33. type digest struct {
  34. a [numLanes]uint64 // main state of the hash
  35. b [numLanes]uint64 // intermediate states
  36. c [sliceSize]uint64 // intermediate states
  37. d [sliceSize]uint64 // intermediate states
  38. outputSize int // desired output size in bytes
  39. capacity int // number of bytes to leave untouched during squeeze/absorb
  40. absorbed int // number of bytes absorbed thus far
  41. }
  42. // minInt returns the lesser of two integer arguments, to simplify the absorption routine.
  43. func minInt(v1, v2 int) int {
  44. if v1 <= v2 {
  45. return v1
  46. }
  47. return v2
  48. }
  49. // rate returns the number of bytes of the internal state which can be absorbed or squeezed
  50. // in between calls to the permutation function.
  51. func (d *digest) rate() int {
  52. return stateSize - d.capacity
  53. }
  54. // Reset clears the internal state by zeroing bytes in the state buffer.
  55. // This can be skipped for a newly-created hash state; the default zero-allocated state is correct.
  56. func (d *digest) Reset() {
  57. d.absorbed = 0
  58. for i := range d.a {
  59. d.a[i] = 0
  60. }
  61. }
  62. // BlockSize, required by the hash.Hash interface, does not have a standard intepretation
  63. // for a sponge-based construction like SHA3. We return the data rate: the number of bytes which
  64. // can be absorbed per invocation of the permutation function. For Merkle-Damgård based hashes
  65. // (ie SHA1, SHA2, MD5) the output size of the internal compression function is returned.
  66. // We consider this to be roughly equivalent because it represents the number of bytes of output
  67. // produced per cryptographic operation.
  68. func (d *digest) BlockSize() int { return d.rate() }
  69. // Size returns the output size of the hash function in bytes.
  70. func (d *digest) Size() int {
  71. return d.outputSize
  72. }
  73. // unalignedAbsorb is a helper function for Write, which absorbs data that isn't aligned with an
  74. // 8-byte lane. This requires shifting the individual bytes into position in a uint64.
  75. func (d *digest) unalignedAbsorb(p []byte) {
  76. var t uint64
  77. for i := len(p) - 1; i >= 0; i-- {
  78. t <<= 8
  79. t |= uint64(p[i])
  80. }
  81. offset := (d.absorbed) % d.rate()
  82. t <<= 8 * uint(offset%laneSize)
  83. d.a[offset/laneSize] ^= t
  84. d.absorbed += len(p)
  85. }
  86. // Write "absorbs" bytes into the state of the SHA3 hash, updating as needed when the sponge
  87. // "fills up" with rate() bytes. Since lanes are stored internally as type uint64, this requires
  88. // converting the incoming bytes into uint64s using a little endian interpretation. This
  89. // implementation is optimized for large, aligned writes of multiples of 8 bytes (laneSize).
  90. // Non-aligned or uneven numbers of bytes require shifting and are slower.
  91. func (d *digest) Write(p []byte) (int, error) {
  92. // An initial offset is needed if the we aren't absorbing to the first lane initially.
  93. offset := d.absorbed % d.rate()
  94. toWrite := len(p)
  95. // The first lane may need to absorb unaligned and/or incomplete data.
  96. if (offset%laneSize != 0 || len(p) < 8) && len(p) > 0 {
  97. toAbsorb := minInt(laneSize-(offset%laneSize), len(p))
  98. d.unalignedAbsorb(p[:toAbsorb])
  99. p = p[toAbsorb:]
  100. offset = (d.absorbed) % d.rate()
  101. // For every rate() bytes absorbed, the state must be permuted via the F Function.
  102. if (d.absorbed)%d.rate() == 0 {
  103. d.keccakF()
  104. }
  105. }
  106. // This loop should absorb the bulk of the data into full, aligned lanes.
  107. // It will call the update function as necessary.
  108. for len(p) > 7 {
  109. firstLane := offset / laneSize
  110. lastLane := minInt(d.rate()/laneSize, firstLane+len(p)/laneSize)
  111. // This inner loop absorbs input bytes into the state in groups of 8, converted to uint64s.
  112. for lane := firstLane; lane < lastLane; lane++ {
  113. d.a[lane] ^= binary.LittleEndian.Uint64(p[:laneSize])
  114. p = p[laneSize:]
  115. }
  116. d.absorbed += (lastLane - firstLane) * laneSize
  117. // For every rate() bytes absorbed, the state must be permuted via the F Function.
  118. if (d.absorbed)%d.rate() == 0 {
  119. d.keccakF()
  120. }
  121. offset = 0
  122. }
  123. // If there are insufficient bytes to fill the final lane, an unaligned absorption.
  124. // This should always start at a correct lane boundary though, or else it would be caught
  125. // by the uneven opening lane case above.
  126. if len(p) > 0 {
  127. d.unalignedAbsorb(p)
  128. }
  129. return toWrite, nil
  130. }
  131. // pad computes the SHA3 padding scheme based on the number of bytes absorbed.
  132. // The padding is a 1 bit, followed by an arbitrary number of 0s and then a final 1 bit, such that
  133. // the input bits plus padding bits are a multiple of rate(). Adding the padding simply requires
  134. // xoring an opening and closing bit into the appropriate lanes.
  135. func (d *digest) pad() {
  136. offset := d.absorbed % d.rate()
  137. // The opening pad bit must be shifted into position based on the number of bytes absorbed
  138. padOpenLane := offset / laneSize
  139. d.a[padOpenLane] ^= 0x0000000000000001 << uint(8*(offset%laneSize))
  140. // The closing padding bit is always in the last position
  141. padCloseLane := (d.rate() / laneSize) - 1
  142. d.a[padCloseLane] ^= 0x8000000000000000
  143. }
  144. // finalize prepares the hash to output data by padding and one final permutation of the state.
  145. func (d *digest) finalize() {
  146. d.pad()
  147. d.keccakF()
  148. }
  149. // squeeze outputs an arbitrary number of bytes from the hash state.
  150. // Squeezing can require multiple calls to the F function (one per rate() bytes squeezed),
  151. // although this is not the case for standard SHA3 parameters. This implementation only supports
  152. // squeezing a single time, subsequent squeezes may lose alignment. Future implementations
  153. // may wish to support multiple squeeze calls, for example to support use as a PRNG.
  154. func (d *digest) squeeze(in []byte, toSqueeze int) []byte {
  155. // Because we read in blocks of laneSize, we need enough room to read
  156. // an integral number of lanes
  157. needed := toSqueeze + (laneSize-toSqueeze%laneSize)%laneSize
  158. if cap(in)-len(in) < needed {
  159. newIn := make([]byte, len(in), len(in)+needed)
  160. copy(newIn, in)
  161. in = newIn
  162. }
  163. out := in[len(in) : len(in)+needed]
  164. for len(out) > 0 {
  165. for i := 0; i < d.rate() && len(out) > 0; i += laneSize {
  166. binary.LittleEndian.PutUint64(out[:], d.a[i/laneSize])
  167. out = out[laneSize:]
  168. }
  169. if len(out) > 0 {
  170. d.keccakF()
  171. }
  172. }
  173. return in[:len(in)+toSqueeze] // Re-slice in case we wrote extra data.
  174. }
  175. // Sum applies padding to the hash state and then squeezes out the desired nubmer of output bytes.
  176. func (d *digest) Sum(in []byte) []byte {
  177. // Make a copy of the original hash so that caller can keep writing and summing.
  178. dup := *d
  179. dup.finalize()
  180. return dup.squeeze(in, dup.outputSize)
  181. }
  182. // The NewKeccakX constructors enable initializing a hash in any of the four recommend sizes
  183. // from the Keccak specification, all of which set capacity=2*outputSize. Note that the final
  184. // NIST standard for SHA3 may specify different input/output lengths.
  185. // The output size is indicated in bits but converted into bytes internally.
  186. func NewKeccak224() hash.Hash { return &digest{outputSize: 224 / 8, capacity: 2 * 224 / 8} }
  187. func NewKeccak256() hash.Hash { return &digest{outputSize: 256 / 8, capacity: 2 * 256 / 8} }
  188. func NewKeccak384() hash.Hash { return &digest{outputSize: 384 / 8, capacity: 2 * 384 / 8} }
  189. func NewKeccak512() hash.Hash { return &digest{outputSize: 512 / 8, capacity: 2 * 512 / 8} }
  190. func Sha3(data ...[]byte) []byte {
  191. d := NewKeccak256()
  192. for _, b := range data {
  193. d.Write(b)
  194. }
  195. return d.Sum(nil)
  196. }