github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/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  	ret, out := sliceForAppend(dst, len(plaintext)+gcmTagSize)
   139  
   140  	var counter, tagMask [gcmBlockSize]byte
   141  	g.deriveCounter(&counter, nonce)
   142  
   143  	g.cipher.Encrypt(tagMask[:], counter[:])
   144  	gcmInc32(&counter)
   145  
   146  	g.counterCrypt(out, plaintext, &counter)
   147  	g.auth(out[len(plaintext):], out[:len(plaintext)], data, &tagMask)
   148  
   149  	return ret
   150  }
   151  
   152  var errOpen = errors.New("cipher: message authentication failed")
   153  
   154  func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
   155  	if len(nonce) != g.nonceSize {
   156  		panic("cipher: incorrect nonce length given to GCM")
   157  	}
   158  
   159  	if len(ciphertext) < gcmTagSize {
   160  		return nil, errOpen
   161  	}
   162  	tag := ciphertext[len(ciphertext)-gcmTagSize:]
   163  	ciphertext = ciphertext[:len(ciphertext)-gcmTagSize]
   164  
   165  	var counter, tagMask [gcmBlockSize]byte
   166  	g.deriveCounter(&counter, nonce)
   167  
   168  	g.cipher.Encrypt(tagMask[:], counter[:])
   169  	gcmInc32(&counter)
   170  
   171  	var expectedTag [gcmTagSize]byte
   172  	g.auth(expectedTag[:], ciphertext, data, &tagMask)
   173  
   174  	ret, out := sliceForAppend(dst, len(ciphertext))
   175  
   176  	if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 {
   177  		// The AESNI code decrypts and authenticates concurrently, and
   178  		// so overwrites dst in the event of a tag mismatch. That
   179  		// behaviour is mimicked here in order to be consistent across
   180  		// platforms.
   181  		for i := range out {
   182  			out[i] = 0
   183  		}
   184  		return nil, errOpen
   185  	}
   186  
   187  	g.counterCrypt(out, ciphertext, &counter)
   188  
   189  	return ret, nil
   190  }
   191  
   192  // reverseBits reverses the order of the bits of 4-bit number in i.
   193  func reverseBits(i int) int {
   194  	i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
   195  	i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
   196  	return i
   197  }
   198  
   199  // gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
   200  func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
   201  	// Addition in a characteristic 2 field is just XOR.
   202  	return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
   203  }
   204  
   205  // gcmDouble returns the result of doubling an element of GF(2¹²⁸).
   206  func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
   207  	msbSet := x.high&1 == 1
   208  
   209  	// Because of the bit-ordering, doubling is actually a right shift.
   210  	double.high = x.high >> 1
   211  	double.high |= x.low << 63
   212  	double.low = x.low >> 1
   213  
   214  	// If the most-significant bit was set before shifting then it,
   215  	// conceptually, becomes a term of x^128. This is greater than the
   216  	// irreducible polynomial so the result has to be reduced. The
   217  	// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
   218  	// eliminate the term at x^128 which also means subtracting the other
   219  	// four terms. In characteristic 2 fields, subtraction == addition ==
   220  	// XOR.
   221  	if msbSet {
   222  		double.low ^= 0xe100000000000000
   223  	}
   224  
   225  	return
   226  }
   227  
   228  var gcmReductionTable = []uint16{
   229  	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
   230  	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
   231  }
   232  
   233  // mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize.
   234  func (g *gcm) mul(y *gcmFieldElement) {
   235  	var z gcmFieldElement
   236  
   237  	for i := 0; i < 2; i++ {
   238  		word := y.high
   239  		if i == 1 {
   240  			word = y.low
   241  		}
   242  
   243  		// Multiplication works by multiplying z by 16 and adding in
   244  		// one of the precomputed multiples of H.
   245  		for j := 0; j < 64; j += 4 {
   246  			msw := z.high & 0xf
   247  			z.high >>= 4
   248  			z.high |= z.low << 60
   249  			z.low >>= 4
   250  			z.low ^= uint64(gcmReductionTable[msw]) << 48
   251  
   252  			// the values in |table| are ordered for
   253  			// little-endian bit positions. See the comment
   254  			// in NewGCMWithNonceSize.
   255  			t := &g.productTable[word&0xf]
   256  
   257  			z.low ^= t.low
   258  			z.high ^= t.high
   259  			word >>= 4
   260  		}
   261  	}
   262  
   263  	*y = z
   264  }
   265  
   266  // updateBlocks extends y with more polynomial terms from blocks, based on
   267  // Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
   268  func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
   269  	for len(blocks) > 0 {
   270  		y.low ^= getUint64(blocks)
   271  		y.high ^= getUint64(blocks[8:])
   272  		g.mul(y)
   273  		blocks = blocks[gcmBlockSize:]
   274  	}
   275  }
   276  
   277  // update extends y with more polynomial terms from data. If data is not a
   278  // multiple of gcmBlockSize bytes long then the remainder is zero padded.
   279  func (g *gcm) update(y *gcmFieldElement, data []byte) {
   280  	fullBlocks := (len(data) >> 4) << 4
   281  	g.updateBlocks(y, data[:fullBlocks])
   282  
   283  	if len(data) != fullBlocks {
   284  		var partialBlock [gcmBlockSize]byte
   285  		copy(partialBlock[:], data[fullBlocks:])
   286  		g.updateBlocks(y, partialBlock[:])
   287  	}
   288  }
   289  
   290  // gcmInc32 treats the final four bytes of counterBlock as a big-endian value
   291  // and increments it.
   292  func gcmInc32(counterBlock *[16]byte) {
   293  	for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- {
   294  		counterBlock[i]++
   295  		if counterBlock[i] != 0 {
   296  			break
   297  		}
   298  	}
   299  }
   300  
   301  // sliceForAppend takes a slice and a requested number of bytes. It returns a
   302  // slice with the contents of the given slice followed by that many bytes and a
   303  // second slice that aliases into it and contains only the extra bytes. If the
   304  // original slice has sufficient capacity then no allocation is performed.
   305  func sliceForAppend(in []byte, n int) (head, tail []byte) {
   306  	if total := len(in) + n; cap(in) >= total {
   307  		head = in[:total]
   308  	} else {
   309  		head = make([]byte, total)
   310  		copy(head, in)
   311  	}
   312  	tail = head[len(in):]
   313  	return
   314  }
   315  
   316  // counterCrypt crypts in to out using g.cipher in counter mode.
   317  func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
   318  	var mask [gcmBlockSize]byte
   319  
   320  	for len(in) >= gcmBlockSize {
   321  		g.cipher.Encrypt(mask[:], counter[:])
   322  		gcmInc32(counter)
   323  
   324  		xorWords(out, in, mask[:])
   325  		out = out[gcmBlockSize:]
   326  		in = in[gcmBlockSize:]
   327  	}
   328  
   329  	if len(in) > 0 {
   330  		g.cipher.Encrypt(mask[:], counter[:])
   331  		gcmInc32(counter)
   332  		xorBytes(out, in, mask[:])
   333  	}
   334  }
   335  
   336  // deriveCounter computes the initial GCM counter state from the given nonce.
   337  // See NIST SP 800-38D, section 7.1. This assumes that counter is filled with
   338  // zeros on entry.
   339  func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) {
   340  	// GCM has two modes of operation with respect to the initial counter
   341  	// state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path"
   342  	// for nonces of other lengths. For a 96-bit nonce, the nonce, along
   343  	// with a four-byte big-endian counter starting at one, is used
   344  	// directly as the starting counter. For other nonce sizes, the counter
   345  	// is computed by passing it through the GHASH function.
   346  	if len(nonce) == gcmStandardNonceSize {
   347  		copy(counter[:], nonce)
   348  		counter[gcmBlockSize-1] = 1
   349  	} else {
   350  		var y gcmFieldElement
   351  		g.update(&y, nonce)
   352  		y.high ^= uint64(len(nonce)) * 8
   353  		g.mul(&y)
   354  		putUint64(counter[:8], y.low)
   355  		putUint64(counter[8:], y.high)
   356  	}
   357  }
   358  
   359  // auth calculates GHASH(ciphertext, additionalData), masks the result with
   360  // tagMask and writes the result to out.
   361  func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
   362  	var y gcmFieldElement
   363  	g.update(&y, additionalData)
   364  	g.update(&y, ciphertext)
   365  
   366  	y.low ^= uint64(len(additionalData)) * 8
   367  	y.high ^= uint64(len(ciphertext)) * 8
   368  
   369  	g.mul(&y)
   370  
   371  	putUint64(out, y.low)
   372  	putUint64(out[8:], y.high)
   373  
   374  	xorWords(out, out, tagMask[:])
   375  }
   376  
   377  func getUint64(data []byte) uint64 {
   378  	r := uint64(data[0])<<56 |
   379  		uint64(data[1])<<48 |
   380  		uint64(data[2])<<40 |
   381  		uint64(data[3])<<32 |
   382  		uint64(data[4])<<24 |
   383  		uint64(data[5])<<16 |
   384  		uint64(data[6])<<8 |
   385  		uint64(data[7])
   386  	return r
   387  }
   388  
   389  func putUint64(out []byte, v uint64) {
   390  	out[0] = byte(v >> 56)
   391  	out[1] = byte(v >> 48)
   392  	out[2] = byte(v >> 40)
   393  	out[3] = byte(v >> 32)
   394  	out[4] = byte(v >> 24)
   395  	out[5] = byte(v >> 16)
   396  	out[6] = byte(v >> 8)
   397  	out[7] = byte(v)
   398  }