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