Source file
src/crypto/cipher/gcm_fips140v2.0_test.go
1
2
3
4
5
6
7 package cipher_test
8
9 import (
10 "crypto/cipher"
11 "crypto/internal/fips140"
12 fipsaes "crypto/internal/fips140/aes"
13 "crypto/internal/fips140/aes/gcm"
14 "encoding/binary"
15 "math"
16 "testing"
17 )
18
19 func TestGCMNoncesFIPSV2(t *testing.T) {
20 tryNonce := func(aead cipher.AEAD, nonce []byte) bool {
21 fips140.ResetServiceIndicator()
22 aead.Seal(nil, nonce, []byte("x"), nil)
23 return fips140.ServiceIndicator()
24 }
25 expectOK := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
26 t.Helper()
27 if !tryNonce(aead, nonce) {
28 t.Errorf("expected service indicator true for %x", nonce)
29 }
30 }
31 expectPanic := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
32 t.Helper()
33 defer func() {
34 t.Helper()
35 if recover() == nil {
36 t.Errorf("expected panic for %x", nonce)
37 }
38 }()
39 tryNonce(aead, nonce)
40 }
41
42 t.Run("NewGCMWithXORCounterNonce", func(t *testing.T) {
43 newGCM := func() *gcm.GCMWithXORCounterNonce {
44 key := make([]byte, 16)
45 block, _ := fipsaes.New(key)
46 aead, _ := gcm.NewGCMWithXORCounterNonce(block)
47 return aead
48 }
49 nonce := func(mask []byte, counter uint64) []byte {
50 nonce := make([]byte, 12)
51 copy(nonce, mask)
52 n := binary.BigEndian.AppendUint64(nil, counter)
53 for i, b := range n {
54 nonce[4+i] ^= b
55 }
56 return nonce
57 }
58
59 for _, mask := range [][]byte{
60 decodeHex(t, "ffffffffffffffffffffffff"),
61 decodeHex(t, "aabbccddeeff001122334455"),
62 decodeHex(t, "000000000000000000000000"),
63 } {
64 g := newGCM()
65
66 expectOK(t, g, nonce(mask, 0))
67 expectOK(t, g, nonce(mask, 1))
68 expectOK(t, g, nonce(mask, 100))
69 expectPanic(t, g, nonce(mask, 100))
70 expectPanic(t, g, nonce(mask, 99))
71 expectOK(t, g, nonce(mask, math.MaxUint64-2))
72 expectOK(t, g, nonce(mask, math.MaxUint64-1))
73 expectPanic(t, g, nonce(mask, math.MaxUint64))
74 expectPanic(t, g, nonce(mask, 0))
75
76 g = newGCM()
77 g.SetNoncePrefixAndMask(mask)
78 expectOK(t, g, nonce(mask, 0xFFFFFFFF))
79 expectOK(t, g, nonce(mask, math.MaxUint64-2))
80 expectOK(t, g, nonce(mask, math.MaxUint64-1))
81 expectPanic(t, g, nonce(mask, math.MaxUint64))
82 expectPanic(t, g, nonce(mask, 0))
83
84 g = newGCM()
85 g.SetNoncePrefixAndMask(mask)
86 expectOK(t, g, nonce(mask, math.MaxUint64-1))
87 expectPanic(t, g, nonce(mask, math.MaxUint64))
88 expectPanic(t, g, nonce(mask, 0))
89 }
90 })
91 }
92
View as plain text