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