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

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

View as plain text