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