github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/crypto/cipher/gcm.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 cipher
     6  
     7  import (
     8  	"crypto/subtle"
     9  	"errors"
    10  )
    11  
    12  // AEAD is a cipher mode providing authenticated encryption with associated
    13  // data. For a description of the methodology, see
    14  //	https://en.wikipedia.org/wiki/Authenticated_encryption
    15  type AEAD interface {
    16  	// NonceSize returns the size of the nonce that must be passed to Seal
    17  	// and Open.
    18  	NonceSize() int
    19  
    20  	// Overhead returns the maximum difference between the lengths of a
    21  	// plaintext and its ciphertext.
    22  	Overhead() int
    23  
    24  	// Seal encrypts and authenticates plaintext, authenticates the
    25  	// additional data and appends the result to dst, returning the updated
    26  	// slice. The nonce must be NonceSize() bytes long and unique for all
    27  	// time, for a given key.
    28  	//
    29  	// The plaintext and dst may alias exactly or not at all. To reuse
    30  	// plaintext's storage for the encrypted output, use plaintext[:0] as dst.
    31  	Seal(dst, nonce, plaintext, additionalData []byte) []byte
    32  
    33  	// Open decrypts and authenticates ciphertext, authenticates the
    34  	// additional data and, if successful, appends the resulting plaintext
    35  	// to dst, returning the updated slice. The nonce must be NonceSize()
    36  	// bytes long and both it and the additional data must match the
    37  	// value passed to Seal.
    38  	//
    39  	// The ciphertext and dst may alias exactly or not at all. To reuse
    40  	// ciphertext's storage for the decrypted output, use ciphertext[:0] as dst.
    41  	//
    42  	// Even if the function fails, the contents of dst, up to its capacity,
    43  	// may be overwritten.
    44  	Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
    45  }
    46  
    47  // gcmAble is an interface implemented by ciphers that have a specific optimized
    48  // implementation of GCM, like crypto/aes. NewGCM will check for this interface
    49  // and return the specific AEAD if found.
    50  type gcmAble interface {
    51  	NewGCM(int) (AEAD, error)
    52  }
    53  
    54  // gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
    55  // standard and make getUint64 suitable for marshaling these values, the bits
    56  // are stored backwards. For example:
    57  //   the coefficient of x⁰ can be obtained by v.low >> 63.
    58  //   the coefficient of x⁶³ can be obtained by v.low & 1.
    59  //   the coefficient of x⁶⁴ can be obtained by v.high >> 63.
    60  //   the coefficient of x¹²⁷ can be obtained by v.high & 1.
    61  type gcmFieldElement struct {
    62  	low, high uint64
    63  }
    64  
    65  // gcm represents a Galois Counter Mode with a specific key. See
    66  // http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
    67  type gcm struct {
    68  	cipher    Block
    69  	nonceSize int
    70  	// productTable contains the first sixteen powers of the key, H.
    71  	// However, they are in bit reversed order. See NewGCMWithNonceSize.
    72  	productTable [16]gcmFieldElement
    73  }
    74  
    75  // NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
    76  // with the standard nonce length.
    77  func NewGCM(cipher Block) (AEAD, error) {
    78  	return NewGCMWithNonceSize(cipher, gcmStandardNonceSize)
    79  }
    80  
    81  // NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
    82  // Counter Mode, which accepts nonces of the given length.
    83  //
    84  // Only use this function if you require compatibility with an existing
    85  // cryptosystem that uses non-standard nonce lengths. All other users should use
    86  // NewGCM, which is faster and more resistant to misuse.
    87  func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error) {
    88  	if cipher, ok := cipher.(gcmAble); ok {
    89  		return cipher.NewGCM(size)
    90  	}
    91  
    92  	if cipher.BlockSize() != gcmBlockSize {
    93  		return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
    94  	}
    95  
    96  	var key [gcmBlockSize]byte
    97  	cipher.Encrypt(key[:], key[:])
    98  
    99  	g := &gcm{cipher: cipher, nonceSize: size}
   100  
   101  	// We precompute 16 multiples of |key|. However, when we do lookups
   102  	// into this table we'll be using bits from a field element and
   103  	// therefore the bits will be in the reverse order. So normally one
   104  	// would expect, say, 4*key to be in index 4 of the table but due to
   105  	// this bit ordering it will actually be in index 0010 (base 2) = 2.
   106  	x := gcmFieldElement{
   107  		getUint64(key[:8]),
   108  		getUint64(key[8:]),
   109  	}
   110  	g.productTable[reverseBits(1)] = x
   111  
   112  	for i := 2; i < 16; i += 2 {
   113  		g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
   114  		g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
   115  	}
   116  
   117  	return g, nil
   118  }
   119  
   120  const (
   121  	gcmBlockSize         = 16
   122  	gcmTagSize           = 16
   123  	gcmStandardNonceSize = 12
   124  )
   125  
   126  func (g *gcm) NonceSize() int {
   127  	return g.nonceSize
   128  }
   129  
   130  func (*gcm) Overhead() int {
   131  	return gcmTagSize
   132  }
   133  
   134  func (g *gcm) Seal(dst, nonce, plaintext, data []byte) []byte {
   135  	if len(nonce) != g.nonceSize {
   136  		panic("cipher: incorrect nonce length given to GCM")
   137  	}
   138  	if uint64(len(plaintext)) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) {
   139  		panic("cipher: message too large for GCM")
   140  	}
   141  
   142  	ret, out := sliceForAppend(dst, len(plaintext)+gcmTagSize)
   143  
   144  	var counter, tagMask [gcmBlockSize]byte
   145  	g.deriveCounter(&counter, nonce)
   146  
   147  	g.cipher.Encrypt(tagMask[:], counter[:])
   148  	gcmInc32(&counter)
   149  
   150  	g.counterCrypt(out, plaintext, &counter)
   151  	g.auth(out[len(plaintext):], out[:len(plaintext)], data, &tagMask)
   152  
   153  	return ret
   154  }
   155  
   156  var errOpen = errors.New("cipher: message authentication failed")
   157  
   158  func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
   159  	if len(nonce) != g.nonceSize {
   160  		panic("cipher: incorrect nonce length given to GCM")
   161  	}
   162  
   163  	if len(ciphertext) < gcmTagSize {
   164  		return nil, errOpen
   165  	}
   166  	if uint64(len(ciphertext)) > ((1<<32)-2)*uint64(g.cipher.BlockSize())+gcmTagSize {
   167  		return nil, errOpen
   168  	}
   169  
   170  	tag := ciphertext[len(ciphertext)-gcmTagSize:]
   171  	ciphertext = ciphertext[:len(ciphertext)-gcmTagSize]
   172  
   173  	var counter, tagMask [gcmBlockSize]byte
   174  	g.deriveCounter(&counter, nonce)
   175  
   176  	g.cipher.Encrypt(tagMask[:], counter[:])
   177  	gcmInc32(&counter)
   178  
   179  	var expectedTag [gcmTagSize]byte
   180  	g.auth(expectedTag[:], ciphertext, data, &tagMask)
   181  
   182  	ret, out := sliceForAppend(dst, len(ciphertext))
   183  
   184  	if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 {
   185  		// The AESNI code decrypts and authenticates concurrently, and
   186  		// so overwrites dst in the event of a tag mismatch. That
   187  		// behaviour is mimicked here in order to be consistent across
   188  		// platforms.
   189  		for i := range out {
   190  			out[i] = 0
   191  		}
   192  		return nil, errOpen
   193  	}
   194  
   195  	g.counterCrypt(out, ciphertext, &counter)
   196  
   197  	return ret, nil
   198  }
   199  
   200  // reverseBits reverses the order of the bits of 4-bit number in i.
   201  func reverseBits(i int) int {
   202  	i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
   203  	i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
   204  	return i
   205  }
   206  
   207  // gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
   208  func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
   209  	// Addition in a characteristic 2 field is just XOR.
   210  	return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
   211  }
   212  
   213  // gcmDouble returns the result of doubling an element of GF(2¹²⁸).
   214  func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
   215  	msbSet := x.high&1 == 1
   216  
   217  	// Because of the bit-ordering, doubling is actually a right shift.
   218  	double.high = x.high >> 1
   219  	double.high |= x.low << 63
   220  	double.low = x.low >> 1
   221  
   222  	// If the most-significant bit was set before shifting then it,
   223  	// conceptually, becomes a term of x^128. This is greater than the
   224  	// irreducible polynomial so the result has to be reduced. The
   225  	// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
   226  	// eliminate the term at x^128 which also means subtracting the other
   227  	// four terms. In characteristic 2 fields, subtraction == addition ==
   228  	// XOR.
   229  	if msbSet {
   230  		double.low ^= 0xe100000000000000
   231  	}
   232  
   233  	return
   234  }
   235  
   236  var gcmReductionTable = []uint16{
   237  	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
   238  	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
   239  }
   240  
   241  // mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
   242  func (g *gcm) mul(y *gcmFieldElement) {
   243  	var z gcmFieldElement
   244  
   245  	for i := 0; i < 2; i++ {
   246  		word := y.high
   247  		if i == 1 {
   248  			word = y.low
   249  		}
   250  
   251  		// Multiplication works by multiplying z by 16 and adding in
   252  		// one of the precomputed multiples of H.
   253  		for j := 0; j < 64; j += 4 {
   254  			msw := z.high & 0xf
   255  			z.high >>= 4
   256  			z.high |= z.low << 60
   257  			z.low >>= 4
   258  			z.low ^= uint64(gcmReductionTable[msw]) << 48
   259  
   260  			// the values in |table| are ordered for
   261  			// little-endian bit positions. See the comment
   262  			// in NewGCMWithNonceSize.
   263  			t := &g.productTable[word&0xf]
   264  
   265  			z.low ^= t.low
   266  			z.high ^= t.high
   267  			word >>= 4
   268  		}
   269  	}
   270  
   271  	*y = z
   272  }
   273  
   274  // updateBlocks extends y with more polynomial terms from blocks, based on
   275  // Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
   276  func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
   277  	for len(blocks) > 0 {
   278  		y.low ^= getUint64(blocks)
   279  		y.high ^= getUint64(blocks[8:])
   280  		g.mul(y)
   281  		blocks = blocks[gcmBlockSize:]
   282  	}
   283  }
   284  
   285  // update extends y with more polynomial terms from data. If data is not a
   286  // multiple of gcmBlockSize bytes long then the remainder is zero padded.
   287  func (g *gcm) update(y *gcmFieldElement, data []byte) {
   288  	fullBlocks := (len(data) >> 4) << 4
   289  	g.updateBlocks(y, data[:fullBlocks])
   290  
   291  	if len(data) != fullBlocks {
   292  		var partialBlock [gcmBlockSize]byte
   293  		copy(partialBlock[:], data[fullBlocks:])
   294  		g.updateBlocks(y, partialBlock[:])
   295  	}
   296  }
   297  
   298  // gcmInc32 treats the final four bytes of counterBlock as a big-endian value
   299  // and increments it.
   300  func gcmInc32(counterBlock *[16]byte) {
   301  	for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- {
   302  		counterBlock[i]++
   303  		if counterBlock[i] != 0 {
   304  			break
   305  		}
   306  	}
   307  }
   308  
   309  // sliceForAppend takes a slice and a requested number of bytes. It returns a
   310  // slice with the contents of the given slice followed by that many bytes and a
   311  // second slice that aliases into it and contains only the extra bytes. If the
   312  // original slice has sufficient capacity then no allocation is performed.
   313  func sliceForAppend(in []byte, n int) (head, tail []byte) {
   314  	if total := len(in) + n; cap(in) >= total {
   315  		head = in[:total]
   316  	} else {
   317  		head = make([]byte, total)
   318  		copy(head, in)
   319  	}
   320  	tail = head[len(in):]
   321  	return
   322  }
   323  
   324  // counterCrypt crypts in to out using g.cipher in counter mode.
   325  func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
   326  	var mask [gcmBlockSize]byte
   327  
   328  	for len(in) >= gcmBlockSize {
   329  		g.cipher.Encrypt(mask[:], counter[:])
   330  		gcmInc32(counter)
   331  
   332  		xorWords(out, in, mask[:])
   333  		out = out[gcmBlockSize:]
   334  		in = in[gcmBlockSize:]
   335  	}
   336  
   337  	if len(in) > 0 {
   338  		g.cipher.Encrypt(mask[:], counter[:])
   339  		gcmInc32(counter)
   340  		xorBytes(out, in, mask[:])
   341  	}
   342  }
   343  
   344  // deriveCounter computes the initial GCM counter state from the given nonce.
   345  // See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
   346  // zeros on entry.
   347  func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
   348  	// GCM has two modes of operation with respect to the initial counter
   349  	// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
   350  	// for nonces of other lengths. For a 96-bit nonce, the nonce, along
   351  	// with a four-byte big-endian counter starting at one, is used
   352  	// directly as the starting counter. For other nonce sizes, the counter
   353  	// is computed by passing it through the GHASH function.
   354  	if len(nonce) == gcmStandardNonceSize {
   355  		copy(counter[:], nonce)
   356  		counter[gcmBlockSize-1] = 1
   357  	} else {
   358  		var y gcmFieldElement
   359  		g.update(&y, nonce)
   360  		y.high ^= uint64(len(nonce)) * 8
   361  		g.mul(&y)
   362  		putUint64(counter[:8], y.low)
   363  		putUint64(counter[8:], y.high)
   364  	}
   365  }
   366  
   367  // auth calculates GHASH(ciphertext, additionalData), masks the result with
   368  // tagMask and writes the result to out.
   369  func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
   370  	var y gcmFieldElement
   371  	g.update(&y, additionalData)
   372  	g.update(&y, ciphertext)
   373  
   374  	y.low ^= uint64(len(additionalData)) * 8
   375  	y.high ^= uint64(len(ciphertext)) * 8
   376  
   377  	g.mul(&y)
   378  
   379  	putUint64(out, y.low)
   380  	putUint64(out[8:], y.high)
   381  
   382  	xorWords(out, out, tagMask[:])
   383  }
   384  
   385  func getUint64(data []byte) uint64 {
   386  	r := uint64(data[0])<<56 |
   387  		uint64(data[1])<<48 |
   388  		uint64(data[2])<<40 |
   389  		uint64(data[3])<<32 |
   390  		uint64(data[4])<<24 |
   391  		uint64(data[5])<<16 |
   392  		uint64(data[6])<<8 |
   393  		uint64(data[7])
   394  	return r
   395  }
   396  
   397  func putUint64(out []byte, v uint64) {
   398  	out[0] = byte(v >> 56)
   399  	out[1] = byte(v >> 48)
   400  	out[2] = byte(v >> 40)
   401  	out[3] = byte(v >> 32)
   402  	out[4] = byte(v >> 24)
   403  	out[5] = byte(v >> 16)
   404  	out[6] = byte(v >> 8)
   405  	out[7] = byte(v)
   406  }