github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/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 must overlap 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 must overlap 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(nonceSize, tagSize 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 tagSize int 71 // productTable contains the first sixteen powers of the key, H. 72 // However, they are in bit reversed order. See NewGCMWithNonceSize. 73 productTable [16]gcmFieldElement 74 } 75 76 // NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode 77 // with the standard nonce length. 78 // 79 // In general, the GHASH operation performed by this implementation of GCM is not constant-time. 80 // An exception is when the underlying Block was created by aes.NewCipher 81 // on systems with hardware support for AES. See the crypto/aes package documentation for details. 82 func NewGCM(cipher Block) (AEAD, error) { 83 return NewGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagSize) 84 } 85 86 // NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois 87 // Counter Mode, which accepts nonces of the given length. 88 // 89 // Only use this function if you require compatibility with an existing 90 // cryptosystem that uses non-standard nonce lengths. All other users should use 91 // NewGCM, which is faster and more resistant to misuse. 92 func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error) { 93 return NewGCMWithNonceAndTagSize(cipher, size, gcmTagSize) 94 } 95 96 // NewGCMWithNonceAndTagSize returns the given 128-bit, block cipher wrapped in Galois 97 // Counter Mode, which accepts nonces of the given length and generates tags with the given length. 98 // 99 // Tag sizes between 12 and 16 bytes are allowed. 100 // 101 // Only use this function if you require compatibility with an existing 102 // cryptosystem that uses non-standard tag lengths. All other users should use 103 // NewGCM, which is more resistant to misuse. 104 func NewGCMWithNonceAndTagSize(cipher Block, nonceSize, tagSize int) (AEAD, error) { 105 if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize { 106 return nil, errors.New("cipher: incorrect tag size given to GCM") 107 } 108 109 if cipher, ok := cipher.(gcmAble); ok { 110 return cipher.NewGCM(nonceSize, tagSize) 111 } 112 113 if cipher.BlockSize() != gcmBlockSize { 114 return nil, errors.New("cipher: NewGCM requires 128-bit block cipher") 115 } 116 117 var key [gcmBlockSize]byte 118 cipher.Encrypt(key[:], key[:]) 119 120 g := &gcm{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize} 121 122 // We precompute 16 multiples of |key|. However, when we do lookups 123 // into this table we'll be using bits from a field element and 124 // therefore the bits will be in the reverse order. So normally one 125 // would expect, say, 4*key to be in index 4 of the table but due to 126 // this bit ordering it will actually be in index 0010 (base 2) = 2. 127 x := gcmFieldElement{ 128 getUint64(key[:8]), 129 getUint64(key[8:]), 130 } 131 g.productTable[reverseBits(1)] = x 132 133 for i := 2; i < 16; i += 2 { 134 g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)]) 135 g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x) 136 } 137 138 return g, nil 139 } 140 141 const ( 142 gcmBlockSize = 16 143 gcmTagSize = 16 144 gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes. 145 gcmStandardNonceSize = 12 146 ) 147 148 func (g *gcm) NonceSize() int { 149 return g.nonceSize 150 } 151 152 func (g *gcm) Overhead() int { 153 return g.tagSize 154 } 155 156 func (g *gcm) Seal(dst, nonce, plaintext, data []byte) []byte { 157 if len(nonce) != g.nonceSize { 158 panic("cipher: incorrect nonce length given to GCM") 159 } 160 if uint64(len(plaintext)) > ((1<<32)-2)*uint64(g.cipher.BlockSize()) { 161 panic("cipher: message too large for GCM") 162 } 163 164 ret, out := sliceForAppend(dst, len(plaintext)+g.tagSize) 165 166 var counter, tagMask [gcmBlockSize]byte 167 g.deriveCounter(&counter, nonce) 168 169 g.cipher.Encrypt(tagMask[:], counter[:]) 170 gcmInc32(&counter) 171 172 g.counterCrypt(out, plaintext, &counter) 173 174 var tag [gcmTagSize]byte 175 g.auth(tag[:], out[:len(plaintext)], data, &tagMask) 176 copy(out[len(plaintext):], tag[:]) 177 178 return ret 179 } 180 181 var errOpen = errors.New("cipher: message authentication failed") 182 183 func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { 184 if len(nonce) != g.nonceSize { 185 panic("cipher: incorrect nonce length given to GCM") 186 } 187 // Sanity check to prevent the authentication from always succeeding if an implementation 188 // leaves tagSize uninitialized, for example. 189 if g.tagSize < gcmMinimumTagSize { 190 panic("cipher: incorrect GCM tag size") 191 } 192 193 if len(ciphertext) < g.tagSize { 194 return nil, errOpen 195 } 196 if uint64(len(ciphertext)) > ((1<<32)-2)*uint64(g.cipher.BlockSize())+uint64(g.tagSize) { 197 return nil, errOpen 198 } 199 200 tag := ciphertext[len(ciphertext)-g.tagSize:] 201 ciphertext = ciphertext[:len(ciphertext)-g.tagSize] 202 203 var counter, tagMask [gcmBlockSize]byte 204 g.deriveCounter(&counter, nonce) 205 206 g.cipher.Encrypt(tagMask[:], counter[:]) 207 gcmInc32(&counter) 208 209 var expectedTag [gcmTagSize]byte 210 g.auth(expectedTag[:], ciphertext, data, &tagMask) 211 212 ret, out := sliceForAppend(dst, len(ciphertext)) 213 214 if subtle.ConstantTimeCompare(expectedTag[:g.tagSize], tag) != 1 { 215 // The AESNI code decrypts and authenticates concurrently, and 216 // so overwrites dst in the event of a tag mismatch. That 217 // behavior is mimicked here in order to be consistent across 218 // platforms. 219 for i := range out { 220 out[i] = 0 221 } 222 return nil, errOpen 223 } 224 225 g.counterCrypt(out, ciphertext, &counter) 226 227 return ret, nil 228 } 229 230 // reverseBits reverses the order of the bits of 4-bit number in i. 231 func reverseBits(i int) int { 232 i = ((i << 2) & 0xc) | ((i >> 2) & 0x3) 233 i = ((i << 1) & 0xa) | ((i >> 1) & 0x5) 234 return i 235 } 236 237 // gcmAdd adds two elements of GF(2¹²⁸) and returns the sum. 238 func gcmAdd(x, y *gcmFieldElement) gcmFieldElement { 239 // Addition in a characteristic 2 field is just XOR. 240 return gcmFieldElement{x.low ^ y.low, x.high ^ y.high} 241 } 242 243 // gcmDouble returns the result of doubling an element of GF(2¹²⁸). 244 func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) { 245 msbSet := x.high&1 == 1 246 247 // Because of the bit-ordering, doubling is actually a right shift. 248 double.high = x.high >> 1 249 double.high |= x.low << 63 250 double.low = x.low >> 1 251 252 // If the most-significant bit was set before shifting then it, 253 // conceptually, becomes a term of x^128. This is greater than the 254 // irreducible polynomial so the result has to be reduced. The 255 // irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to 256 // eliminate the term at x^128 which also means subtracting the other 257 // four terms. In characteristic 2 fields, subtraction == addition == 258 // XOR. 259 if msbSet { 260 double.low ^= 0xe100000000000000 261 } 262 263 return 264 } 265 266 var gcmReductionTable = []uint16{ 267 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0, 268 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0, 269 } 270 271 // mul sets y to y*H, where H is the GCM key, fixed during NewGCMWithNonceSize. 272 func (g *gcm) mul(y *gcmFieldElement) { 273 var z gcmFieldElement 274 275 for i := 0; i < 2; i++ { 276 word := y.high 277 if i == 1 { 278 word = y.low 279 } 280 281 // Multiplication works by multiplying z by 16 and adding in 282 // one of the precomputed multiples of H. 283 for j := 0; j < 64; j += 4 { 284 msw := z.high & 0xf 285 z.high >>= 4 286 z.high |= z.low << 60 287 z.low >>= 4 288 z.low ^= uint64(gcmReductionTable[msw]) << 48 289 290 // the values in |table| are ordered for 291 // little-endian bit positions. See the comment 292 // in NewGCMWithNonceSize. 293 t := &g.productTable[word&0xf] 294 295 z.low ^= t.low 296 z.high ^= t.high 297 word >>= 4 298 } 299 } 300 301 *y = z 302 } 303 304 // updateBlocks extends y with more polynomial terms from blocks, based on 305 // Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks. 306 func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) { 307 for len(blocks) > 0 { 308 y.low ^= getUint64(blocks) 309 y.high ^= getUint64(blocks[8:]) 310 g.mul(y) 311 blocks = blocks[gcmBlockSize:] 312 } 313 } 314 315 // update extends y with more polynomial terms from data. If data is not a 316 // multiple of gcmBlockSize bytes long then the remainder is zero padded. 317 func (g *gcm) update(y *gcmFieldElement, data []byte) { 318 fullBlocks := (len(data) >> 4) << 4 319 g.updateBlocks(y, data[:fullBlocks]) 320 321 if len(data) != fullBlocks { 322 var partialBlock [gcmBlockSize]byte 323 copy(partialBlock[:], data[fullBlocks:]) 324 g.updateBlocks(y, partialBlock[:]) 325 } 326 } 327 328 // gcmInc32 treats the final four bytes of counterBlock as a big-endian value 329 // and increments it. 330 func gcmInc32(counterBlock *[16]byte) { 331 for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- { 332 counterBlock[i]++ 333 if counterBlock[i] != 0 { 334 break 335 } 336 } 337 } 338 339 // sliceForAppend takes a slice and a requested number of bytes. It returns a 340 // slice with the contents of the given slice followed by that many bytes and a 341 // second slice that aliases into it and contains only the extra bytes. If the 342 // original slice has sufficient capacity then no allocation is performed. 343 func sliceForAppend(in []byte, n int) (head, tail []byte) { 344 if total := len(in) + n; cap(in) >= total { 345 head = in[:total] 346 } else { 347 head = make([]byte, total) 348 copy(head, in) 349 } 350 tail = head[len(in):] 351 return 352 } 353 354 // counterCrypt crypts in to out using g.cipher in counter mode. 355 func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) { 356 var mask [gcmBlockSize]byte 357 358 for len(in) >= gcmBlockSize { 359 g.cipher.Encrypt(mask[:], counter[:]) 360 gcmInc32(counter) 361 362 xorWords(out, in, mask[:]) 363 out = out[gcmBlockSize:] 364 in = in[gcmBlockSize:] 365 } 366 367 if len(in) > 0 { 368 g.cipher.Encrypt(mask[:], counter[:]) 369 gcmInc32(counter) 370 xorBytes(out, in, mask[:]) 371 } 372 } 373 374 // deriveCounter computes the initial GCM counter state from the given nonce. 375 // See NIST SP 800-38D, section 7.1. This assumes that counter is filled with 376 // zeros on entry. 377 func (g *gcm) deriveCounter(counter *[gcmBlockSize]byte, nonce []byte) { 378 // GCM has two modes of operation with respect to the initial counter 379 // state: a "fast path" for 96-bit (12-byte) nonces, and a "slow path" 380 // for nonces of other lengths. For a 96-bit nonce, the nonce, along 381 // with a four-byte big-endian counter starting at one, is used 382 // directly as the starting counter. For other nonce sizes, the counter 383 // is computed by passing it through the GHASH function. 384 if len(nonce) == gcmStandardNonceSize { 385 copy(counter[:], nonce) 386 counter[gcmBlockSize-1] = 1 387 } else { 388 var y gcmFieldElement 389 g.update(&y, nonce) 390 y.high ^= uint64(len(nonce)) * 8 391 g.mul(&y) 392 putUint64(counter[:8], y.low) 393 putUint64(counter[8:], y.high) 394 } 395 } 396 397 // auth calculates GHASH(ciphertext, additionalData), masks the result with 398 // tagMask and writes the result to out. 399 func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) { 400 var y gcmFieldElement 401 g.update(&y, additionalData) 402 g.update(&y, ciphertext) 403 404 y.low ^= uint64(len(additionalData)) * 8 405 y.high ^= uint64(len(ciphertext)) * 8 406 407 g.mul(&y) 408 409 putUint64(out, y.low) 410 putUint64(out[8:], y.high) 411 412 xorWords(out, out, tagMask[:]) 413 } 414 415 func getUint64(data []byte) uint64 { 416 r := uint64(data[0])<<56 | 417 uint64(data[1])<<48 | 418 uint64(data[2])<<40 | 419 uint64(data[3])<<32 | 420 uint64(data[4])<<24 | 421 uint64(data[5])<<16 | 422 uint64(data[6])<<8 | 423 uint64(data[7]) 424 return r 425 } 426 427 func putUint64(out []byte, v uint64) { 428 out[0] = byte(v >> 56) 429 out[1] = byte(v >> 48) 430 out[2] = byte(v >> 40) 431 out[3] = byte(v >> 32) 432 out[4] = byte(v >> 24) 433 out[5] = byte(v >> 16) 434 out[6] = byte(v >> 8) 435 out[7] = byte(v) 436 }