codekingpro commited on
Commit
4bcc2be
·
verified ·
1 Parent(s): f7a7bb1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. go/src/crypto/aes/aes.go +48 -0
  2. go/src/crypto/aes/aes_test.go +175 -0
  3. go/src/crypto/boring/boring.go +21 -0
  4. go/src/crypto/boring/boring_test.go +22 -0
  5. go/src/crypto/boring/notboring_test.go +13 -0
  6. go/src/crypto/cipher/benchmark_test.go +130 -0
  7. go/src/crypto/cipher/cbc.go +207 -0
  8. go/src/crypto/cipher/cbc_aes_test.go +113 -0
  9. go/src/crypto/cipher/cbc_test.go +68 -0
  10. go/src/crypto/cipher/cfb.go +102 -0
  11. go/src/crypto/cipher/cfb_test.go +160 -0
  12. go/src/crypto/cipher/cipher.go +98 -0
  13. go/src/crypto/cipher/common_test.go +28 -0
  14. go/src/crypto/cipher/ctr.go +115 -0
  15. go/src/crypto/cipher/ctr_aes_test.go +363 -0
  16. go/src/crypto/cipher/ctr_test.go +100 -0
  17. go/src/crypto/cipher/example_test.go +363 -0
  18. go/src/crypto/cipher/fuzz_test.go +103 -0
  19. go/src/crypto/cipher/gcm.go +377 -0
  20. go/src/crypto/cipher/gcm_fips140v1.26_test.go +105 -0
  21. go/src/crypto/cipher/gcm_test.go +909 -0
  22. go/src/crypto/cipher/io.go +53 -0
  23. go/src/crypto/cipher/modes_test.go +126 -0
  24. go/src/crypto/cipher/ofb.go +88 -0
  25. go/src/crypto/cipher/ofb_test.go +139 -0
  26. go/src/crypto/des/block.go +249 -0
  27. go/src/crypto/des/cipher.go +165 -0
  28. go/src/crypto/des/const.go +142 -0
  29. go/src/crypto/des/des_test.go +1575 -0
  30. go/src/crypto/des/example_test.go +25 -0
  31. go/src/crypto/des/internal_test.go +29 -0
  32. go/src/crypto/dsa/dsa.go +330 -0
  33. go/src/crypto/dsa/dsa_test.go +144 -0
  34. go/src/crypto/ecdh/ecdh.go +174 -0
  35. go/src/crypto/ecdh/ecdh_test.go +527 -0
  36. go/src/crypto/ecdh/nist.go +227 -0
  37. go/src/crypto/ecdh/x25519.go +150 -0
  38. go/src/crypto/ecdsa/boring.go +106 -0
  39. go/src/crypto/ecdsa/ecdsa.go +632 -0
  40. go/src/crypto/ecdsa/ecdsa_legacy.go +220 -0
  41. go/src/crypto/ecdsa/ecdsa_test.go +778 -0
  42. go/src/crypto/ecdsa/equal_test.go +75 -0
  43. go/src/crypto/ecdsa/example_test.go +32 -0
  44. go/src/crypto/ecdsa/notboring.go +16 -0
  45. go/src/crypto/ed25519/ed25519.go +257 -0
  46. go/src/crypto/ed25519/ed25519_test.go +427 -0
  47. go/src/crypto/ed25519/ed25519vectors_test.go +94 -0
  48. go/src/crypto/elliptic/elliptic.go +280 -0
  49. go/src/crypto/elliptic/elliptic_test.go +413 -0
  50. go/src/crypto/elliptic/nistec.go +270 -0
go/src/crypto/aes/aes.go ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 aes implements AES encryption (formerly Rijndael), as defined in
6
+ // U.S. Federal Information Processing Standards Publication 197.
7
+ //
8
+ // The AES operations in this package are not implemented using constant-time algorithms.
9
+ // An exception is when running on systems with enabled hardware support for AES
10
+ // that makes these operations constant-time. Examples include amd64 systems using AES-NI
11
+ // extensions and s390x systems using Message-Security-Assist extensions.
12
+ // On such systems, when the result of NewCipher is passed to cipher.NewGCM,
13
+ // the GHASH operation used by GCM is also constant-time.
14
+ package aes
15
+
16
+ import (
17
+ "crypto/cipher"
18
+ "crypto/internal/boring"
19
+ "crypto/internal/fips140/aes"
20
+ "strconv"
21
+ )
22
+
23
+ // The AES block size in bytes.
24
+ const BlockSize = 16
25
+
26
+ type KeySizeError int
27
+
28
+ func (k KeySizeError) Error() string {
29
+ return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
30
+ }
31
+
32
+ // NewCipher creates and returns a new [cipher.Block].
33
+ // The key argument must be the AES key,
34
+ // either 16, 24, or 32 bytes to select
35
+ // AES-128, AES-192, or AES-256.
36
+ func NewCipher(key []byte) (cipher.Block, error) {
37
+ k := len(key)
38
+ switch k {
39
+ default:
40
+ return nil, KeySizeError(k)
41
+ case 16, 24, 32:
42
+ break
43
+ }
44
+ if boring.Enabled {
45
+ return boring.NewAESCipher(key)
46
+ }
47
+ return aes.New(key)
48
+ }
go/src/crypto/aes/aes_test.go ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 aes
6
+
7
+ import (
8
+ "crypto/internal/boring"
9
+ "crypto/internal/cryptotest"
10
+ "fmt"
11
+ "testing"
12
+ )
13
+
14
+ // Test vectors are from FIPS 197:
15
+ // https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
16
+
17
+ // Appendix B, C of FIPS 197: Cipher examples, Example vectors.
18
+ type CryptTest struct {
19
+ key []byte
20
+ in []byte
21
+ out []byte
22
+ }
23
+
24
+ var encryptTests = []CryptTest{
25
+ {
26
+ // Appendix B.
27
+ []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c},
28
+ []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34},
29
+ []byte{0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32},
30
+ },
31
+ {
32
+ // Appendix C.1. AES-128
33
+ []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
34
+ []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
35
+ []byte{0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a},
36
+ },
37
+ {
38
+ // Appendix C.2. AES-192
39
+ []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
40
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
41
+ },
42
+ []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
43
+ []byte{0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91},
44
+ },
45
+ {
46
+ // Appendix C.3. AES-256
47
+ []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
48
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
49
+ },
50
+ []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
51
+ []byte{0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89},
52
+ },
53
+ }
54
+
55
+ // Test Cipher Encrypt method against FIPS 197 examples.
56
+ func TestCipherEncrypt(t *testing.T) {
57
+ cryptotest.TestAllImplementations(t, "aes", testCipherEncrypt)
58
+ }
59
+
60
+ func testCipherEncrypt(t *testing.T) {
61
+ for i, tt := range encryptTests {
62
+ c, err := NewCipher(tt.key)
63
+ if err != nil {
64
+ t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err)
65
+ continue
66
+ }
67
+ out := make([]byte, len(tt.in))
68
+ c.Encrypt(out, tt.in)
69
+ for j, v := range out {
70
+ if v != tt.out[j] {
71
+ t.Errorf("Cipher.Encrypt %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j])
72
+ break
73
+ }
74
+ }
75
+ }
76
+ }
77
+
78
+ // Test Cipher Decrypt against FIPS 197 examples.
79
+ func TestCipherDecrypt(t *testing.T) {
80
+ cryptotest.TestAllImplementations(t, "aes", testCipherDecrypt)
81
+ }
82
+
83
+ func testCipherDecrypt(t *testing.T) {
84
+ for i, tt := range encryptTests {
85
+ c, err := NewCipher(tt.key)
86
+ if err != nil {
87
+ t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err)
88
+ continue
89
+ }
90
+ plain := make([]byte, len(tt.in))
91
+ c.Decrypt(plain, tt.out)
92
+ for j, v := range plain {
93
+ if v != tt.in[j] {
94
+ t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j])
95
+ break
96
+ }
97
+ }
98
+ }
99
+ }
100
+
101
+ // Test AES against the general cipher.Block interface tester
102
+ func TestAESBlock(t *testing.T) {
103
+ cryptotest.TestAllImplementations(t, "aes", testAESBlock)
104
+ }
105
+
106
+ func testAESBlock(t *testing.T) {
107
+ for _, keylen := range []int{128, 192, 256} {
108
+ t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
109
+ cryptotest.TestBlock(t, keylen/8, NewCipher)
110
+ })
111
+ }
112
+ }
113
+
114
+ func TestExtraMethods(t *testing.T) {
115
+ if boring.Enabled {
116
+ t.Skip("Go+BoringCrypto still uses the interface upgrades in crypto/cipher")
117
+ }
118
+ cryptotest.TestAllImplementations(t, "aes", func(t *testing.T) {
119
+ b, _ := NewCipher(make([]byte, 16))
120
+ cryptotest.NoExtraMethods(t, &b)
121
+ })
122
+ }
123
+
124
+ func BenchmarkEncrypt(b *testing.B) {
125
+ b.Run("AES-128", func(b *testing.B) { benchmarkEncrypt(b, encryptTests[1]) })
126
+ b.Run("AES-192", func(b *testing.B) { benchmarkEncrypt(b, encryptTests[2]) })
127
+ b.Run("AES-256", func(b *testing.B) { benchmarkEncrypt(b, encryptTests[3]) })
128
+ }
129
+
130
+ func benchmarkEncrypt(b *testing.B, tt CryptTest) {
131
+ c, err := NewCipher(tt.key)
132
+ if err != nil {
133
+ b.Fatal("NewCipher:", err)
134
+ }
135
+ out := make([]byte, len(tt.in))
136
+ b.SetBytes(int64(len(out)))
137
+ b.ResetTimer()
138
+ for i := 0; i < b.N; i++ {
139
+ c.Encrypt(out, tt.in)
140
+ }
141
+ }
142
+
143
+ func BenchmarkDecrypt(b *testing.B) {
144
+ b.Run("AES-128", func(b *testing.B) { benchmarkDecrypt(b, encryptTests[1]) })
145
+ b.Run("AES-192", func(b *testing.B) { benchmarkDecrypt(b, encryptTests[2]) })
146
+ b.Run("AES-256", func(b *testing.B) { benchmarkDecrypt(b, encryptTests[3]) })
147
+ }
148
+
149
+ func benchmarkDecrypt(b *testing.B, tt CryptTest) {
150
+ c, err := NewCipher(tt.key)
151
+ if err != nil {
152
+ b.Fatal("NewCipher:", err)
153
+ }
154
+ out := make([]byte, len(tt.out))
155
+ b.SetBytes(int64(len(out)))
156
+ b.ResetTimer()
157
+ for i := 0; i < b.N; i++ {
158
+ c.Decrypt(out, tt.out)
159
+ }
160
+ }
161
+
162
+ func BenchmarkCreateCipher(b *testing.B) {
163
+ b.Run("AES-128", func(b *testing.B) { benchmarkCreateCipher(b, encryptTests[1]) })
164
+ b.Run("AES-192", func(b *testing.B) { benchmarkCreateCipher(b, encryptTests[2]) })
165
+ b.Run("AES-256", func(b *testing.B) { benchmarkCreateCipher(b, encryptTests[3]) })
166
+ }
167
+
168
+ func benchmarkCreateCipher(b *testing.B, tt CryptTest) {
169
+ b.ReportAllocs()
170
+ for i := 0; i < b.N; i++ {
171
+ if _, err := NewCipher(tt.key); err != nil {
172
+ b.Fatal(err)
173
+ }
174
+ }
175
+ }
go/src/crypto/boring/boring.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 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
+ //go:build boringcrypto
6
+
7
+ // Package boring exposes functions that are only available when building with
8
+ // Go+BoringCrypto. This package is available on all targets as long as the
9
+ // Go+BoringCrypto toolchain is used. Use the Enabled function to determine
10
+ // whether the BoringCrypto core is actually in use.
11
+ //
12
+ // Any time the Go+BoringCrypto toolchain is used, the "boringcrypto" build tag
13
+ // is satisfied, so that applications can tag files that use this package.
14
+ package boring
15
+
16
+ import "crypto/internal/boring"
17
+
18
+ // Enabled reports whether BoringCrypto handles supported crypto operations.
19
+ func Enabled() bool {
20
+ return boring.Enabled
21
+ }
go/src/crypto/boring/boring_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 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
+ //go:build boringcrypto
6
+
7
+ package boring_test
8
+
9
+ import (
10
+ "crypto/boring"
11
+ "runtime"
12
+ "testing"
13
+ )
14
+
15
+ func TestEnabled(t *testing.T) {
16
+ supportedPlatform := runtime.GOOS == "linux" && (runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64")
17
+ if supportedPlatform && !boring.Enabled() {
18
+ t.Error("Enabled returned false on a supported platform")
19
+ } else if !supportedPlatform && boring.Enabled() {
20
+ t.Error("Enabled returned true on an unsupported platform")
21
+ }
22
+ }
go/src/crypto/boring/notboring_test.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 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
+ //go:build (goexperiment.boringcrypto && !boringcrypto) || (!goexperiment.boringcrypto && boringcrypto)
6
+
7
+ package boring_test
8
+
9
+ import "testing"
10
+
11
+ func TestNotBoring(t *testing.T) {
12
+ t.Error("goexperiment.boringcrypto and boringcrypto should be equivalent build tags")
13
+ }
go/src/crypto/cipher/benchmark_test.go ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_test
6
+
7
+ import (
8
+ "crypto/aes"
9
+ "crypto/cipher"
10
+ "strconv"
11
+ "testing"
12
+ )
13
+
14
+ func benchmarkAESGCMSeal(b *testing.B, buf []byte, keySize int) {
15
+ b.ReportAllocs()
16
+ b.SetBytes(int64(len(buf)))
17
+
18
+ var key = make([]byte, keySize)
19
+ var nonce [12]byte
20
+ var ad [13]byte
21
+ aes, _ := aes.NewCipher(key[:])
22
+ aesgcm, _ := cipher.NewGCM(aes)
23
+ var out []byte
24
+
25
+ b.ResetTimer()
26
+ for i := 0; i < b.N; i++ {
27
+ out = aesgcm.Seal(out[:0], nonce[:], buf, ad[:])
28
+ }
29
+ }
30
+
31
+ func benchmarkAESGCMOpen(b *testing.B, buf []byte, keySize int) {
32
+ b.ReportAllocs()
33
+ b.SetBytes(int64(len(buf)))
34
+
35
+ var key = make([]byte, keySize)
36
+ var nonce [12]byte
37
+ var ad [13]byte
38
+ aes, _ := aes.NewCipher(key[:])
39
+ aesgcm, _ := cipher.NewGCM(aes)
40
+ var out []byte
41
+
42
+ ct := aesgcm.Seal(nil, nonce[:], buf[:], ad[:])
43
+
44
+ b.ResetTimer()
45
+ for i := 0; i < b.N; i++ {
46
+ out, _ = aesgcm.Open(out[:0], nonce[:], ct, ad[:])
47
+ }
48
+ }
49
+
50
+ func BenchmarkAESGCM(b *testing.B) {
51
+ for _, length := range []int{64, 1350, 8 * 1024} {
52
+ b.Run("Open-128-"+strconv.Itoa(length), func(b *testing.B) {
53
+ benchmarkAESGCMOpen(b, make([]byte, length), 128/8)
54
+ })
55
+ b.Run("Seal-128-"+strconv.Itoa(length), func(b *testing.B) {
56
+ benchmarkAESGCMSeal(b, make([]byte, length), 128/8)
57
+ })
58
+
59
+ b.Run("Open-256-"+strconv.Itoa(length), func(b *testing.B) {
60
+ benchmarkAESGCMOpen(b, make([]byte, length), 256/8)
61
+ })
62
+ b.Run("Seal-256-"+strconv.Itoa(length), func(b *testing.B) {
63
+ benchmarkAESGCMSeal(b, make([]byte, length), 256/8)
64
+ })
65
+ }
66
+ }
67
+
68
+ func benchmarkAESStream(b *testing.B, mode func(cipher.Block, []byte) cipher.Stream, buf []byte, keySize int) {
69
+ b.SetBytes(int64(len(buf)))
70
+
71
+ key := make([]byte, keySize)
72
+ var iv [16]byte
73
+ aes, _ := aes.NewCipher(key)
74
+ stream := mode(aes, iv[:])
75
+
76
+ b.ResetTimer()
77
+ for i := 0; i < b.N; i++ {
78
+ stream.XORKeyStream(buf, buf)
79
+ }
80
+ }
81
+
82
+ // If we test exactly 1K blocks, we would generate exact multiples of
83
+ // the cipher's block size, and the cipher stream fragments would
84
+ // always be wordsize aligned, whereas non-aligned is a more typical
85
+ // use-case.
86
+ const almost1K = 1024 - 5
87
+ const almost8K = 8*1024 - 5
88
+
89
+ func BenchmarkAESCTR(b *testing.B) {
90
+ for _, keyBits := range []int{128, 192, 256} {
91
+ keySize := keyBits / 8
92
+ b.Run(strconv.Itoa(keyBits), func(b *testing.B) {
93
+ b.Run("50", func(b *testing.B) {
94
+ benchmarkAESStream(b, cipher.NewCTR, make([]byte, 50), keySize)
95
+ })
96
+ b.Run("1K", func(b *testing.B) {
97
+ benchmarkAESStream(b, cipher.NewCTR, make([]byte, almost1K), keySize)
98
+ })
99
+ b.Run("8K", func(b *testing.B) {
100
+ benchmarkAESStream(b, cipher.NewCTR, make([]byte, almost8K), keySize)
101
+ })
102
+ })
103
+ }
104
+ }
105
+
106
+ func BenchmarkAESCBCEncrypt1K(b *testing.B) {
107
+ buf := make([]byte, 1024)
108
+ b.SetBytes(int64(len(buf)))
109
+
110
+ var key [16]byte
111
+ var iv [16]byte
112
+ aes, _ := aes.NewCipher(key[:])
113
+ cbc := cipher.NewCBCEncrypter(aes, iv[:])
114
+ for i := 0; i < b.N; i++ {
115
+ cbc.CryptBlocks(buf, buf)
116
+ }
117
+ }
118
+
119
+ func BenchmarkAESCBCDecrypt1K(b *testing.B) {
120
+ buf := make([]byte, 1024)
121
+ b.SetBytes(int64(len(buf)))
122
+
123
+ var key [16]byte
124
+ var iv [16]byte
125
+ aes, _ := aes.NewCipher(key[:])
126
+ cbc := cipher.NewCBCDecrypter(aes, iv[:])
127
+ for i := 0; i < b.N; i++ {
128
+ cbc.CryptBlocks(buf, buf)
129
+ }
130
+ }
go/src/crypto/cipher/cbc.go ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // Cipher block chaining (CBC) mode.
6
+
7
+ // CBC provides confidentiality by xoring (chaining) each plaintext block
8
+ // with the previous ciphertext block before applying the block cipher.
9
+
10
+ // See NIST SP 800-38A, pp 10-11
11
+
12
+ package cipher
13
+
14
+ import (
15
+ "bytes"
16
+ "crypto/internal/fips140/aes"
17
+ "crypto/internal/fips140/alias"
18
+ "crypto/internal/fips140only"
19
+ "crypto/subtle"
20
+ )
21
+
22
+ type cbc struct {
23
+ b Block
24
+ blockSize int
25
+ iv []byte
26
+ tmp []byte
27
+ }
28
+
29
+ func newCBC(b Block, iv []byte) *cbc {
30
+ return &cbc{
31
+ b: b,
32
+ blockSize: b.BlockSize(),
33
+ iv: bytes.Clone(iv),
34
+ tmp: make([]byte, b.BlockSize()),
35
+ }
36
+ }
37
+
38
+ type cbcEncrypter cbc
39
+
40
+ // cbcEncAble is an interface implemented by ciphers that have a specific
41
+ // optimized implementation of CBC encryption. crypto/aes doesn't use this
42
+ // anymore, and we'd like to eventually remove it.
43
+ type cbcEncAble interface {
44
+ NewCBCEncrypter(iv []byte) BlockMode
45
+ }
46
+
47
+ // NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining
48
+ // mode, using the given Block. The length of iv must be the same as the
49
+ // Block's block size.
50
+ func NewCBCEncrypter(b Block, iv []byte) BlockMode {
51
+ if len(iv) != b.BlockSize() {
52
+ panic("cipher.NewCBCEncrypter: IV length must equal block size")
53
+ }
54
+ if b, ok := b.(*aes.Block); ok {
55
+ return aes.NewCBCEncrypter(b, [16]byte(iv))
56
+ }
57
+ if fips140only.Enforced() {
58
+ panic("crypto/cipher: use of CBC with non-AES ciphers is not allowed in FIPS 140-only mode")
59
+ }
60
+ if cbc, ok := b.(cbcEncAble); ok {
61
+ return cbc.NewCBCEncrypter(iv)
62
+ }
63
+ return (*cbcEncrypter)(newCBC(b, iv))
64
+ }
65
+
66
+ // newCBCGenericEncrypter returns a BlockMode which encrypts in cipher block chaining
67
+ // mode, using the given Block. The length of iv must be the same as the
68
+ // Block's block size. This always returns the generic non-asm encrypter for use
69
+ // in fuzz testing.
70
+ func newCBCGenericEncrypter(b Block, iv []byte) BlockMode {
71
+ if len(iv) != b.BlockSize() {
72
+ panic("cipher.NewCBCEncrypter: IV length must equal block size")
73
+ }
74
+ return (*cbcEncrypter)(newCBC(b, iv))
75
+ }
76
+
77
+ func (x *cbcEncrypter) BlockSize() int { return x.blockSize }
78
+
79
+ func (x *cbcEncrypter) CryptBlocks(dst, src []byte) {
80
+ if len(src)%x.blockSize != 0 {
81
+ panic("crypto/cipher: input not full blocks")
82
+ }
83
+ if len(dst) < len(src) {
84
+ panic("crypto/cipher: output smaller than input")
85
+ }
86
+ if alias.InexactOverlap(dst[:len(src)], src) {
87
+ panic("crypto/cipher: invalid buffer overlap")
88
+ }
89
+ if _, ok := x.b.(*aes.Block); ok {
90
+ panic("crypto/cipher: internal error: generic CBC used with AES")
91
+ }
92
+
93
+ iv := x.iv
94
+
95
+ for len(src) > 0 {
96
+ // Write the xor to dst, then encrypt in place.
97
+ subtle.XORBytes(dst[:x.blockSize], src[:x.blockSize], iv)
98
+ x.b.Encrypt(dst[:x.blockSize], dst[:x.blockSize])
99
+
100
+ // Move to the next block with this block as the next iv.
101
+ iv = dst[:x.blockSize]
102
+ src = src[x.blockSize:]
103
+ dst = dst[x.blockSize:]
104
+ }
105
+
106
+ // Save the iv for the next CryptBlocks call.
107
+ copy(x.iv, iv)
108
+ }
109
+
110
+ func (x *cbcEncrypter) SetIV(iv []byte) {
111
+ if len(iv) != len(x.iv) {
112
+ panic("cipher: incorrect length IV")
113
+ }
114
+ copy(x.iv, iv)
115
+ }
116
+
117
+ type cbcDecrypter cbc
118
+
119
+ // cbcDecAble is an interface implemented by ciphers that have a specific
120
+ // optimized implementation of CBC decryption. crypto/aes doesn't use this
121
+ // anymore, and we'd like to eventually remove it.
122
+ type cbcDecAble interface {
123
+ NewCBCDecrypter(iv []byte) BlockMode
124
+ }
125
+
126
+ // NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining
127
+ // mode, using the given Block. The length of iv must be the same as the
128
+ // Block's block size and must match the iv used to encrypt the data.
129
+ func NewCBCDecrypter(b Block, iv []byte) BlockMode {
130
+ if len(iv) != b.BlockSize() {
131
+ panic("cipher.NewCBCDecrypter: IV length must equal block size")
132
+ }
133
+ if b, ok := b.(*aes.Block); ok {
134
+ return aes.NewCBCDecrypter(b, [16]byte(iv))
135
+ }
136
+ if fips140only.Enforced() {
137
+ panic("crypto/cipher: use of CBC with non-AES ciphers is not allowed in FIPS 140-only mode")
138
+ }
139
+ if cbc, ok := b.(cbcDecAble); ok {
140
+ return cbc.NewCBCDecrypter(iv)
141
+ }
142
+ return (*cbcDecrypter)(newCBC(b, iv))
143
+ }
144
+
145
+ // newCBCGenericDecrypter returns a BlockMode which encrypts in cipher block chaining
146
+ // mode, using the given Block. The length of iv must be the same as the
147
+ // Block's block size. This always returns the generic non-asm decrypter for use in
148
+ // fuzz testing.
149
+ func newCBCGenericDecrypter(b Block, iv []byte) BlockMode {
150
+ if len(iv) != b.BlockSize() {
151
+ panic("cipher.NewCBCDecrypter: IV length must equal block size")
152
+ }
153
+ return (*cbcDecrypter)(newCBC(b, iv))
154
+ }
155
+
156
+ func (x *cbcDecrypter) BlockSize() int { return x.blockSize }
157
+
158
+ func (x *cbcDecrypter) CryptBlocks(dst, src []byte) {
159
+ if len(src)%x.blockSize != 0 {
160
+ panic("crypto/cipher: input not full blocks")
161
+ }
162
+ if len(dst) < len(src) {
163
+ panic("crypto/cipher: output smaller than input")
164
+ }
165
+ if alias.InexactOverlap(dst[:len(src)], src) {
166
+ panic("crypto/cipher: invalid buffer overlap")
167
+ }
168
+ if _, ok := x.b.(*aes.Block); ok {
169
+ panic("crypto/cipher: internal error: generic CBC used with AES")
170
+ }
171
+ if len(src) == 0 {
172
+ return
173
+ }
174
+
175
+ // For each block, we need to xor the decrypted data with the previous block's ciphertext (the iv).
176
+ // To avoid making a copy each time, we loop over the blocks BACKWARDS.
177
+ end := len(src)
178
+ start := end - x.blockSize
179
+ prev := start - x.blockSize
180
+
181
+ // Copy the last block of ciphertext in preparation as the new iv.
182
+ copy(x.tmp, src[start:end])
183
+
184
+ // Loop over all but the first block.
185
+ for start > 0 {
186
+ x.b.Decrypt(dst[start:end], src[start:end])
187
+ subtle.XORBytes(dst[start:end], dst[start:end], src[prev:start])
188
+
189
+ end = start
190
+ start = prev
191
+ prev -= x.blockSize
192
+ }
193
+
194
+ // The first block is special because it uses the saved iv.
195
+ x.b.Decrypt(dst[start:end], src[start:end])
196
+ subtle.XORBytes(dst[start:end], dst[start:end], x.iv)
197
+
198
+ // Set the new iv to the first block we copied earlier.
199
+ x.iv, x.tmp = x.tmp, x.iv
200
+ }
201
+
202
+ func (x *cbcDecrypter) SetIV(iv []byte) {
203
+ if len(iv) != len(x.iv) {
204
+ panic("cipher: incorrect length IV")
205
+ }
206
+ copy(x.iv, iv)
207
+ }
go/src/crypto/cipher/cbc_aes_test.go ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // CBC AES test vectors.
6
+
7
+ // See U.S. National Institute of Standards and Technology (NIST)
8
+ // Special Publication 800-38A, ``Recommendation for Block Cipher
9
+ // Modes of Operation,'' 2001 Edition, pp. 24-29.
10
+
11
+ package cipher_test
12
+
13
+ import (
14
+ "bytes"
15
+ "crypto/aes"
16
+ "crypto/cipher"
17
+ "crypto/internal/cryptotest"
18
+ "testing"
19
+ )
20
+
21
+ var cbcAESTests = []struct {
22
+ name string
23
+ key []byte
24
+ iv []byte
25
+ in []byte
26
+ out []byte
27
+ }{
28
+ // NIST SP 800-38A pp 27-29
29
+ {
30
+ "CBC-AES128",
31
+ commonKey128,
32
+ commonIV,
33
+ commonInput,
34
+ []byte{
35
+ 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d,
36
+ 0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2,
37
+ 0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16,
38
+ 0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7,
39
+ },
40
+ },
41
+ {
42
+ "CBC-AES192",
43
+ commonKey192,
44
+ commonIV,
45
+ commonInput,
46
+ []byte{
47
+ 0x4f, 0x02, 0x1d, 0xb2, 0x43, 0xbc, 0x63, 0x3d, 0x71, 0x78, 0x18, 0x3a, 0x9f, 0xa0, 0x71, 0xe8,
48
+ 0xb4, 0xd9, 0xad, 0xa9, 0xad, 0x7d, 0xed, 0xf4, 0xe5, 0xe7, 0x38, 0x76, 0x3f, 0x69, 0x14, 0x5a,
49
+ 0x57, 0x1b, 0x24, 0x20, 0x12, 0xfb, 0x7a, 0xe0, 0x7f, 0xa9, 0xba, 0xac, 0x3d, 0xf1, 0x02, 0xe0,
50
+ 0x08, 0xb0, 0xe2, 0x79, 0x88, 0x59, 0x88, 0x81, 0xd9, 0x20, 0xa9, 0xe6, 0x4f, 0x56, 0x15, 0xcd,
51
+ },
52
+ },
53
+ {
54
+ "CBC-AES256",
55
+ commonKey256,
56
+ commonIV,
57
+ commonInput,
58
+ []byte{
59
+ 0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6,
60
+ 0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d,
61
+ 0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61,
62
+ 0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b,
63
+ },
64
+ },
65
+ }
66
+
67
+ func TestCBCEncrypterAES(t *testing.T) {
68
+ cryptotest.TestAllImplementations(t, "aes", testCBCEncrypterAES)
69
+ }
70
+
71
+ func testCBCEncrypterAES(t *testing.T) {
72
+ for _, test := range cbcAESTests {
73
+ c, err := aes.NewCipher(test.key)
74
+ if err != nil {
75
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test.name, len(test.key), err)
76
+ continue
77
+ }
78
+
79
+ encrypter := cipher.NewCBCEncrypter(c, test.iv)
80
+
81
+ data := make([]byte, len(test.in))
82
+ copy(data, test.in)
83
+
84
+ encrypter.CryptBlocks(data, data)
85
+ if !bytes.Equal(test.out, data) {
86
+ t.Errorf("%s: CBCEncrypter\nhave %x\nwant %x", test.name, data, test.out)
87
+ }
88
+ }
89
+ }
90
+
91
+ func TestCBCDecrypterAES(t *testing.T) {
92
+ cryptotest.TestAllImplementations(t, "aes", testCBCDecrypterAES)
93
+ }
94
+
95
+ func testCBCDecrypterAES(t *testing.T) {
96
+ for _, test := range cbcAESTests {
97
+ c, err := aes.NewCipher(test.key)
98
+ if err != nil {
99
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test.name, len(test.key), err)
100
+ continue
101
+ }
102
+
103
+ decrypter := cipher.NewCBCDecrypter(c, test.iv)
104
+
105
+ data := make([]byte, len(test.out))
106
+ copy(data, test.out)
107
+
108
+ decrypter.CryptBlocks(data, data)
109
+ if !bytes.Equal(test.in, data) {
110
+ t.Errorf("%s: CBCDecrypter\nhave %x\nwant %x", test.name, data, test.in)
111
+ }
112
+ }
113
+ }
go/src/crypto/cipher/cbc_test.go ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 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_test
6
+
7
+ import (
8
+ "crypto/aes"
9
+ "crypto/cipher"
10
+ "crypto/des"
11
+ "crypto/internal/cryptotest"
12
+ "fmt"
13
+ "io"
14
+ "math/rand"
15
+ "testing"
16
+ "time"
17
+ )
18
+
19
+ // Test CBC Blockmode against the general cipher.BlockMode interface tester
20
+ func TestCBCBlockMode(t *testing.T) {
21
+ cryptotest.TestAllImplementations(t, "aes", func(t *testing.T) {
22
+ for _, keylen := range []int{128, 192, 256} {
23
+ t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
24
+ rng := newRandReader(t)
25
+
26
+ key := make([]byte, keylen/8)
27
+ rng.Read(key)
28
+
29
+ block, err := aes.NewCipher(key)
30
+ if err != nil {
31
+ panic(err)
32
+ }
33
+
34
+ cryptotest.TestBlockMode(t, block, cipher.NewCBCEncrypter, cipher.NewCBCDecrypter)
35
+ })
36
+ }
37
+ })
38
+
39
+ t.Run("DES", func(t *testing.T) {
40
+ rng := newRandReader(t)
41
+
42
+ key := make([]byte, 8)
43
+ rng.Read(key)
44
+
45
+ block, err := des.NewCipher(key)
46
+ if err != nil {
47
+ panic(err)
48
+ }
49
+
50
+ cryptotest.TestBlockMode(t, block, cipher.NewCBCEncrypter, cipher.NewCBCDecrypter)
51
+ })
52
+ }
53
+
54
+ func TestCBCExtraMethods(t *testing.T) {
55
+ block, _ := aes.NewCipher(make([]byte, 16))
56
+ iv := make([]byte, block.BlockSize())
57
+ s := cipher.NewCBCEncrypter(block, iv)
58
+ cryptotest.NoExtraMethods(t, &s, "SetIV")
59
+
60
+ s = cipher.NewCBCDecrypter(block, iv)
61
+ cryptotest.NoExtraMethods(t, &s, "SetIV")
62
+ }
63
+
64
+ func newRandReader(t *testing.T) io.Reader {
65
+ seed := time.Now().UnixNano()
66
+ t.Logf("Deterministic RNG seed: 0x%x", seed)
67
+ return rand.New(rand.NewSource(seed))
68
+ }
go/src/crypto/cipher/cfb.go ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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
+ // CFB (Cipher Feedback) Mode.
6
+
7
+ package cipher
8
+
9
+ import (
10
+ "crypto/internal/fips140/alias"
11
+ "crypto/internal/fips140only"
12
+ "crypto/subtle"
13
+ )
14
+
15
+ type cfb struct {
16
+ b Block
17
+ next []byte
18
+ out []byte
19
+ outUsed int
20
+
21
+ decrypt bool
22
+ }
23
+
24
+ func (x *cfb) XORKeyStream(dst, src []byte) {
25
+ if len(dst) < len(src) {
26
+ panic("crypto/cipher: output smaller than input")
27
+ }
28
+ if alias.InexactOverlap(dst[:len(src)], src) {
29
+ panic("crypto/cipher: invalid buffer overlap")
30
+ }
31
+ for len(src) > 0 {
32
+ if x.outUsed == len(x.out) {
33
+ x.b.Encrypt(x.out, x.next)
34
+ x.outUsed = 0
35
+ }
36
+
37
+ if x.decrypt {
38
+ // We can precompute a larger segment of the
39
+ // keystream on decryption. This will allow
40
+ // larger batches for xor, and we should be
41
+ // able to match CTR/OFB performance.
42
+ copy(x.next[x.outUsed:], src)
43
+ }
44
+ n := subtle.XORBytes(dst, src, x.out[x.outUsed:])
45
+ if !x.decrypt {
46
+ copy(x.next[x.outUsed:], dst)
47
+ }
48
+ dst = dst[n:]
49
+ src = src[n:]
50
+ x.outUsed += n
51
+ }
52
+ }
53
+
54
+ // NewCFBEncrypter returns a [Stream] which encrypts with cipher feedback mode,
55
+ // using the given [Block]. The iv must be the same length as the [Block]'s block
56
+ // size.
57
+ //
58
+ // Deprecated: CFB mode is not authenticated, which generally enables active
59
+ // attacks to manipulate and recover the plaintext. It is recommended that
60
+ // applications use [AEAD] modes instead. The standard library implementation of
61
+ // CFB is also unoptimized and not validated as part of the FIPS 140-3 module.
62
+ // If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
63
+ func NewCFBEncrypter(block Block, iv []byte) Stream {
64
+ if fips140only.Enforced() {
65
+ panic("crypto/cipher: use of CFB is not allowed in FIPS 140-only mode")
66
+ }
67
+ return newCFB(block, iv, false)
68
+ }
69
+
70
+ // NewCFBDecrypter returns a [Stream] which decrypts with cipher feedback mode,
71
+ // using the given [Block]. The iv must be the same length as the [Block]'s block
72
+ // size.
73
+ //
74
+ // Deprecated: CFB mode is not authenticated, which generally enables active
75
+ // attacks to manipulate and recover the plaintext. It is recommended that
76
+ // applications use [AEAD] modes instead. The standard library implementation of
77
+ // CFB is also unoptimized and not validated as part of the FIPS 140-3 module.
78
+ // If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
79
+ func NewCFBDecrypter(block Block, iv []byte) Stream {
80
+ if fips140only.Enforced() {
81
+ panic("crypto/cipher: use of CFB is not allowed in FIPS 140-only mode")
82
+ }
83
+ return newCFB(block, iv, true)
84
+ }
85
+
86
+ func newCFB(block Block, iv []byte, decrypt bool) Stream {
87
+ blockSize := block.BlockSize()
88
+ if len(iv) != blockSize {
89
+ // Stack trace will indicate whether it was de- or en-cryption.
90
+ panic("cipher.newCFB: IV length must equal block size")
91
+ }
92
+ x := &cfb{
93
+ b: block,
94
+ out: make([]byte, blockSize),
95
+ next: make([]byte, blockSize),
96
+ outUsed: blockSize,
97
+ decrypt: decrypt,
98
+ }
99
+ copy(x.next, iv)
100
+
101
+ return x
102
+ }
go/src/crypto/cipher/cfb_test.go ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/aes"
10
+ "crypto/cipher"
11
+ "crypto/des"
12
+ "crypto/internal/cryptotest"
13
+ "crypto/rand"
14
+ "encoding/hex"
15
+ "fmt"
16
+ "testing"
17
+ )
18
+
19
+ // cfbTests contains the test vectors from
20
+ // https://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section
21
+ // F.3.13.
22
+ var cfbTests = []struct {
23
+ key, iv, plaintext, ciphertext string
24
+ }{
25
+ {
26
+ "2b7e151628aed2a6abf7158809cf4f3c",
27
+ "000102030405060708090a0b0c0d0e0f",
28
+ "6bc1bee22e409f96e93d7e117393172a",
29
+ "3b3fd92eb72dad20333449f8e83cfb4a",
30
+ },
31
+ {
32
+ "2b7e151628aed2a6abf7158809cf4f3c",
33
+ "3B3FD92EB72DAD20333449F8E83CFB4A",
34
+ "ae2d8a571e03ac9c9eb76fac45af8e51",
35
+ "c8a64537a0b3a93fcde3cdad9f1ce58b",
36
+ },
37
+ {
38
+ "2b7e151628aed2a6abf7158809cf4f3c",
39
+ "C8A64537A0B3A93FCDE3CDAD9F1CE58B",
40
+ "30c81c46a35ce411e5fbc1191a0a52ef",
41
+ "26751f67a3cbb140b1808cf187a4f4df",
42
+ },
43
+ {
44
+ "2b7e151628aed2a6abf7158809cf4f3c",
45
+ "26751F67A3CBB140B1808CF187A4F4DF",
46
+ "f69f2445df4f9b17ad2b417be66c3710",
47
+ "c04b05357c5d1c0eeac4c66f9ff7f2e6",
48
+ },
49
+ }
50
+
51
+ func TestCFBVectors(t *testing.T) {
52
+ for i, test := range cfbTests {
53
+ key, err := hex.DecodeString(test.key)
54
+ if err != nil {
55
+ t.Fatal(err)
56
+ }
57
+ iv, err := hex.DecodeString(test.iv)
58
+ if err != nil {
59
+ t.Fatal(err)
60
+ }
61
+ plaintext, err := hex.DecodeString(test.plaintext)
62
+ if err != nil {
63
+ t.Fatal(err)
64
+ }
65
+ expected, err := hex.DecodeString(test.ciphertext)
66
+ if err != nil {
67
+ t.Fatal(err)
68
+ }
69
+
70
+ block, err := aes.NewCipher(key)
71
+ if err != nil {
72
+ t.Fatal(err)
73
+ }
74
+
75
+ ciphertext := make([]byte, len(plaintext))
76
+ cfb := cipher.NewCFBEncrypter(block, iv)
77
+ cfb.XORKeyStream(ciphertext, plaintext)
78
+
79
+ if !bytes.Equal(ciphertext, expected) {
80
+ t.Errorf("#%d: wrong output: got %x, expected %x", i, ciphertext, expected)
81
+ }
82
+
83
+ cfbdec := cipher.NewCFBDecrypter(block, iv)
84
+ plaintextCopy := make([]byte, len(ciphertext))
85
+ cfbdec.XORKeyStream(plaintextCopy, ciphertext)
86
+
87
+ if !bytes.Equal(plaintextCopy, plaintext) {
88
+ t.Errorf("#%d: wrong plaintext: got %x, expected %x", i, plaintextCopy, plaintext)
89
+ }
90
+ }
91
+ }
92
+
93
+ func TestCFBInverse(t *testing.T) {
94
+ block, err := aes.NewCipher(commonKey128)
95
+ if err != nil {
96
+ t.Error(err)
97
+ return
98
+ }
99
+
100
+ plaintext := []byte("this is the plaintext. this is the plaintext.")
101
+ iv := make([]byte, block.BlockSize())
102
+ rand.Reader.Read(iv)
103
+ cfb := cipher.NewCFBEncrypter(block, iv)
104
+ ciphertext := make([]byte, len(plaintext))
105
+ copy(ciphertext, plaintext)
106
+ cfb.XORKeyStream(ciphertext, ciphertext)
107
+
108
+ cfbdec := cipher.NewCFBDecrypter(block, iv)
109
+ plaintextCopy := make([]byte, len(plaintext))
110
+ copy(plaintextCopy, ciphertext)
111
+ cfbdec.XORKeyStream(plaintextCopy, plaintextCopy)
112
+
113
+ if !bytes.Equal(plaintextCopy, plaintext) {
114
+ t.Errorf("got: %x, want: %x", plaintextCopy, plaintext)
115
+ }
116
+ }
117
+
118
+ func TestCFBStream(t *testing.T) {
119
+
120
+ for _, keylen := range []int{128, 192, 256} {
121
+
122
+ t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
123
+ rng := newRandReader(t)
124
+
125
+ key := make([]byte, keylen/8)
126
+ rng.Read(key)
127
+
128
+ block, err := aes.NewCipher(key)
129
+ if err != nil {
130
+ panic(err)
131
+ }
132
+
133
+ t.Run("Encrypter", func(t *testing.T) {
134
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCFBEncrypter)
135
+ })
136
+ t.Run("Decrypter", func(t *testing.T) {
137
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCFBDecrypter)
138
+ })
139
+ })
140
+ }
141
+
142
+ t.Run("DES", func(t *testing.T) {
143
+ rng := newRandReader(t)
144
+
145
+ key := make([]byte, 8)
146
+ rng.Read(key)
147
+
148
+ block, err := des.NewCipher(key)
149
+ if err != nil {
150
+ panic(err)
151
+ }
152
+
153
+ t.Run("Encrypter", func(t *testing.T) {
154
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCFBEncrypter)
155
+ })
156
+ t.Run("Decrypter", func(t *testing.T) {
157
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCFBDecrypter)
158
+ })
159
+ })
160
+ }
go/src/crypto/cipher/cipher.go ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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 implements standard block cipher modes that can be wrapped
6
+ // around low-level block cipher implementations.
7
+ // See https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html
8
+ // and NIST Special Publication 800-38A.
9
+ package cipher
10
+
11
+ // A Block represents an implementation of block cipher
12
+ // using a given key. It provides the capability to encrypt
13
+ // or decrypt individual blocks. The mode implementations
14
+ // extend that capability to streams of blocks.
15
+ type Block interface {
16
+ // BlockSize returns the cipher's block size.
17
+ BlockSize() int
18
+
19
+ // Encrypt encrypts the first block in src into dst.
20
+ // Dst and src must overlap entirely or not at all.
21
+ Encrypt(dst, src []byte)
22
+
23
+ // Decrypt decrypts the first block in src into dst.
24
+ // Dst and src must overlap entirely or not at all.
25
+ Decrypt(dst, src []byte)
26
+ }
27
+
28
+ // A Stream represents a stream cipher.
29
+ type Stream interface {
30
+ // XORKeyStream XORs each byte in the given slice with a byte from the
31
+ // cipher's key stream. Dst and src must overlap entirely or not at all.
32
+ //
33
+ // If len(dst) < len(src), XORKeyStream should panic. It is acceptable
34
+ // to pass a dst bigger than src, and in that case, XORKeyStream will
35
+ // only update dst[:len(src)] and will not touch the rest of dst.
36
+ //
37
+ // Multiple calls to XORKeyStream behave as if the concatenation of
38
+ // the src buffers was passed in a single run. That is, Stream
39
+ // maintains state and does not reset at each XORKeyStream call.
40
+ XORKeyStream(dst, src []byte)
41
+ }
42
+
43
+ // A BlockMode represents a block cipher running in a block-based mode (CBC,
44
+ // ECB etc).
45
+ type BlockMode interface {
46
+ // BlockSize returns the mode's block size.
47
+ BlockSize() int
48
+
49
+ // CryptBlocks encrypts or decrypts a number of blocks. The length of
50
+ // src must be a multiple of the block size. Dst and src must overlap
51
+ // entirely or not at all.
52
+ //
53
+ // If len(dst) < len(src), CryptBlocks should panic. It is acceptable
54
+ // to pass a dst bigger than src, and in that case, CryptBlocks will
55
+ // only update dst[:len(src)] and will not touch the rest of dst.
56
+ //
57
+ // Multiple calls to CryptBlocks behave as if the concatenation of
58
+ // the src buffers was passed in a single run. That is, BlockMode
59
+ // maintains state and does not reset at each CryptBlocks call.
60
+ CryptBlocks(dst, src []byte)
61
+ }
62
+
63
+ // AEAD is a cipher mode providing authenticated encryption with associated
64
+ // data. For a description of the methodology, see
65
+ // https://en.wikipedia.org/wiki/Authenticated_encryption.
66
+ type AEAD interface {
67
+ // NonceSize returns the size of the nonce that must be passed to Seal
68
+ // and Open.
69
+ NonceSize() int
70
+
71
+ // Overhead returns the maximum difference between the lengths of a
72
+ // plaintext and its ciphertext.
73
+ Overhead() int
74
+
75
+ // Seal encrypts and authenticates plaintext, authenticates the
76
+ // additional data and appends the result to dst, returning the updated
77
+ // slice. The nonce must be NonceSize() bytes long and unique for all
78
+ // time, for a given key.
79
+ //
80
+ // To reuse plaintext's storage for the encrypted output, use plaintext[:0]
81
+ // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
82
+ // dst and additionalData may not overlap.
83
+ Seal(dst, nonce, plaintext, additionalData []byte) []byte
84
+
85
+ // Open decrypts and authenticates ciphertext, authenticates the
86
+ // additional data and, if successful, appends the resulting plaintext
87
+ // to dst, returning the updated slice. The nonce must be NonceSize()
88
+ // bytes long and both it and the additional data must match the
89
+ // value passed to Seal.
90
+ //
91
+ // To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
92
+ // as dst. Otherwise, the remaining capacity of dst must not overlap ciphertext.
93
+ // dst and additionalData may not overlap.
94
+ //
95
+ // Even if the function fails, the contents of dst, up to its capacity,
96
+ // may be overwritten.
97
+ Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
98
+ }
go/src/crypto/cipher/common_test.go ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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_test
6
+
7
+ // Common values for tests.
8
+
9
+ var commonInput = []byte{
10
+ 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
11
+ 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
12
+ 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
13
+ 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10,
14
+ }
15
+
16
+ var commonKey128 = []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}
17
+
18
+ var commonKey192 = []byte{
19
+ 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
20
+ 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b,
21
+ }
22
+
23
+ var commonKey256 = []byte{
24
+ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
25
+ 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4,
26
+ }
27
+
28
+ var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
go/src/crypto/cipher/ctr.go ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // Counter (CTR) mode.
6
+
7
+ // CTR converts a block cipher into a stream cipher by
8
+ // repeatedly encrypting an incrementing counter and
9
+ // xoring the resulting stream of data with the input.
10
+
11
+ // See NIST SP 800-38A, pp 13-15
12
+
13
+ package cipher
14
+
15
+ import (
16
+ "bytes"
17
+ "crypto/internal/fips140/aes"
18
+ "crypto/internal/fips140/alias"
19
+ "crypto/internal/fips140only"
20
+ "crypto/subtle"
21
+ )
22
+
23
+ type ctr struct {
24
+ b Block
25
+ ctr []byte
26
+ out []byte
27
+ outUsed int
28
+ }
29
+
30
+ const streamBufferSize = 512
31
+
32
+ // ctrAble is an interface implemented by ciphers that have a specific optimized
33
+ // implementation of CTR. crypto/aes doesn't use this anymore, and we'd like to
34
+ // eventually remove it.
35
+ type ctrAble interface {
36
+ NewCTR(iv []byte) Stream
37
+ }
38
+
39
+ // NewCTR returns a [Stream] which encrypts/decrypts using the given [Block] in
40
+ // counter mode. The length of iv must be the same as the [Block]'s block size.
41
+ func NewCTR(block Block, iv []byte) Stream {
42
+ if block, ok := block.(*aes.Block); ok {
43
+ return aesCtrWrapper{aes.NewCTR(block, iv)}
44
+ }
45
+ if fips140only.Enforced() {
46
+ panic("crypto/cipher: use of CTR with non-AES ciphers is not allowed in FIPS 140-only mode")
47
+ }
48
+ if ctr, ok := block.(ctrAble); ok {
49
+ return ctr.NewCTR(iv)
50
+ }
51
+ if len(iv) != block.BlockSize() {
52
+ panic("cipher.NewCTR: IV length must equal block size")
53
+ }
54
+ bufSize := streamBufferSize
55
+ if bufSize < block.BlockSize() {
56
+ bufSize = block.BlockSize()
57
+ }
58
+ return &ctr{
59
+ b: block,
60
+ ctr: bytes.Clone(iv),
61
+ out: make([]byte, 0, bufSize),
62
+ outUsed: 0,
63
+ }
64
+ }
65
+
66
+ // aesCtrWrapper hides extra methods from aes.CTR.
67
+ type aesCtrWrapper struct {
68
+ c *aes.CTR
69
+ }
70
+
71
+ func (x aesCtrWrapper) XORKeyStream(dst, src []byte) {
72
+ x.c.XORKeyStream(dst, src)
73
+ }
74
+
75
+ func (x *ctr) refill() {
76
+ remain := len(x.out) - x.outUsed
77
+ copy(x.out, x.out[x.outUsed:])
78
+ x.out = x.out[:cap(x.out)]
79
+ bs := x.b.BlockSize()
80
+ for remain <= len(x.out)-bs {
81
+ x.b.Encrypt(x.out[remain:], x.ctr)
82
+ remain += bs
83
+
84
+ // Increment counter
85
+ for i := len(x.ctr) - 1; i >= 0; i-- {
86
+ x.ctr[i]++
87
+ if x.ctr[i] != 0 {
88
+ break
89
+ }
90
+ }
91
+ }
92
+ x.out = x.out[:remain]
93
+ x.outUsed = 0
94
+ }
95
+
96
+ func (x *ctr) XORKeyStream(dst, src []byte) {
97
+ if len(dst) < len(src) {
98
+ panic("crypto/cipher: output smaller than input")
99
+ }
100
+ if alias.InexactOverlap(dst[:len(src)], src) {
101
+ panic("crypto/cipher: invalid buffer overlap")
102
+ }
103
+ if _, ok := x.b.(*aes.Block); ok {
104
+ panic("crypto/cipher: internal error: generic CTR used with AES")
105
+ }
106
+ for len(src) > 0 {
107
+ if x.outUsed >= len(x.out)-x.b.BlockSize() {
108
+ x.refill()
109
+ }
110
+ n := subtle.XORBytes(dst, src, x.out[x.outUsed:])
111
+ dst = dst[n:]
112
+ src = src[n:]
113
+ x.outUsed += n
114
+ }
115
+ }
go/src/crypto/cipher/ctr_aes_test.go ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // CTR AES test vectors.
6
+
7
+ // See U.S. National Institute of Standards and Technology (NIST)
8
+ // Special Publication 800-38A, ``Recommendation for Block Cipher
9
+ // Modes of Operation,'' 2001 Edition, pp. 55-58.
10
+
11
+ package cipher_test
12
+
13
+ import (
14
+ "bytes"
15
+ "crypto/aes"
16
+ "crypto/cipher"
17
+ "crypto/internal/boring"
18
+ "crypto/internal/cryptotest"
19
+ fipsaes "crypto/internal/fips140/aes"
20
+ "encoding/binary"
21
+ "encoding/hex"
22
+ "fmt"
23
+ "math/rand"
24
+ "sort"
25
+ "strings"
26
+ "testing"
27
+ )
28
+
29
+ var commonCounter = []byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}
30
+
31
+ var ctrAESTests = []struct {
32
+ name string
33
+ key []byte
34
+ iv []byte
35
+ in []byte
36
+ out []byte
37
+ }{
38
+ // NIST SP 800-38A pp 55-58
39
+ {
40
+ "CTR-AES128",
41
+ commonKey128,
42
+ commonCounter,
43
+ commonInput,
44
+ []byte{
45
+ 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
46
+ 0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
47
+ 0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
48
+ 0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee,
49
+ },
50
+ },
51
+ {
52
+ "CTR-AES192",
53
+ commonKey192,
54
+ commonCounter,
55
+ commonInput,
56
+ []byte{
57
+ 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2, 0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b,
58
+ 0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef, 0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94,
59
+ 0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70, 0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7,
60
+ 0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58, 0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50,
61
+ },
62
+ },
63
+ {
64
+ "CTR-AES256",
65
+ commonKey256,
66
+ commonCounter,
67
+ commonInput,
68
+ []byte{
69
+ 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5, 0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28,
70
+ 0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a, 0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5,
71
+ 0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c, 0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d,
72
+ 0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6, 0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6,
73
+ },
74
+ },
75
+ }
76
+
77
+ func TestCTR_AES(t *testing.T) {
78
+ cryptotest.TestAllImplementations(t, "aes", testCTR_AES)
79
+ }
80
+
81
+ func testCTR_AES(t *testing.T) {
82
+ for _, tt := range ctrAESTests {
83
+ test := tt.name
84
+
85
+ c, err := aes.NewCipher(tt.key)
86
+ if err != nil {
87
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
88
+ continue
89
+ }
90
+
91
+ for j := 0; j <= 5; j += 5 {
92
+ in := tt.in[0 : len(tt.in)-j]
93
+ ctr := cipher.NewCTR(c, tt.iv)
94
+ encrypted := make([]byte, len(in))
95
+ ctr.XORKeyStream(encrypted, in)
96
+ if out := tt.out[:len(in)]; !bytes.Equal(out, encrypted) {
97
+ t.Errorf("%s/%d: CTR\ninpt %x\nhave %x\nwant %x", test, len(in), in, encrypted, out)
98
+ }
99
+ }
100
+
101
+ for j := 0; j <= 7; j += 7 {
102
+ in := tt.out[0 : len(tt.out)-j]
103
+ ctr := cipher.NewCTR(c, tt.iv)
104
+ plain := make([]byte, len(in))
105
+ ctr.XORKeyStream(plain, in)
106
+ if out := tt.in[:len(in)]; !bytes.Equal(out, plain) {
107
+ t.Errorf("%s/%d: CTRReader\nhave %x\nwant %x", test, len(out), plain, out)
108
+ }
109
+ }
110
+
111
+ if t.Failed() {
112
+ break
113
+ }
114
+ }
115
+ }
116
+
117
+ func makeTestingCiphers(aesBlock cipher.Block, iv []byte) (genericCtr, multiblockCtr cipher.Stream) {
118
+ return cipher.NewCTR(wrap(aesBlock), iv), cipher.NewCTR(aesBlock, iv)
119
+ }
120
+
121
+ // TestCTR_AES_blocks8FastPathMatchesGeneric ensures the overlow aware branch
122
+ // produces identical keystreams to the generic counter walker across
123
+ // representative IVs, including near-overflow cases.
124
+ func TestCTR_AES_blocks8FastPathMatchesGeneric(t *testing.T) {
125
+ key := make([]byte, aes.BlockSize)
126
+ block, err := aes.NewCipher(key)
127
+ if err != nil {
128
+ t.Fatal(err)
129
+ }
130
+ if _, ok := block.(*fipsaes.Block); !ok {
131
+ t.Skip("requires crypto/internal/fips140/aes")
132
+ }
133
+
134
+ keystream := make([]byte, 8*aes.BlockSize)
135
+
136
+ testCases := []struct {
137
+ name string
138
+ hi uint64
139
+ lo uint64
140
+ }{
141
+ {"Zero", 0, 0},
142
+ {"NearOverflowMinus7", 1, ^uint64(0) - 7},
143
+ {"NearOverflowMinus6", 2, ^uint64(0) - 6},
144
+ {"Overflow", 0, ^uint64(0)},
145
+ }
146
+
147
+ for _, tc := range testCases {
148
+ t.Run(tc.name, func(t *testing.T) {
149
+ var iv [aes.BlockSize]byte
150
+ binary.BigEndian.PutUint64(iv[0:8], tc.hi)
151
+ binary.BigEndian.PutUint64(iv[8:], tc.lo)
152
+
153
+ generic, multiblock := makeTestingCiphers(block, iv[:])
154
+
155
+ genericOut := make([]byte, len(keystream))
156
+ multiblockOut := make([]byte, len(keystream))
157
+
158
+ generic.XORKeyStream(genericOut, keystream)
159
+ multiblock.XORKeyStream(multiblockOut, keystream)
160
+
161
+ if !bytes.Equal(multiblockOut, genericOut) {
162
+ t.Fatalf("mismatch for iv %#x:%#x\n"+
163
+ "asm keystream: %x\n"+
164
+ "gen keystream: %x\n"+
165
+ "asm counters: %x\n"+
166
+ "gen counters: %x",
167
+ tc.hi, tc.lo, multiblockOut, genericOut,
168
+ extractCounters(block, multiblockOut),
169
+ extractCounters(block, genericOut))
170
+ }
171
+ })
172
+ }
173
+ }
174
+
175
+ func randBytes(t *testing.T, r *rand.Rand, count int) []byte {
176
+ t.Helper()
177
+ buf := make([]byte, count)
178
+ n, err := r.Read(buf)
179
+ if err != nil {
180
+ t.Fatal(err)
181
+ }
182
+ if n != count {
183
+ t.Fatal("short read from Rand")
184
+ }
185
+ return buf
186
+ }
187
+
188
+ const aesBlockSize = 16
189
+
190
+ type ctrAble interface {
191
+ NewCTR(iv []byte) cipher.Stream
192
+ }
193
+
194
+ // Verify that multiblock AES CTR (src/crypto/aes/ctr_*.s)
195
+ // produces the same results as generic single-block implementation.
196
+ // This test runs checks on random IV.
197
+ func TestCTR_AES_multiblock_random_IV(t *testing.T) {
198
+ r := rand.New(rand.NewSource(54321))
199
+ iv := randBytes(t, r, aesBlockSize)
200
+ const Size = 100
201
+
202
+ for _, keySize := range []int{16, 24, 32} {
203
+ t.Run(fmt.Sprintf("keySize=%d", keySize), func(t *testing.T) {
204
+ key := randBytes(t, r, keySize)
205
+ aesBlock, err := aes.NewCipher(key)
206
+ if err != nil {
207
+ t.Fatal(err)
208
+ }
209
+ genericCtr, _ := makeTestingCiphers(aesBlock, iv)
210
+
211
+ plaintext := randBytes(t, r, Size)
212
+
213
+ // Generate reference ciphertext.
214
+ genericCiphertext := make([]byte, len(plaintext))
215
+ genericCtr.XORKeyStream(genericCiphertext, plaintext)
216
+
217
+ // Split the text in 3 parts in all possible ways and encrypt them
218
+ // individually using multiblock implementation to catch edge cases.
219
+
220
+ for part1 := 0; part1 <= Size; part1++ {
221
+ t.Run(fmt.Sprintf("part1=%d", part1), func(t *testing.T) {
222
+ for part2 := 0; part2 <= Size-part1; part2++ {
223
+ t.Run(fmt.Sprintf("part2=%d", part2), func(t *testing.T) {
224
+ _, multiblockCtr := makeTestingCiphers(aesBlock, iv)
225
+ multiblockCiphertext := make([]byte, len(plaintext))
226
+ multiblockCtr.XORKeyStream(multiblockCiphertext[:part1], plaintext[:part1])
227
+ multiblockCtr.XORKeyStream(multiblockCiphertext[part1:part1+part2], plaintext[part1:part1+part2])
228
+ multiblockCtr.XORKeyStream(multiblockCiphertext[part1+part2:], plaintext[part1+part2:])
229
+ if !bytes.Equal(genericCiphertext, multiblockCiphertext) {
230
+ t.Fatal("multiblock CTR's output does not match generic CTR's output")
231
+ }
232
+ })
233
+ }
234
+ })
235
+ }
236
+ })
237
+ }
238
+ }
239
+
240
+ func parseHex(str string) []byte {
241
+ b, err := hex.DecodeString(strings.ReplaceAll(str, " ", ""))
242
+ if err != nil {
243
+ panic(err)
244
+ }
245
+ return b
246
+ }
247
+
248
+ // Verify that multiblock AES CTR (src/crypto/aes/ctr_*.s)
249
+ // produces the same results as generic single-block implementation.
250
+ // This test runs checks on edge cases (IV overflows).
251
+ func TestCTR_AES_multiblock_overflow_IV(t *testing.T) {
252
+ r := rand.New(rand.NewSource(987654))
253
+
254
+ const Size = 4096
255
+ plaintext := randBytes(t, r, Size)
256
+
257
+ ivs := [][]byte{
258
+ parseHex("00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FF"),
259
+ parseHex("FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF"),
260
+ parseHex("FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00"),
261
+ parseHex("FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF fe"),
262
+ parseHex("00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF fe"),
263
+ parseHex("FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 00"),
264
+ parseHex("00 00 00 00 00 00 00 01 FF FF FF FF FF FF FF 00"),
265
+ parseHex("00 00 00 00 00 00 00 01 FF FF FF FF FF FF FF FF"),
266
+ parseHex("00 00 00 00 00 00 00 01 FF FF FF FF FF FF FF fe"),
267
+ parseHex("00 00 00 00 00 00 00 01 FF FF FF FF FF FF FF 00"),
268
+ }
269
+
270
+ for _, keySize := range []int{16, 24, 32} {
271
+ t.Run(fmt.Sprintf("keySize=%d", keySize), func(t *testing.T) {
272
+ for _, iv := range ivs {
273
+ key := randBytes(t, r, keySize)
274
+ aesBlock, err := aes.NewCipher(key)
275
+ if err != nil {
276
+ t.Fatal(err)
277
+ }
278
+
279
+ t.Run(fmt.Sprintf("iv=%s", hex.EncodeToString(iv)), func(t *testing.T) {
280
+ for _, offset := range []int{0, 1, 16, 1024} {
281
+ t.Run(fmt.Sprintf("offset=%d", offset), func(t *testing.T) {
282
+ genericCtr, multiblockCtr := makeTestingCiphers(aesBlock, iv)
283
+
284
+ // Generate reference ciphertext.
285
+ genericCiphertext := make([]byte, Size)
286
+ genericCtr.XORKeyStream(genericCiphertext, plaintext)
287
+
288
+ multiblockCiphertext := make([]byte, Size)
289
+ multiblockCtr.XORKeyStream(multiblockCiphertext, plaintext[:offset])
290
+ multiblockCtr.XORKeyStream(multiblockCiphertext[offset:], plaintext[offset:])
291
+ if !bytes.Equal(genericCiphertext, multiblockCiphertext) {
292
+ t.Fatal("multiblock CTR's output does not match generic CTR's output")
293
+ }
294
+ })
295
+ }
296
+ })
297
+ }
298
+ })
299
+ }
300
+ }
301
+
302
+ // Check that method XORKeyStreamAt works correctly.
303
+ func TestCTR_AES_multiblock_XORKeyStreamAt(t *testing.T) {
304
+ if boring.Enabled {
305
+ t.Skip("XORKeyStreamAt is not available in boring mode")
306
+ }
307
+
308
+ r := rand.New(rand.NewSource(12345))
309
+ const Size = 32 * 1024 * 1024
310
+ plaintext := randBytes(t, r, Size)
311
+
312
+ for _, keySize := range []int{16, 24, 32} {
313
+ t.Run(fmt.Sprintf("keySize=%d", keySize), func(t *testing.T) {
314
+ key := randBytes(t, r, keySize)
315
+ iv := randBytes(t, r, aesBlockSize)
316
+
317
+ aesBlock, err := aes.NewCipher(key)
318
+ if err != nil {
319
+ t.Fatal(err)
320
+ }
321
+ genericCtr, _ := makeTestingCiphers(aesBlock, iv)
322
+ ctrAt := fipsaes.NewCTR(aesBlock.(*fipsaes.Block), iv)
323
+
324
+ // Generate reference ciphertext.
325
+ genericCiphertext := make([]byte, Size)
326
+ genericCtr.XORKeyStream(genericCiphertext, plaintext)
327
+
328
+ multiblockCiphertext := make([]byte, Size)
329
+ // Split the range to random slices.
330
+ const N = 1000
331
+ boundaries := make([]int, 0, N+2)
332
+ for i := 0; i < N; i++ {
333
+ boundaries = append(boundaries, r.Intn(Size))
334
+ }
335
+ boundaries = append(boundaries, 0)
336
+ boundaries = append(boundaries, Size)
337
+ sort.Ints(boundaries)
338
+
339
+ for _, i := range r.Perm(N + 1) {
340
+ begin := boundaries[i]
341
+ end := boundaries[i+1]
342
+ ctrAt.XORKeyStreamAt(
343
+ multiblockCiphertext[begin:end],
344
+ plaintext[begin:end],
345
+ uint64(begin),
346
+ )
347
+ }
348
+
349
+ if !bytes.Equal(genericCiphertext, multiblockCiphertext) {
350
+ t.Fatal("multiblock CTR's output does not match generic CTR's output")
351
+ }
352
+ })
353
+ }
354
+ }
355
+
356
+ func extractCounters(block cipher.Block, keystream []byte) []byte {
357
+ blockSize := block.BlockSize()
358
+ res := make([]byte, len(keystream))
359
+ for i := 0; i < len(keystream); i += blockSize {
360
+ block.Decrypt(res[i:i+blockSize], keystream[i:i+blockSize])
361
+ }
362
+ return res
363
+ }
go/src/crypto/cipher/ctr_test.go ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/aes"
10
+ "crypto/cipher"
11
+ "crypto/des"
12
+ "crypto/internal/cryptotest"
13
+ "fmt"
14
+ "testing"
15
+ )
16
+
17
+ type noopBlock int
18
+
19
+ func (b noopBlock) BlockSize() int { return int(b) }
20
+ func (noopBlock) Encrypt(dst, src []byte) { copy(dst, src) }
21
+ func (noopBlock) Decrypt(dst, src []byte) { panic("unreachable") }
22
+
23
+ func inc(b []byte) {
24
+ for i := len(b) - 1; i >= 0; i++ {
25
+ b[i]++
26
+ if b[i] != 0 {
27
+ break
28
+ }
29
+ }
30
+ }
31
+
32
+ func xor(a, b []byte) {
33
+ for i := range a {
34
+ a[i] ^= b[i]
35
+ }
36
+ }
37
+
38
+ func TestCTR(t *testing.T) {
39
+ for size := 64; size <= 1024; size *= 2 {
40
+ iv := make([]byte, size)
41
+ ctr := cipher.NewCTR(noopBlock(size), iv)
42
+ src := make([]byte, 1024)
43
+ for i := range src {
44
+ src[i] = 0xff
45
+ }
46
+ want := make([]byte, 1024)
47
+ copy(want, src)
48
+ counter := make([]byte, size)
49
+ for i := 1; i < len(want)/size; i++ {
50
+ inc(counter)
51
+ xor(want[i*size:(i+1)*size], counter)
52
+ }
53
+ dst := make([]byte, 1024)
54
+ ctr.XORKeyStream(dst, src)
55
+ if !bytes.Equal(dst, want) {
56
+ t.Errorf("for size %d\nhave %x\nwant %x", size, dst, want)
57
+ }
58
+ }
59
+ }
60
+
61
+ func TestCTRStream(t *testing.T) {
62
+ cryptotest.TestAllImplementations(t, "aes", func(t *testing.T) {
63
+ for _, keylen := range []int{128, 192, 256} {
64
+ t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
65
+ rng := newRandReader(t)
66
+
67
+ key := make([]byte, keylen/8)
68
+ rng.Read(key)
69
+
70
+ block, err := aes.NewCipher(key)
71
+ if err != nil {
72
+ panic(err)
73
+ }
74
+
75
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCTR)
76
+ })
77
+ }
78
+ })
79
+
80
+ t.Run("DES", func(t *testing.T) {
81
+ rng := newRandReader(t)
82
+
83
+ key := make([]byte, 8)
84
+ rng.Read(key)
85
+
86
+ block, err := des.NewCipher(key)
87
+ if err != nil {
88
+ panic(err)
89
+ }
90
+
91
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewCTR)
92
+ })
93
+ }
94
+
95
+ func TestCTRExtraMethods(t *testing.T) {
96
+ block, _ := aes.NewCipher(make([]byte, 16))
97
+ iv := make([]byte, block.BlockSize())
98
+ s := cipher.NewCTR(block, iv)
99
+ cryptotest.NoExtraMethods(t, &s)
100
+ }
go/src/crypto/cipher/example_test.go ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 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_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/aes"
10
+ "crypto/cipher"
11
+ "crypto/rand"
12
+ "encoding/hex"
13
+ "fmt"
14
+ "io"
15
+ "os"
16
+ )
17
+
18
+ func ExampleNewGCM_encrypt() {
19
+ // Load your secret key from a safe place and reuse it across multiple
20
+ // Seal/Open calls. (Obviously don't use this example key for anything
21
+ // real.) If you want to convert a passphrase to a key, use a suitable
22
+ // package like bcrypt or scrypt.
23
+ // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
24
+ key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
25
+ plaintext := []byte("exampleplaintext")
26
+
27
+ block, err := aes.NewCipher(key)
28
+ if err != nil {
29
+ panic(err.Error())
30
+ }
31
+
32
+ aesgcm, err := cipher.NewGCM(block)
33
+ if err != nil {
34
+ panic(err.Error())
35
+ }
36
+
37
+ // Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
38
+ nonce := make([]byte, aesgcm.NonceSize())
39
+ if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
40
+ panic(err.Error())
41
+ }
42
+
43
+ ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
44
+ fmt.Printf("%x\n", ciphertext)
45
+ }
46
+
47
+ func ExampleNewGCM_decrypt() {
48
+ // Load your secret key from a safe place and reuse it across multiple
49
+ // Seal/Open calls. (Obviously don't use this example key for anything
50
+ // real.) If you want to convert a passphrase to a key, use a suitable
51
+ // package like bcrypt or scrypt.
52
+ // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
53
+ key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
54
+ ciphertext, _ := hex.DecodeString("c3aaa29f002ca75870806e44086700f62ce4d43e902b3888e23ceff797a7a471")
55
+ nonce, _ := hex.DecodeString("64a9433eae7ccceee2fc0eda")
56
+
57
+ block, err := aes.NewCipher(key)
58
+ if err != nil {
59
+ panic(err.Error())
60
+ }
61
+
62
+ aesgcm, err := cipher.NewGCM(block)
63
+ if err != nil {
64
+ panic(err.Error())
65
+ }
66
+
67
+ plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
68
+ if err != nil {
69
+ panic(err.Error())
70
+ }
71
+
72
+ fmt.Printf("%s\n", plaintext)
73
+ // Output: exampleplaintext
74
+ }
75
+
76
+ func ExampleNewCBCDecrypter() {
77
+ // Load your secret key from a safe place and reuse it across multiple
78
+ // NewCipher calls. (Obviously don't use this example key for anything
79
+ // real.) If you want to convert a passphrase to a key, use a suitable
80
+ // package like bcrypt or scrypt.
81
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
82
+ ciphertext, _ := hex.DecodeString("73c86d43a9d700a253a96c85b0f6b03ac9792e0e757f869cca306bd3cba1c62b")
83
+
84
+ block, err := aes.NewCipher(key)
85
+ if err != nil {
86
+ panic(err)
87
+ }
88
+
89
+ // The IV needs to be unique, but not secure. Therefore it's common to
90
+ // include it at the beginning of the ciphertext.
91
+ if len(ciphertext) < aes.BlockSize {
92
+ panic("ciphertext too short")
93
+ }
94
+ iv := ciphertext[:aes.BlockSize]
95
+ ciphertext = ciphertext[aes.BlockSize:]
96
+
97
+ // CBC mode always works in whole blocks.
98
+ if len(ciphertext)%aes.BlockSize != 0 {
99
+ panic("ciphertext is not a multiple of the block size")
100
+ }
101
+
102
+ mode := cipher.NewCBCDecrypter(block, iv)
103
+
104
+ // CryptBlocks can work in-place if the two arguments are the same.
105
+ mode.CryptBlocks(ciphertext, ciphertext)
106
+
107
+ // If the original plaintext lengths are not a multiple of the block
108
+ // size, padding would have to be added when encrypting, which would be
109
+ // removed at this point. For an example, see
110
+ // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
111
+ // critical to note that ciphertexts must be authenticated (i.e. by
112
+ // using crypto/hmac) before being decrypted in order to avoid creating
113
+ // a padding oracle.
114
+
115
+ fmt.Printf("%s\n", ciphertext)
116
+ // Output: exampleplaintext
117
+ }
118
+
119
+ func ExampleNewCBCEncrypter() {
120
+ // Load your secret key from a safe place and reuse it across multiple
121
+ // NewCipher calls. (Obviously don't use this example key for anything
122
+ // real.) If you want to convert a passphrase to a key, use a suitable
123
+ // package like bcrypt or scrypt.
124
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
125
+ plaintext := []byte("exampleplaintext")
126
+
127
+ // CBC mode works on blocks so plaintexts may need to be padded to the
128
+ // next whole block. For an example of such padding, see
129
+ // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
130
+ // assume that the plaintext is already of the correct length.
131
+ if len(plaintext)%aes.BlockSize != 0 {
132
+ panic("plaintext is not a multiple of the block size")
133
+ }
134
+
135
+ block, err := aes.NewCipher(key)
136
+ if err != nil {
137
+ panic(err)
138
+ }
139
+
140
+ // The IV needs to be unique, but not secure. Therefore it's common to
141
+ // include it at the beginning of the ciphertext.
142
+ ciphertext := make([]byte, aes.BlockSize+len(plaintext))
143
+ iv := ciphertext[:aes.BlockSize]
144
+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {
145
+ panic(err)
146
+ }
147
+
148
+ mode := cipher.NewCBCEncrypter(block, iv)
149
+ mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
150
+
151
+ // It's important to remember that ciphertexts must be authenticated
152
+ // (i.e. by using crypto/hmac) as well as being encrypted in order to
153
+ // be secure.
154
+
155
+ fmt.Printf("%x\n", ciphertext)
156
+ }
157
+
158
+ func ExampleNewCFBDecrypter() {
159
+ // Load your secret key from a safe place and reuse it across multiple
160
+ // NewCipher calls. (Obviously don't use this example key for anything
161
+ // real.) If you want to convert a passphrase to a key, use a suitable
162
+ // package like bcrypt or scrypt.
163
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
164
+ ciphertext, _ := hex.DecodeString("7dd015f06bec7f1b8f6559dad89f4131da62261786845100056b353194ad")
165
+
166
+ block, err := aes.NewCipher(key)
167
+ if err != nil {
168
+ panic(err)
169
+ }
170
+
171
+ // The IV needs to be unique, but not secure. Therefore it's common to
172
+ // include it at the beginning of the ciphertext.
173
+ if len(ciphertext) < aes.BlockSize {
174
+ panic("ciphertext too short")
175
+ }
176
+ iv := ciphertext[:aes.BlockSize]
177
+ ciphertext = ciphertext[aes.BlockSize:]
178
+
179
+ stream := cipher.NewCFBDecrypter(block, iv)
180
+
181
+ // XORKeyStream can work in-place if the two arguments are the same.
182
+ stream.XORKeyStream(ciphertext, ciphertext)
183
+ fmt.Printf("%s", ciphertext)
184
+ // Output: some plaintext
185
+ }
186
+
187
+ func ExampleNewCFBEncrypter() {
188
+ // Load your secret key from a safe place and reuse it across multiple
189
+ // NewCipher calls. (Obviously don't use this example key for anything
190
+ // real.) If you want to convert a passphrase to a key, use a suitable
191
+ // package like bcrypt or scrypt.
192
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
193
+ plaintext := []byte("some plaintext")
194
+
195
+ block, err := aes.NewCipher(key)
196
+ if err != nil {
197
+ panic(err)
198
+ }
199
+
200
+ // The IV needs to be unique, but not secure. Therefore it's common to
201
+ // include it at the beginning of the ciphertext.
202
+ ciphertext := make([]byte, aes.BlockSize+len(plaintext))
203
+ iv := ciphertext[:aes.BlockSize]
204
+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {
205
+ panic(err)
206
+ }
207
+
208
+ stream := cipher.NewCFBEncrypter(block, iv)
209
+ stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
210
+
211
+ // It's important to remember that ciphertexts must be authenticated
212
+ // (i.e. by using crypto/hmac) as well as being encrypted in order to
213
+ // be secure.
214
+ fmt.Printf("%x\n", ciphertext)
215
+ }
216
+
217
+ func ExampleNewCTR() {
218
+ // Load your secret key from a safe place and reuse it across multiple
219
+ // NewCipher calls. (Obviously don't use this example key for anything
220
+ // real.) If you want to convert a passphrase to a key, use a suitable
221
+ // package like bcrypt or scrypt.
222
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
223
+ plaintext := []byte("some plaintext")
224
+
225
+ block, err := aes.NewCipher(key)
226
+ if err != nil {
227
+ panic(err)
228
+ }
229
+
230
+ // The IV needs to be unique, but not secure. Therefore it's common to
231
+ // include it at the beginning of the ciphertext.
232
+ ciphertext := make([]byte, aes.BlockSize+len(plaintext))
233
+ iv := ciphertext[:aes.BlockSize]
234
+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {
235
+ panic(err)
236
+ }
237
+
238
+ stream := cipher.NewCTR(block, iv)
239
+ stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
240
+
241
+ // It's important to remember that ciphertexts must be authenticated
242
+ // (i.e. by using crypto/hmac) as well as being encrypted in order to
243
+ // be secure.
244
+
245
+ // CTR mode is the same for both encryption and decryption, so we can
246
+ // also decrypt that ciphertext with NewCTR.
247
+
248
+ plaintext2 := make([]byte, len(plaintext))
249
+ stream = cipher.NewCTR(block, iv)
250
+ stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
251
+
252
+ fmt.Printf("%s\n", plaintext2)
253
+ // Output: some plaintext
254
+ }
255
+
256
+ func ExampleNewOFB() {
257
+ // Load your secret key from a safe place and reuse it across multiple
258
+ // NewCipher calls. (Obviously don't use this example key for anything
259
+ // real.) If you want to convert a passphrase to a key, use a suitable
260
+ // package like bcrypt or scrypt.
261
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
262
+ plaintext := []byte("some plaintext")
263
+
264
+ block, err := aes.NewCipher(key)
265
+ if err != nil {
266
+ panic(err)
267
+ }
268
+
269
+ // The IV needs to be unique, but not secure. Therefore it's common to
270
+ // include it at the beginning of the ciphertext.
271
+ ciphertext := make([]byte, aes.BlockSize+len(plaintext))
272
+ iv := ciphertext[:aes.BlockSize]
273
+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {
274
+ panic(err)
275
+ }
276
+
277
+ stream := cipher.NewOFB(block, iv)
278
+ stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
279
+
280
+ // It's important to remember that ciphertexts must be authenticated
281
+ // (i.e. by using crypto/hmac) as well as being encrypted in order to
282
+ // be secure.
283
+
284
+ // OFB mode is the same for both encryption and decryption, so we can
285
+ // also decrypt that ciphertext with NewOFB.
286
+
287
+ plaintext2 := make([]byte, len(plaintext))
288
+ stream = cipher.NewOFB(block, iv)
289
+ stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
290
+
291
+ fmt.Printf("%s\n", plaintext2)
292
+ // Output: some plaintext
293
+ }
294
+
295
+ func ExampleStreamReader() {
296
+ // Load your secret key from a safe place and reuse it across multiple
297
+ // NewCipher calls. (Obviously don't use this example key for anything
298
+ // real.) If you want to convert a passphrase to a key, use a suitable
299
+ // package like bcrypt or scrypt.
300
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
301
+
302
+ encrypted, _ := hex.DecodeString("cf0495cc6f75dafc23948538e79904a9")
303
+ bReader := bytes.NewReader(encrypted)
304
+
305
+ block, err := aes.NewCipher(key)
306
+ if err != nil {
307
+ panic(err)
308
+ }
309
+
310
+ // If the key is unique for each ciphertext, then it's ok to use a zero
311
+ // IV.
312
+ var iv [aes.BlockSize]byte
313
+ stream := cipher.NewOFB(block, iv[:])
314
+
315
+ reader := &cipher.StreamReader{S: stream, R: bReader}
316
+ // Copy the input to the output stream, decrypting as we go.
317
+ if _, err := io.Copy(os.Stdout, reader); err != nil {
318
+ panic(err)
319
+ }
320
+
321
+ // Note that this example is simplistic in that it omits any
322
+ // authentication of the encrypted data. If you were actually to use
323
+ // StreamReader in this manner, an attacker could flip arbitrary bits in
324
+ // the output.
325
+
326
+ // Output: some secret text
327
+ }
328
+
329
+ func ExampleStreamWriter() {
330
+ // Load your secret key from a safe place and reuse it across multiple
331
+ // NewCipher calls. (Obviously don't use this example key for anything
332
+ // real.) If you want to convert a passphrase to a key, use a suitable
333
+ // package like bcrypt or scrypt.
334
+ key, _ := hex.DecodeString("6368616e676520746869732070617373")
335
+
336
+ bReader := bytes.NewReader([]byte("some secret text"))
337
+
338
+ block, err := aes.NewCipher(key)
339
+ if err != nil {
340
+ panic(err)
341
+ }
342
+
343
+ // If the key is unique for each ciphertext, then it's ok to use a zero
344
+ // IV.
345
+ var iv [aes.BlockSize]byte
346
+ stream := cipher.NewOFB(block, iv[:])
347
+
348
+ var out bytes.Buffer
349
+
350
+ writer := &cipher.StreamWriter{S: stream, W: &out}
351
+ // Copy the input to the output buffer, encrypting as we go.
352
+ if _, err := io.Copy(writer, bReader); err != nil {
353
+ panic(err)
354
+ }
355
+
356
+ // Note that this example is simplistic in that it omits any
357
+ // authentication of the encrypted data. If you were actually to use
358
+ // StreamReader in this manner, an attacker could flip arbitrary bits in
359
+ // the decrypted result.
360
+
361
+ fmt.Printf("%x\n", out.Bytes())
362
+ // Output: cf0495cc6f75dafc23948538e79904a9
363
+ }
go/src/crypto/cipher/fuzz_test.go ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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
+ //go:build ppc64le
6
+
7
+ package cipher_test
8
+
9
+ import (
10
+ "bytes"
11
+ "crypto/aes"
12
+ "crypto/cipher"
13
+ "crypto/rand"
14
+ "testing"
15
+ "time"
16
+ )
17
+
18
+ var cbcAESFuzzTests = []struct {
19
+ name string
20
+ key []byte
21
+ }{
22
+ {
23
+ "CBC-AES128",
24
+ commonKey128,
25
+ },
26
+ {
27
+ "CBC-AES192",
28
+ commonKey192,
29
+ },
30
+ {
31
+ "CBC-AES256",
32
+ commonKey256,
33
+ },
34
+ }
35
+
36
+ var timeout *time.Timer
37
+
38
+ const datalen = 1024
39
+
40
+ func TestFuzz(t *testing.T) {
41
+
42
+ for _, ft := range cbcAESFuzzTests {
43
+ c, _ := aes.NewCipher(ft.key)
44
+
45
+ cbcAsm := cipher.NewCBCEncrypter(c, commonIV)
46
+ cbcGeneric := cipher.NewCBCEncrypter(wrap(c), commonIV)
47
+
48
+ if testing.Short() {
49
+ timeout = time.NewTimer(10 * time.Millisecond)
50
+ } else {
51
+ timeout = time.NewTimer(2 * time.Second)
52
+ }
53
+
54
+ indata := make([]byte, datalen)
55
+ outgeneric := make([]byte, datalen)
56
+ outdata := make([]byte, datalen)
57
+
58
+ fuzzencrypt:
59
+ for {
60
+ select {
61
+ case <-timeout.C:
62
+ break fuzzencrypt
63
+ default:
64
+ }
65
+
66
+ rand.Read(indata[:])
67
+
68
+ cbcGeneric.CryptBlocks(indata, outgeneric)
69
+ cbcAsm.CryptBlocks(indata, outdata)
70
+
71
+ if !bytes.Equal(outdata, outgeneric) {
72
+ t.Fatalf("AES-CBC encryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
73
+ }
74
+ }
75
+
76
+ cbcAsm = cipher.NewCBCDecrypter(c, commonIV)
77
+ cbcGeneric = cipher.NewCBCDecrypter(wrap(c), commonIV)
78
+
79
+ if testing.Short() {
80
+ timeout = time.NewTimer(10 * time.Millisecond)
81
+ } else {
82
+ timeout = time.NewTimer(2 * time.Second)
83
+ }
84
+
85
+ fuzzdecrypt:
86
+ for {
87
+ select {
88
+ case <-timeout.C:
89
+ break fuzzdecrypt
90
+ default:
91
+ }
92
+
93
+ rand.Read(indata[:])
94
+
95
+ cbcGeneric.CryptBlocks(indata, outgeneric)
96
+ cbcAsm.CryptBlocks(indata, outdata)
97
+
98
+ if !bytes.Equal(outdata, outgeneric) {
99
+ t.Fatalf("AES-CBC decryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
100
+ }
101
+ }
102
+ }
103
+ }
go/src/crypto/cipher/gcm.go ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 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/internal/fips140/aes"
9
+ "crypto/internal/fips140/aes/gcm"
10
+ "crypto/internal/fips140/alias"
11
+ "crypto/internal/fips140only"
12
+ "crypto/subtle"
13
+ "errors"
14
+ "internal/byteorder"
15
+ )
16
+
17
+ const (
18
+ gcmBlockSize = 16
19
+ gcmStandardNonceSize = 12
20
+ gcmTagSize = 16
21
+ gcmMinimumTagSize = 12 // NIST SP 800-38D recommends tags with 12 or more bytes.
22
+ )
23
+
24
+ // NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode
25
+ // with the standard nonce length.
26
+ //
27
+ // In general, the GHASH operation performed by this implementation of GCM is not constant-time.
28
+ // An exception is when the underlying [Block] was created by aes.NewCipher
29
+ // on systems with hardware support for AES. See the [crypto/aes] package documentation for details.
30
+ func NewGCM(cipher Block) (AEAD, error) {
31
+ if fips140only.Enforced() {
32
+ return nil, errors.New("crypto/cipher: use of GCM with arbitrary IVs is not allowed in FIPS 140-only mode, use NewGCMWithRandomNonce")
33
+ }
34
+ return newGCM(cipher, gcmStandardNonceSize, gcmTagSize)
35
+ }
36
+
37
+ // NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois
38
+ // Counter Mode, which accepts nonces of the given length. The length must not
39
+ // be zero.
40
+ //
41
+ // Only use this function if you require compatibility with an existing
42
+ // cryptosystem that uses non-standard nonce lengths. All other users should use
43
+ // [NewGCM], which is faster and more resistant to misuse.
44
+ func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error) {
45
+ if fips140only.Enforced() {
46
+ return nil, errors.New("crypto/cipher: use of GCM with arbitrary IVs is not allowed in FIPS 140-only mode, use NewGCMWithRandomNonce")
47
+ }
48
+ return newGCM(cipher, size, gcmTagSize)
49
+ }
50
+
51
+ // NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
52
+ // Counter Mode, which generates tags with the given length.
53
+ //
54
+ // Tag sizes between 12 and 16 bytes are allowed.
55
+ //
56
+ // Only use this function if you require compatibility with an existing
57
+ // cryptosystem that uses non-standard tag lengths. All other users should use
58
+ // [NewGCM], which is more resistant to misuse.
59
+ func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error) {
60
+ if fips140only.Enforced() {
61
+ return nil, errors.New("crypto/cipher: use of GCM with arbitrary IVs is not allowed in FIPS 140-only mode, use NewGCMWithRandomNonce")
62
+ }
63
+ return newGCM(cipher, gcmStandardNonceSize, tagSize)
64
+ }
65
+
66
+ func newGCM(cipher Block, nonceSize, tagSize int) (AEAD, error) {
67
+ c, ok := cipher.(*aes.Block)
68
+ if !ok {
69
+ if fips140only.Enforced() {
70
+ return nil, errors.New("crypto/cipher: use of GCM with non-AES ciphers is not allowed in FIPS 140-only mode")
71
+ }
72
+ return newGCMFallback(cipher, nonceSize, tagSize)
73
+ }
74
+ // We don't return gcm.New directly, because it would always return a non-nil
75
+ // AEAD interface value with type *gcm.GCM even if the *gcm.GCM is nil.
76
+ g, err := gcm.New(c, nonceSize, tagSize)
77
+ if err != nil {
78
+ return nil, err
79
+ }
80
+ return g, nil
81
+ }
82
+
83
+ // NewGCMWithRandomNonce returns the given cipher wrapped in Galois Counter
84
+ // Mode, with randomly-generated nonces. The cipher must have been created by
85
+ // [crypto/aes.NewCipher].
86
+ //
87
+ // It generates a random 96-bit nonce, which is prepended to the ciphertext by Seal,
88
+ // and is extracted from the ciphertext by Open. The NonceSize of the AEAD is zero,
89
+ // while the Overhead is 28 bytes (the combination of nonce size and tag size).
90
+ //
91
+ // A given key MUST NOT be used to encrypt more than 2^32 messages, to limit the
92
+ // risk of a random nonce collision to negligible levels.
93
+ func NewGCMWithRandomNonce(cipher Block) (AEAD, error) {
94
+ c, ok := cipher.(*aes.Block)
95
+ if !ok {
96
+ return nil, errors.New("cipher: NewGCMWithRandomNonce requires aes.Block")
97
+ }
98
+ g, err := gcm.New(c, gcmStandardNonceSize, gcmTagSize)
99
+ if err != nil {
100
+ return nil, err
101
+ }
102
+ return gcmWithRandomNonce{g}, nil
103
+ }
104
+
105
+ type gcmWithRandomNonce struct {
106
+ *gcm.GCM
107
+ }
108
+
109
+ func (g gcmWithRandomNonce) NonceSize() int {
110
+ return 0
111
+ }
112
+
113
+ func (g gcmWithRandomNonce) Overhead() int {
114
+ return gcmStandardNonceSize + gcmTagSize
115
+ }
116
+
117
+ func (g gcmWithRandomNonce) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
118
+ if len(nonce) != 0 {
119
+ panic("crypto/cipher: non-empty nonce passed to GCMWithRandomNonce")
120
+ }
121
+
122
+ ret, out := sliceForAppend(dst, gcmStandardNonceSize+len(plaintext)+gcmTagSize)
123
+ if alias.InexactOverlap(out, plaintext) {
124
+ panic("crypto/cipher: invalid buffer overlap of output and input")
125
+ }
126
+ if alias.AnyOverlap(out, additionalData) {
127
+ panic("crypto/cipher: invalid buffer overlap of output and additional data")
128
+ }
129
+ nonce = out[:gcmStandardNonceSize]
130
+ ciphertext := out[gcmStandardNonceSize:]
131
+
132
+ // The AEAD interface allows using plaintext[:0] or ciphertext[:0] as dst.
133
+ //
134
+ // This is kind of a problem when trying to prepend or trim a nonce, because the
135
+ // actual AES-GCTR blocks end up overlapping but not exactly.
136
+ //
137
+ // In Open, we write the output *before* the input, so unless we do something
138
+ // weird like working through a chunk of block backwards, it works out.
139
+ //
140
+ // In Seal, we could work through the input backwards or intentionally load
141
+ // ahead before writing.
142
+ //
143
+ // However, the crypto/internal/fips140/aes/gcm APIs also check for exact overlap,
144
+ // so for now we just do a memmove if we detect overlap.
145
+ //
146
+ // ┌───────────────────────────┬ ─ ─
147
+ // │PPPPPPPPPPPPPPPPPPPPPPPPPPP│ │
148
+ // └▽─────────────────────────▲┴ ─ ─
149
+ // ╲ Seal ╲
150
+ // ╲ Open ╲
151
+ // ┌───▼─────────────────────────△──┐
152
+ // │NN|CCCCCCCCCCCCCCCCCCCCCCCCCCC|T│
153
+ // └────────────────────────────────┘
154
+ //
155
+ if alias.AnyOverlap(out, plaintext) {
156
+ copy(ciphertext, plaintext)
157
+ plaintext = ciphertext[:len(plaintext)]
158
+ }
159
+
160
+ gcm.SealWithRandomNonce(g.GCM, nonce, ciphertext, plaintext, additionalData)
161
+ return ret
162
+ }
163
+
164
+ func (g gcmWithRandomNonce) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
165
+ if len(nonce) != 0 {
166
+ panic("crypto/cipher: non-empty nonce passed to GCMWithRandomNonce")
167
+ }
168
+ if len(ciphertext) < gcmStandardNonceSize+gcmTagSize {
169
+ return nil, errOpen
170
+ }
171
+
172
+ ret, out := sliceForAppend(dst, len(ciphertext)-gcmStandardNonceSize-gcmTagSize)
173
+ if alias.InexactOverlap(out, ciphertext) {
174
+ panic("crypto/cipher: invalid buffer overlap of output and input")
175
+ }
176
+ if alias.AnyOverlap(out, additionalData) {
177
+ panic("crypto/cipher: invalid buffer overlap of output and additional data")
178
+ }
179
+ // See the discussion in Seal. Note that if there is any overlap at this
180
+ // point, it's because out = ciphertext, so out must have enough capacity
181
+ // even if we sliced the tag off. Also note how [AEAD] specifies that "the
182
+ // contents of dst, up to its capacity, may be overwritten".
183
+ if alias.AnyOverlap(out, ciphertext) {
184
+ nonce = make([]byte, gcmStandardNonceSize)
185
+ copy(nonce, ciphertext)
186
+ copy(out[:len(ciphertext)], ciphertext[gcmStandardNonceSize:])
187
+ ciphertext = out[:len(ciphertext)-gcmStandardNonceSize]
188
+ } else {
189
+ nonce = ciphertext[:gcmStandardNonceSize]
190
+ ciphertext = ciphertext[gcmStandardNonceSize:]
191
+ }
192
+
193
+ _, err := g.GCM.Open(out[:0], nonce, ciphertext, additionalData)
194
+ if err != nil {
195
+ return nil, err
196
+ }
197
+ return ret, nil
198
+ }
199
+
200
+ // gcmAble is an interface implemented by ciphers that have a specific optimized
201
+ // implementation of GCM. crypto/aes doesn't use this anymore, and we'd like to
202
+ // eventually remove it.
203
+ type gcmAble interface {
204
+ NewGCM(nonceSize, tagSize int) (AEAD, error)
205
+ }
206
+
207
+ func newGCMFallback(cipher Block, nonceSize, tagSize int) (AEAD, error) {
208
+ if tagSize < gcmMinimumTagSize || tagSize > gcmBlockSize {
209
+ return nil, errors.New("cipher: incorrect tag size given to GCM")
210
+ }
211
+ if nonceSize <= 0 {
212
+ return nil, errors.New("cipher: the nonce can't have zero length")
213
+ }
214
+ if cipher, ok := cipher.(gcmAble); ok {
215
+ return cipher.NewGCM(nonceSize, tagSize)
216
+ }
217
+ if cipher.BlockSize() != gcmBlockSize {
218
+ return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
219
+ }
220
+ return &gcmFallback{cipher: cipher, nonceSize: nonceSize, tagSize: tagSize}, nil
221
+ }
222
+
223
+ // gcmFallback is only used for non-AES ciphers, which regrettably we
224
+ // theoretically support. It's a copy of the generic implementation from
225
+ // crypto/internal/fips140/aes/gcm/gcm_generic.go, refer to that file for more details.
226
+ type gcmFallback struct {
227
+ cipher Block
228
+ nonceSize int
229
+ tagSize int
230
+ }
231
+
232
+ func (g *gcmFallback) NonceSize() int {
233
+ return g.nonceSize
234
+ }
235
+
236
+ func (g *gcmFallback) Overhead() int {
237
+ return g.tagSize
238
+ }
239
+
240
+ func (g *gcmFallback) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
241
+ if len(nonce) != g.nonceSize {
242
+ panic("crypto/cipher: incorrect nonce length given to GCM")
243
+ }
244
+ if g.nonceSize == 0 {
245
+ panic("crypto/cipher: incorrect GCM nonce size")
246
+ }
247
+ if uint64(len(plaintext)) > uint64((1<<32)-2)*gcmBlockSize {
248
+ panic("crypto/cipher: message too large for GCM")
249
+ }
250
+
251
+ ret, out := sliceForAppend(dst, len(plaintext)+g.tagSize)
252
+ if alias.InexactOverlap(out, plaintext) {
253
+ panic("crypto/cipher: invalid buffer overlap of output and input")
254
+ }
255
+ if alias.AnyOverlap(out, additionalData) {
256
+ panic("crypto/cipher: invalid buffer overlap of output and additional data")
257
+ }
258
+
259
+ var H, counter, tagMask [gcmBlockSize]byte
260
+ g.cipher.Encrypt(H[:], H[:])
261
+ deriveCounter(&H, &counter, nonce)
262
+ gcmCounterCryptGeneric(g.cipher, tagMask[:], tagMask[:], &counter)
263
+
264
+ gcmCounterCryptGeneric(g.cipher, out, plaintext, &counter)
265
+
266
+ var tag [gcmTagSize]byte
267
+ gcmAuth(tag[:], &H, &tagMask, out[:len(plaintext)], additionalData)
268
+ copy(out[len(plaintext):], tag[:])
269
+
270
+ return ret
271
+ }
272
+
273
+ var errOpen = errors.New("cipher: message authentication failed")
274
+
275
+ func (g *gcmFallback) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
276
+ if len(nonce) != g.nonceSize {
277
+ panic("crypto/cipher: incorrect nonce length given to GCM")
278
+ }
279
+ if g.tagSize < gcmMinimumTagSize {
280
+ panic("crypto/cipher: incorrect GCM tag size")
281
+ }
282
+
283
+ if len(ciphertext) < g.tagSize {
284
+ return nil, errOpen
285
+ }
286
+ if uint64(len(ciphertext)) > uint64((1<<32)-2)*gcmBlockSize+uint64(g.tagSize) {
287
+ return nil, errOpen
288
+ }
289
+
290
+ ret, out := sliceForAppend(dst, len(ciphertext)-g.tagSize)
291
+ if alias.InexactOverlap(out, ciphertext) {
292
+ panic("crypto/cipher: invalid buffer overlap of output and input")
293
+ }
294
+ if alias.AnyOverlap(out, additionalData) {
295
+ panic("crypto/cipher: invalid buffer overlap of output and additional data")
296
+ }
297
+
298
+ var H, counter, tagMask [gcmBlockSize]byte
299
+ g.cipher.Encrypt(H[:], H[:])
300
+ deriveCounter(&H, &counter, nonce)
301
+ gcmCounterCryptGeneric(g.cipher, tagMask[:], tagMask[:], &counter)
302
+
303
+ tag := ciphertext[len(ciphertext)-g.tagSize:]
304
+ ciphertext = ciphertext[:len(ciphertext)-g.tagSize]
305
+
306
+ var expectedTag [gcmTagSize]byte
307
+ gcmAuth(expectedTag[:], &H, &tagMask, ciphertext, additionalData)
308
+ if subtle.ConstantTimeCompare(expectedTag[:g.tagSize], tag) != 1 {
309
+ // We sometimes decrypt and authenticate concurrently, so we overwrite
310
+ // dst in the event of a tag mismatch. To be consistent across platforms
311
+ // and to avoid releasing unauthenticated plaintext, we clear the buffer
312
+ // in the event of an error.
313
+ clear(out)
314
+ return nil, errOpen
315
+ }
316
+
317
+ gcmCounterCryptGeneric(g.cipher, out, ciphertext, &counter)
318
+
319
+ return ret, nil
320
+ }
321
+
322
+ func deriveCounter(H, counter *[gcmBlockSize]byte, nonce []byte) {
323
+ if len(nonce) == gcmStandardNonceSize {
324
+ copy(counter[:], nonce)
325
+ counter[gcmBlockSize-1] = 1
326
+ } else {
327
+ lenBlock := make([]byte, 16)
328
+ byteorder.BEPutUint64(lenBlock[8:], uint64(len(nonce))*8)
329
+ J := gcm.GHASH(H, nonce, lenBlock)
330
+ copy(counter[:], J)
331
+ }
332
+ }
333
+
334
+ func gcmCounterCryptGeneric(b Block, out, src []byte, counter *[gcmBlockSize]byte) {
335
+ var mask [gcmBlockSize]byte
336
+ for len(src) >= gcmBlockSize {
337
+ b.Encrypt(mask[:], counter[:])
338
+ gcmInc32(counter)
339
+
340
+ subtle.XORBytes(out, src, mask[:])
341
+ out = out[gcmBlockSize:]
342
+ src = src[gcmBlockSize:]
343
+ }
344
+ if len(src) > 0 {
345
+ b.Encrypt(mask[:], counter[:])
346
+ gcmInc32(counter)
347
+ subtle.XORBytes(out, src, mask[:])
348
+ }
349
+ }
350
+
351
+ func gcmInc32(counterBlock *[gcmBlockSize]byte) {
352
+ ctr := counterBlock[len(counterBlock)-4:]
353
+ byteorder.BEPutUint32(ctr, byteorder.BEUint32(ctr)+1)
354
+ }
355
+
356
+ func gcmAuth(out []byte, H, tagMask *[gcmBlockSize]byte, ciphertext, additionalData []byte) {
357
+ lenBlock := make([]byte, 16)
358
+ byteorder.BEPutUint64(lenBlock[:8], uint64(len(additionalData))*8)
359
+ byteorder.BEPutUint64(lenBlock[8:], uint64(len(ciphertext))*8)
360
+ S := gcm.GHASH(H, additionalData, ciphertext, lenBlock)
361
+ subtle.XORBytes(out, S, tagMask[:])
362
+ }
363
+
364
+ // sliceForAppend takes a slice and a requested number of bytes. It returns a
365
+ // slice with the contents of the given slice followed by that many bytes and a
366
+ // second slice that aliases into it and contains only the extra bytes. If the
367
+ // original slice has sufficient capacity then no allocation is performed.
368
+ func sliceForAppend(in []byte, n int) (head, tail []byte) {
369
+ if total := len(in) + n; cap(in) >= total {
370
+ head = in[:total]
371
+ } else {
372
+ head = make([]byte, total)
373
+ copy(head, in)
374
+ }
375
+ tail = head[len(in):]
376
+ return
377
+ }
go/src/crypto/cipher/gcm_fips140v1.26_test.go ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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
+ //go:build !fips140v1.0
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
+ "internal/testenv"
17
+ "math"
18
+ "testing"
19
+ )
20
+
21
+ func TestGCMNoncesFIPSV126(t *testing.T) {
22
+ cryptotest.MustSupportFIPS140(t)
23
+ if !fips140.Enabled {
24
+ cmd := testenv.Command(t, testenv.Executable(t), "-test.run=^TestGCMNoncesFIPSV126$", "-test.v")
25
+ cmd.Env = append(cmd.Environ(), "GODEBUG=fips140=on")
26
+ out, err := cmd.CombinedOutput()
27
+ t.Logf("running with GODEBUG=fips140=on:\n%s", out)
28
+ if err != nil {
29
+ t.Errorf("fips140=on subprocess failed: %v", err)
30
+ }
31
+ return
32
+ }
33
+
34
+ tryNonce := func(aead cipher.AEAD, nonce []byte) bool {
35
+ fips140.ResetServiceIndicator()
36
+ aead.Seal(nil, nonce, []byte("x"), nil)
37
+ return fips140.ServiceIndicator()
38
+ }
39
+ expectOK := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
40
+ t.Helper()
41
+ if !tryNonce(aead, nonce) {
42
+ t.Errorf("expected service indicator true for %x", nonce)
43
+ }
44
+ }
45
+ expectPanic := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
46
+ t.Helper()
47
+ defer func() {
48
+ t.Helper()
49
+ if recover() == nil {
50
+ t.Errorf("expected panic for %x", nonce)
51
+ }
52
+ }()
53
+ tryNonce(aead, nonce)
54
+ }
55
+
56
+ t.Run("NewGCMWithXORCounterNonce", func(t *testing.T) {
57
+ newGCM := func() *gcm.GCMWithXORCounterNonce {
58
+ key := make([]byte, 16)
59
+ block, _ := fipsaes.New(key)
60
+ aead, _ := gcm.NewGCMWithXORCounterNonce(block)
61
+ return aead
62
+ }
63
+ nonce := func(mask []byte, counter uint64) []byte {
64
+ nonce := make([]byte, 12)
65
+ copy(nonce, mask)
66
+ n := binary.BigEndian.AppendUint64(nil, counter)
67
+ for i, b := range n {
68
+ nonce[4+i] ^= b
69
+ }
70
+ return nonce
71
+ }
72
+
73
+ for _, mask := range [][]byte{
74
+ decodeHex(t, "ffffffffffffffffffffffff"),
75
+ decodeHex(t, "aabbccddeeff001122334455"),
76
+ decodeHex(t, "000000000000000000000000"),
77
+ } {
78
+ g := newGCM()
79
+ // Mask is derived from first invocation with zero nonce.
80
+ expectOK(t, g, nonce(mask, 0))
81
+ expectOK(t, g, nonce(mask, 1))
82
+ expectOK(t, g, nonce(mask, 100))
83
+ expectPanic(t, g, nonce(mask, 100))
84
+ expectPanic(t, g, nonce(mask, 99))
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, 0xFFFFFFFF))
93
+ expectOK(t, g, nonce(mask, math.MaxUint64-2))
94
+ expectOK(t, g, nonce(mask, math.MaxUint64-1))
95
+ expectPanic(t, g, nonce(mask, math.MaxUint64))
96
+ expectPanic(t, g, nonce(mask, 0))
97
+
98
+ g = newGCM()
99
+ g.SetNoncePrefixAndMask(mask)
100
+ expectOK(t, g, nonce(mask, math.MaxUint64-1))
101
+ expectPanic(t, g, nonce(mask, math.MaxUint64))
102
+ expectPanic(t, g, nonce(mask, 0))
103
+ }
104
+ })
105
+ }
go/src/crypto/cipher/gcm_test.go ADDED
@@ -0,0 +1,909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/aes"
10
+ "crypto/cipher"
11
+ "crypto/internal/boring"
12
+ "crypto/internal/cryptotest"
13
+ "crypto/internal/fips140"
14
+ fipsaes "crypto/internal/fips140/aes"
15
+ "crypto/internal/fips140/aes/gcm"
16
+ "crypto/rand"
17
+ "encoding/hex"
18
+ "errors"
19
+ "fmt"
20
+ "internal/testenv"
21
+ "io"
22
+ "reflect"
23
+ "testing"
24
+ )
25
+
26
+ var _ cipher.Block = (*wrapper)(nil)
27
+
28
+ type wrapper struct {
29
+ block cipher.Block
30
+ }
31
+
32
+ func (w *wrapper) BlockSize() int { return w.block.BlockSize() }
33
+ func (w *wrapper) Encrypt(dst, src []byte) { w.block.Encrypt(dst, src) }
34
+ func (w *wrapper) Decrypt(dst, src []byte) { w.block.Decrypt(dst, src) }
35
+
36
+ // wrap wraps the Block so that it does not type-asserts to *aes.Block.
37
+ func wrap(b cipher.Block) cipher.Block {
38
+ return &wrapper{b}
39
+ }
40
+
41
+ func testAllImplementations(t *testing.T, f func(*testing.T, func([]byte) cipher.Block)) {
42
+ cryptotest.TestAllImplementations(t, "gcm", func(t *testing.T) {
43
+ f(t, func(b []byte) cipher.Block {
44
+ c, err := aes.NewCipher(b)
45
+ if err != nil {
46
+ t.Fatal(err)
47
+ }
48
+ return c
49
+ })
50
+ })
51
+ t.Run("Fallback", func(t *testing.T) {
52
+ f(t, func(b []byte) cipher.Block {
53
+ c, err := aes.NewCipher(b)
54
+ if err != nil {
55
+ t.Fatal(err)
56
+ }
57
+ return wrap(c)
58
+ })
59
+ })
60
+ }
61
+
62
+ var aesGCMTests = []struct {
63
+ key, nonce, plaintext, ad, result string
64
+ }{
65
+ { // key=16, plaintext=null
66
+ "11754cd72aec309bf52f7687212e8957",
67
+ "3c819d9a9bed087615030b65",
68
+ "",
69
+ "",
70
+ "250327c674aaf477aef2675748cf6971",
71
+ },
72
+ { // key=24, plaintext=null
73
+ "e2e001a36c60d2bf40d69ff5b2b1161ea218db263be16a4e",
74
+ "3c819d9a9bed087615030b65",
75
+ "",
76
+ "",
77
+ "c7b8da1fe2e3dccc4071ba92a0a57ba8",
78
+ },
79
+ { // key=32, plaintext=null
80
+ "5394e890d37ba55ec9d5f327f15680f6a63ef5279c79331643ad0af6d2623525",
81
+ "3c819d9a9bed087615030b65",
82
+ "",
83
+ "",
84
+ "d9b260d4bc4630733ffb642f5ce45726",
85
+ },
86
+ {
87
+ "ca47248ac0b6f8372a97ac43508308ed",
88
+ "ffd2b598feabc9019262d2be",
89
+ "",
90
+ "",
91
+ "60d20404af527d248d893ae495707d1a",
92
+ },
93
+ {
94
+ "fbe3467cc254f81be8e78d765a2e6333",
95
+ "c6697351ff4aec29cdbaabf2",
96
+ "",
97
+ "67",
98
+ "3659cdc25288bf499ac736c03bfc1159",
99
+ },
100
+ {
101
+ "8a7f9d80d08ad0bd5a20fb689c88f9fc",
102
+ "88b7b27d800937fda4f47301",
103
+ "",
104
+ "50edd0503e0d7b8c91608eb5a1",
105
+ "ed6f65322a4740011f91d2aae22dd44e",
106
+ },
107
+ {
108
+ "051758e95ed4abb2cdc69bb454110e82",
109
+ "c99a66320db73158a35a255d",
110
+ "",
111
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339f",
112
+ "6ce77f1a5616c505b6aec09420234036",
113
+ },
114
+ {
115
+ "77be63708971c4e240d1cb79e8d77feb",
116
+ "e0e00f19fed7ba0136a797f3",
117
+ "",
118
+ "7a43ec1d9c0a5a78a0b16533a6213cab",
119
+ "209fcc8d3675ed938e9c7166709dd946",
120
+ },
121
+ {
122
+ "7680c5d3ca6154758e510f4d25b98820",
123
+ "f8f105f9c3df4965780321f8",
124
+ "",
125
+ "c94c410194c765e3dcc7964379758ed3",
126
+ "94dca8edfcf90bb74b153c8d48a17930",
127
+ },
128
+
129
+ { // key=16, plaintext=16
130
+ "7fddb57453c241d03efbed3ac44e371c",
131
+ "ee283a3fc75575e33efd4887",
132
+ "d5de42b461646c255c87bd2962d3b9a2",
133
+ "",
134
+ "2ccda4a5415cb91e135c2a0f78c9b2fdb36d1df9b9d5e596f83e8b7f52971cb3",
135
+ },
136
+ {
137
+ "ab72c77b97cb5fe9a382d9fe81ffdbed",
138
+ "54cc7dc2c37ec006bcc6d1da",
139
+ "007c5e5b3e59df24a7c355584fc1518d",
140
+ "",
141
+ "0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c",
142
+ },
143
+ { // key=24, plaintext=16
144
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
145
+ "54cc7dc2c37ec006bcc6d1da",
146
+ "007c5e5b3e59df24a7c355584fc1518d",
147
+ "",
148
+ "7bd53594c28b6c6596feb240199cad4c9badb907fd65bde541b8df3bd444d3a8",
149
+ },
150
+ { // key=32, plaintext=16
151
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
152
+ "54cc7dc2c37ec006bcc6d1da",
153
+ "007c5e5b3e59df24a7c355584fc1518d",
154
+ "",
155
+ "d50b9e252b70945d4240d351677eb10f937cdaef6f2822b6a3191654ba41b197",
156
+ },
157
+ { // key=16, plaintext=23
158
+ "ab72c77b97cb5fe9a382d9fe81ffdbed",
159
+ "54cc7dc2c37ec006bcc6d1da",
160
+ "007c5e5b3e59df24a7c355584fc1518dabcdefab",
161
+ "",
162
+ "0e1bde206a07a9c2c1b65300f8c64997b73381a6ff6bc24c5146fbd73361f4fe",
163
+ },
164
+ { // key=24, plaintext=23
165
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
166
+ "54cc7dc2c37ec006bcc6d1da",
167
+ "007c5e5b3e59df24a7c355584fc1518dabcdefab",
168
+ "",
169
+ "7bd53594c28b6c6596feb240199cad4c23b86a96d423cffa929e68541dc16b28",
170
+ },
171
+ { // key=32, plaintext=23
172
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
173
+ "54cc7dc2c37ec006bcc6d1da",
174
+ "007c5e5b3e59df24a7c355584fc1518dabcdefab",
175
+ "",
176
+ "d50b9e252b70945d4240d351677eb10f27fd385388ad3b72b96a2d5dea1240ae",
177
+ },
178
+
179
+ { // key=16, plaintext=51
180
+ "fe47fcce5fc32665d2ae399e4eec72ba",
181
+ "5adb9609dbaeb58cbd6e7275",
182
+ "7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1b840382c4bccaf3bafb4ca8429bea063",
183
+ "88319d6e1d3ffa5f987199166c8a9b56c2aeba5a",
184
+ "98f4826f05a265e6dd2be82db241c0fbbbf9ffb1c173aa83964b7cf5393043736365253ddbc5db8778371495da76d269e5db3e291ef1982e4defedaa2249f898556b47",
185
+ },
186
+ {
187
+ "ec0c2ba17aa95cd6afffe949da9cc3a8",
188
+ "296bce5b50b7d66096d627ef",
189
+ "b85b3753535b825cbe5f632c0b843c741351f18aa484281aebec2f45bb9eea2d79d987b764b9611f6c0f8641843d5d58f3a242",
190
+ "f8d00f05d22bf68599bcdeb131292ad6e2df5d14",
191
+ "a7443d31c26bdf2a1c945e29ee4bd344a99cfaf3aa71f8b3f191f83c2adfc7a07162995506fde6309ffc19e716eddf1a828c5a890147971946b627c40016da1ecf3e77",
192
+ },
193
+ {
194
+ "2c1f21cf0f6fb3661943155c3e3d8492",
195
+ "23cb5ff362e22426984d1907",
196
+ "42f758836986954db44bf37c6ef5e4ac0adaf38f27252a1b82d02ea949c8a1a2dbc0d68b5615ba7c1220ff6510e259f06655d8",
197
+ "5d3624879d35e46849953e45a32a624d6a6c536ed9857c613b572b0333e701557a713e3f010ecdf9a6bd6c9e3e44b065208645aff4aabee611b391528514170084ccf587177f4488f33cfb5e979e42b6e1cfc0a60238982a7aec",
198
+ "81824f0e0d523db30d3da369fdc0d60894c7a0a20646dd015073ad2732bd989b14a222b6ad57af43e1895df9dca2a5344a62cc57a3ee28136e94c74838997ae9823f3a",
199
+ },
200
+ {
201
+ "d9f7d2411091f947b4d6f1e2d1f0fb2e",
202
+ "e1934f5db57cc983e6b180e7",
203
+ "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490c2c6f6166f4a59431e182663fcaea05a",
204
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
205
+ "aaadbd5c92e9151ce3db7210b8714126b73e43436d242677afa50384f2149b831f1d573c7891c2a91fbc48db29967ec9542b2321b51ca862cb637cdd03b99a0f93b134",
206
+ },
207
+ { //key=24 plaintext=51
208
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
209
+ "e1934f5db57cc983e6b180e7",
210
+ "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490c2c6f6166f4a59431e182663fcaea05a",
211
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
212
+ "0736378955001d50773305975b3a534a4cd3614dd7300916301ae508cb7b45aa16e79435ca16b5557bcad5991bc52b971806863b15dc0b055748919b8ee91bc8477f68",
213
+ },
214
+ { //key-32 plaintext=51
215
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
216
+ "e1934f5db57cc983e6b180e7",
217
+ "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490c2c6f6166f4a59431e182663fcaea05a",
218
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
219
+ "fc1ae2b5dcd2c4176c3f538b4c3cc21197f79e608cc3730167936382e4b1e5a7b75ae1678bcebd876705477eb0e0fdbbcda92fb9a0dc58c8d8f84fb590e0422e6077ef",
220
+ },
221
+ { //key=16 plaintext=138
222
+ "d9f7d2411091f947b4d6f1e2d1f0fb2e",
223
+ "e1934f5db57cc983e6b180e7",
224
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3aabbccddee",
225
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
226
+ "be86d00ce4e150190f646eae0f670ad26b3af66db45d2ee3fd71badd2fe763396bdbca498f3f779c70b80ed2695943e15139b406e5147b3855a1441dfb7bd64954b581e3db0ddf26b1c759e2276a4c18a8e4ad4b890f473e61c78e60074bd0633961e87e66d0a1be77c51ab6b9bb3318ccdd43794ffc18a03a83c1d368eeea590a13407c7ef48efc66e26047f3ab9deed0412ce89e",
227
+ },
228
+ { //key=24 plaintext=138
229
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
230
+ "e1934f5db57cc983e6b180e7",
231
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3aabbccddee",
232
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
233
+ "131d5ad9230858559b8c1929ec2c18be90d7d4630e49018262ce5c511688bd10622109403db8006014ce93905b0a16bf1d1411acc9e14edf09518bd5967ff4bc202805d4c2810810a093e996a0f56c9a3e3e593c783f68528c1a282ff6f4925902bb2b3d4cdd04b873663bf5fd9dd53b5df462e0424d038f249b10a99c0523200f8c92c3e8a178a25ee8e23b71308c88ec2cfe047e",
234
+ },
235
+ { //key-32 plaintext=138
236
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
237
+ "e1934f5db57cc983e6b180e7",
238
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3aabbccddee",
239
+ "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8",
240
+ "e8318fe5aada811280804f35fb2a89e54bf32b4e55ba7b953547dadb39421d1dc39c7c127c6008b208010177f02fc093c8bbb8b3834d0e060d96dda96ba386c7c01224a4cac1edebffda4f9a64692bfbffb9f7c2999069fab84205224978a10d815d5ab8fa31e4e11630ba01c3b6cb99bef5772357ce86b83b4fb45ea7146402d560b6ad07de635b9366865e788a6bcdb132dcd079",
241
+ },
242
+ { // key=16, plaintext=13
243
+ "fe9bb47deb3a61e423c2231841cfd1fb",
244
+ "4d328eb776f500a2f7fb47aa",
245
+ "f1cc3818e421876bb6b8bbd6c9",
246
+ "",
247
+ "b88c5c1977b35b517b0aeae96743fd4727fe5cdb4b5b42818dea7ef8c9",
248
+ },
249
+ { // key=16, plaintext=13
250
+ "6703df3701a7f54911ca72e24dca046a",
251
+ "12823ab601c350ea4bc2488c",
252
+ "793cd125b0b84a043e3ac67717",
253
+ "",
254
+ "b2051c80014f42f08735a7b0cd38e6bcd29962e5f2c13626b85a877101",
255
+ },
256
+ { // key=24, plaintext=13
257
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
258
+ "12823ab601c350ea4bc2488c",
259
+ "793cd125b0b84a043e3ac67717",
260
+ "",
261
+ "e888c2f438caedd4189d26c59f53439b8a7caec29e98c33ebf7e5712d6",
262
+ },
263
+ { // key=32, plaintext=13
264
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
265
+ "12823ab601c350ea4bc2488c",
266
+ "793cd125b0b84a043e3ac67717",
267
+ "",
268
+ "e796c39074c7783a38193e3f8d46b355adacca7198d16d879fbfeac6e3",
269
+ },
270
+
271
+ // These cases test non-standard nonce sizes.
272
+ { // key=16, plaintext=0
273
+ "1672c3537afa82004c6b8a46f6f0d026",
274
+ "05",
275
+ "",
276
+ "",
277
+ "8e2ad721f9455f74d8b53d3141f27e8e",
278
+ },
279
+ { //key=16, plaintext=32
280
+ "9a4fea86a621a91ab371e492457796c0",
281
+ "75",
282
+ "ca6131faf0ff210e4e693d6c31c109fc5b6f54224eb120f37de31dc59ec669b6",
283
+ "4f6e2585c161f05a9ae1f2f894e9f0ab52b45d0f",
284
+ "5698c0a384241d30004290aac56bb3ece6fe8eacc5c4be98954deb9c3ff6aebf5d50e1af100509e1fba2a5e8a0af9670",
285
+ },
286
+ { //key=24, plaintext=32
287
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
288
+ "75",
289
+ "ca6131faf0ff210e4e693d6c31c109fc5b6f54224eb120f37de31dc59ec669b6",
290
+ "4f6e2585c161f05a9ae1f2f894e9f0ab52b45d0f",
291
+ "2709b357ec8334a074dbd5c4c352b216cfd1c8bd66343c5d43bfc6bd3b2b6cd0e3a82315d56ea5e4961c9ef3bc7e4042",
292
+ },
293
+ { //key=32, plaintext=32
294
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
295
+ "75",
296
+ "ca6131faf0ff210e4e693d6c31c109fc5b6f54224eb120f37de31dc59ec669b6",
297
+ "4f6e2585c161f05a9ae1f2f894e9f0ab52b45d0f",
298
+ "d73bebe722c5e312fe910ba71d5a6a063a4297203f819103dfa885a8076d095545a999affde3dbac2b5be6be39195ed0",
299
+ },
300
+ { // key=16, plaintext=0
301
+ "d0f1f4defa1e8c08b4b26d576392027c",
302
+ "42b4f01eb9f5a1ea5b1eb73b0fb0baed54f387ecaa0393c7d7dffc6af50146ecc021abf7eb9038d4303d91f8d741a11743166c0860208bcc02c6258fd9511a2fa626f96d60b72fcff773af4e88e7a923506e4916ecbd814651e9f445adef4ad6a6b6c7290cc13b956130eef5b837c939fcac0cbbcc9656cd75b13823ee5acdac",
303
+ "",
304
+ "",
305
+ "7ab49b57ddf5f62c427950111c5c4f0d",
306
+ },
307
+ { //key=16, plaintext=13
308
+ "4a0c00a3d284dea9d4bf8b8dde86685e",
309
+ "f8cbe82588e784bcacbe092cd9089b51e01527297f635bf294b3aa787d91057ef23869789698ac960707857f163ecb242135a228ad93964f5dc4a4d7f88fd7b3b07dd0a5b37f9768fb05a523639f108c34c661498a56879e501a2321c8a4a94d7e1b89db255ac1f685e185263368e99735ebe62a7f2931b47282be8eb165e4d7",
310
+ "6d4bf87640a6a48a50d28797b7",
311
+ "8d8c7ffc55086d539b5a8f0d1232654c",
312
+ "0d803ec309482f35b8e6226f2b56303239298e06b281c2d51aaba3c125",
313
+ },
314
+ { //key=16, plaintext=128
315
+ "0e18a844ac5bf38e4cd72d9b0942e506",
316
+ "0870d4b28a2954489a0abcd5",
317
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3",
318
+ "05eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea9",
319
+ "cace28f4976afd72e3c5128167eb788fbf6634dda0a2f53148d00f6fa557f5e9e8f736c12e450894af56cb67f7d99e1027258c8571bd91ee3b7360e0d508aa1f382411a16115f9c05251cc326d4016f62e0eb8151c048465b0c6c8ff12558d43310e18b2cb1889eec91557ce21ba05955cf4c1d4847aadfb1b0a83f3a3b82b7efa62a5f03c5d6eda381a85dd78dbc55c",
320
+ },
321
+ { //key=24, plaintext=128
322
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
323
+ "0870d4b28a2954489a0abcd5",
324
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3",
325
+ "05eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea9",
326
+ "303157d398376a8d51e39eabdd397f45b65f81f09acbe51c726ae85867e1675cad178580bb31c7f37c1af3644bd36ac436e9459139a4903d95944f306e415da709134dccde9d2b2d7d196b6740c196d9d10caa45296cf577a6e15d7ddf3576c20c503617d6a9e6b6d2be09ae28410a1210700a463a5b3b8d391abe9dac217e76a6f78306b5ebe759a5986b7d6682db0b",
327
+ },
328
+ { //key=32, plaintext=128
329
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
330
+ "0870d4b28a2954489a0abcd5",
331
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b3",
332
+ "05eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea9",
333
+ "e4f13934744125b9c35935ed4c5ac7d0c16434d52eadef1da91c6abb62bc757f01e3e42f628f030d750826adceb961f0675b81de48376b181d8781c6a0ccd0f34872ef6901b97ff7c2e152426b3257fb91f6a43f47befaaf7a2136fd0c97de8c48517ce047a5641141092c717b151b44f0794a164b5861f0a77271d1bdbc332e9e43d3b9828ccfdbd4ae338da5baf7a9",
334
+ },
335
+
336
+ { //key=16, plaintext=512
337
+ "1f6c3a3bc0542aabba4ef8f6c7169e73",
338
+ "f3584606472b260e0dd2ebb2",
339
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525cf08f5e9e25e5360aad2b2d085fa54d835e8d466826498d9a8877565705a8a3f62802944de7ca5894e5759d351adac869580ec17e485f18c0c66f17cc07cbb22fce466da610b63af62bc83b4692f3affaf271693ac071fb86d11342d8def4f89d4b66335c1c7e4248367d8ed9612ec453902d8e50af89d7709d1a596c1f41f",
340
+ "95aa82ca6c49ae90cd1668baac7aa6f2b4a8ca99b2c2372acb08cf61c9c3805e6e0328da4cd76a19edd2d3994c798b0022569ad418d1fee4d9cd45a391c601ffc92ad91501432fee150287617c13629e69fc7281cd7165a63eab49cf714bce3a75a74f76ea7e64ff81eb61fdfec39b67bf0de98c7e4e32bdf97c8c6ac75ba43c02f4b2ed7216ecf3014df000108b67cf99505b179f8ed4980a6103d1bca70dbe9bbfab0ed59801d6e5f2d6f67d3ec5168e212e2daf02c6b963c98a1f7097de0c56891a2b211b01070dd8fd8b16c2a1a4e3cfd292d2984b3561d555d16c33ddc2bcf7edde13efe520c7e2abdda44d81881c531aeeeb66244c3b791ea8acfb6a68",
341
+ "55864065117e07650ca650a0f0d9ef4b02aee7c58928462fddb49045bf85355b4653fa26158210a7f3ef5b3ca48612e8b7adf5c025c1b821960af770d935df1c9a1dd25077d6b1c7f937b2e20ce981b07980880214698f3fad72fa370b3b7da257ce1d0cf352bc5304fada3e0f8927bd4e5c1abbffa563bdedcb567daa64faaed748cb361732200ba3506836a3c1c82aafa14c76dc07f6c4277ff2c61325f91fdbd6c1883e745fcaadd5a6d692eeaa5ad56eead6a9d74a595d22757ed89532a4b8831e2b9e2315baea70a9b95d228f09d491a5ed5ab7076766703457e3159bbb9b17b329525669863153079448c68cd2f200c0be9d43061a60639cb59d50993d276c05caaa565db8ce633b2673e4012bebbca02b1a64d779d04066f3e949ece173825885ec816468c819a8129007cc05d8785c48077d09eb1abcba14508dde85a6f16a744bc95faef24888d53a8020515ab20307efaecbdf143a26563c67989bceedc2d6d2bb9699bb6c615d93767e4158c1124e3b6c723aaa47796e59a60d3696cd85adfae9a62f2c02c22009f80ed494bdc587f31dd892c253b5c6d6b7db078fa72d23474ee54f8144d6561182d71c862941dbc0b2cb37a4d4b23cbad5637e6be901cc73f16d5aec39c60dddee631511e57b47520b61ae1892d2d1bd2b486e30faec892f171b6de98d96108016fac805604761f8e74742b3bb7dc8a290a46bf697c3e4446e6e65832cbae7cf1aaad1",
342
+ },
343
+ { //key=24, plaintext=512
344
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c",
345
+ "f3584606472b260e0dd2ebb2",
346
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525cf08f5e9e25e5360aad2b2d085fa54d835e8d466826498d9a8877565705a8a3f62802944de7ca5894e5759d351adac869580ec17e485f18c0c66f17cc07cbb22fce466da610b63af62bc83b4692f3affaf271693ac071fb86d11342d8def4f89d4b66335c1c7e4248367d8ed9612ec453902d8e50af89d7709d1a596c1f41f",
347
+ "95aa82ca6c49ae90cd1668baac7aa6f2b4a8ca99b2c2372acb08cf61c9c3805e6e0328da4cd76a19edd2d3994c798b0022569ad418d1fee4d9cd45a391c601ffc92ad91501432fee150287617c13629e69fc7281cd7165a63eab49cf714bce3a75a74f76ea7e64ff81eb61fdfec39b67bf0de98c7e4e32bdf97c8c6ac75ba43c02f4b2ed7216ecf3014df000108b67cf99505b179f8ed4980a6103d1bca70dbe9bbfab0ed59801d6e5f2d6f67d3ec5168e212e2daf02c6b963c98a1f7097de0c56891a2b211b01070dd8fd8b16c2a1a4e3cfd292d2984b3561d555d16c33ddc2bcf7edde13efe520c7e2abdda44d81881c531aeeeb66244c3b791ea8acfb6a68",
348
+ "9daa466c7174dfde72b435fb6041ed7ff8ab8b1b96edb90437c3cc2e7e8a7c2c3629bae3bcaede99ee926ef4c55571e504e1c516975f6c719611c4da74acc23bbc79b3a67491f84d573e0293aa0cf5d775dde93fc466d5babd3e93a6506c0261021ac184f571ab190df83c32b41a67eaaa8dde27c02b08f15cabc75e46d1f9634f32f9233b2cb975386ff3a5e16b6ea2e2e4215cb33beb4de39a861d7f4a02165cd763f8252b2d60ac45d65a70735a8806a8fec3ca9d37c2cdcb21d2bd5c08d350e4bbdfb11dca344b9bee17e71ee0df3449fd9f9581c6b5483843b457534afb4240585f38ac22aa59a68a167fed6f1be0a5b072b2461f16c976b9aa0f5f2f5988818b01faa025ac7788212d92d222f7c14fe6e8f644c8cd117bb8def5a0217dad4f05cbb334ff9ccf819a4a085ed7c19928ddc40edc931b47339f456ccd423b5c0c1cdc96278006b29de945cdceb0737771e14562fff2aba40606f6046da5031647308682060412812317962bb68be3b42876f0905d52da51ec6345677fe86613828f488cc5685a4b973e48babd109a56d1a1effb286133dc2a94b4ada5707d3a7825941fea1a7502693afc7fe5d810bb0050d98aa6b80801e13b563954a35c31f57d5ba1ddb1a2be26426e2fe7bcd13ba183d80ac1c556b7ec2069b01de1450431a1c2e27848e1f5f4af013bce9080aebd2bb0f1de9f7bb460771c266d48ff4cf84a66f82630657db861c032971079",
349
+ },
350
+ { //key=32, plaintext=512
351
+ "feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
352
+ "f3584606472b260e0dd2ebb2",
353
+ "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525cf08f5e9e25e5360aad2b2d085fa54d835e8d466826498d9a8877565705a8a3f62802944de7ca5894e5759d351adac869580ec17e485f18c0c66f17cc07cbb22fce466da610b63af62bc83b4692f3affaf271693ac071fb86d11342d8def4f89d4b66335c1c7e4248367d8ed9612ec453902d8e50af89d7709d1a596c1f41f",
354
+ "95aa82ca6c49ae90cd1668baac7aa6f2b4a8ca99b2c2372acb08cf61c9c3805e6e0328da4cd76a19edd2d3994c798b0022569ad418d1fee4d9cd45a391c601ffc92ad91501432fee150287617c13629e69fc7281cd7165a63eab49cf714bce3a75a74f76ea7e64ff81eb61fdfec39b67bf0de98c7e4e32bdf97c8c6ac75ba43c02f4b2ed7216ecf3014df000108b67cf99505b179f8ed4980a6103d1bca70dbe9bbfab0ed59801d6e5f2d6f67d3ec5168e212e2daf02c6b963c98a1f7097de0c56891a2b211b01070dd8fd8b16c2a1a4e3cfd292d2984b3561d555d16c33ddc2bcf7edde13efe520c7e2abdda44d81881c531aeeeb66244c3b791ea8acfb6a68",
355
+ "793d34afb982ab70b0e204e1e7243314a19e987d9ab7662f58c3dc6064c9be35667ad53b115c610cfc229f4e5b3e8aae7aac97ce66d1d20b92da3860701b5006dd1385e173e3af7a5a9bb7da85c0434cd55a40fb9c482a0b36f0782846a7f16d05b40a08f0ad9a633f9a1e99e69e6b8039a0f2a91be40f193f4ce3bed1886dab1b0a6112f91503684c1e5afb938b9497166a7147badd1cc19c73e8b9f22e0dcbd18996868d7ad47755e677ee6e6ec87094cab7ee35feb96017c474261ba7391b18a72451e6daa7f38e162358c5d84788c974e614acc362b887c56b756df5aeacdda09b11d35a1f97daaceb5ca1b40a78b6058f7e1d26ad945be6ef74a8e72729f9ab2e3e7dda88d8f803e26e84a34ac07a7cecf5b6be23a4aa1ac6897f23169d894d53369b27673cf2438af9c6b53a2fa412c74dc075c617029e571f4c2951b1cdd63d33765af9d9d20e12430a83784c2bca8603f11521fa97f2e45398b4a385176701c6f416720ca0816bf51a3e0b4c7a28a89f0616a296423760f0f2f471e1def8a2f43956f79790a6b64dfdbb8159236ebd7fe1049e8e005e231e5f1936bfdccbda8cf0cb5116af758dfd6732dfa77ac3e6faf0996c13473292da363f01ddcb6a524dbf1d5d608f57c146173a9b169f979e101fe581f749764fd87119ae301958c8e9a9bfd16249e564ffbb304bc2ca4c34713a20fb858b47c83ce768e04f149884504c0515345631401f829e3259",
356
+ },
357
+
358
+ { //key=16, plaintext=293
359
+ "0795d80bc7f40f4d41c280271a2e4f7f",
360
+ "ff824c906594aff365d3cb1f",
361
+ "1ad4e74d127f935beee57cff920665babe7ce56227377afe570ba786193ded3412d4812453157f42fafc418c02a746c1232c234a639d49baa8f041c12e2ef540027764568ce49886e0d913e28059a3a485c6eee96337a30b28e4cd5612c2961539fa6bc5de034cbedc5fa15db844013e0bef276e27ca7a4faf47a5c1093bd643354108144454d221b3737e6cb87faac36ed131959babe44af2890cfcc4e23ffa24470e689ce0894f5407bb0c8665cff536008ad2ac6f1c9ef8289abd0bd9b72f21c597bda5210cf928c805af2dd4a464d52e36819d521f967bba5386930ab5b4cf4c71746d7e6e964673457348e9d71d170d9eb560bd4bdb779e610ba816bf776231ebd0af5966f5cdab6815944032ab4dd060ad8dab880549e910f1ffcf6862005432afad",
362
+ "98a47a430d8fd74dc1829a91e3481f8ed024d8ba34c9b903321b04864db333e558ae28653dffb2",
363
+ "3b8f91443480e647473a0a0b03d571c622b7e70e4309a02c9bb7980053010d865e6aec161354dc9f481b2cd5213e09432b57ec4e58fbd0a8549dd15c8c4e74a6529f75fad0ce5a9e20e2beeb2f91eb638bf88999968de438d2f1cedbfb0a1c81f9e8e7362c738e0fddd963692a4f4df9276b7f040979ce874cf6fa3de26da0713784bdb25e4efcb840554ef5b38b5fe8380549a496bd8e423a7456df6f4ae78a07ebe2276a8e22fc2243ec4f78abe0c99c733fd67c8c492699fa5ee2289cdd0a8d469bf883520ee74efb854bfadc7366a49ee65ca4e894e3335e2b672618d362eee12a577dd8dc2ba55c49c1fc3ad68180e9b112d0234d4aa28f5661f1e036450ca6f18be0166676bd80f8a4890c6ddea306fabb7ff3cb2860aa32a827e3a312912a2dfa70f6bc1c07de238448f2d751bd0cf15bf7",
364
+ },
365
+ { //key=24, plaintext=293
366
+ "e2e001a36c60d2bf40d69ff5b2b1161ea218db263be16a4e",
367
+ "84230643130d05425826641e",
368
+ "adb034f3f4a7ca45e2993812d113a9821d50df151af978bccc6d3bc113e15bc0918fb385377dca1916022ce816d56a332649484043c0fc0f2d37d040182b00a9bbb42ef231f80b48fb3730110d9a4433e38c73264c703579a705b9c031b969ec6d98de9f90e9e78b21179c2eb1e061946cd4bbb844f031ecf6eaac27a4151311adf1b03eda97c9fbae66295f468af4b35faf6ba39f9d8f95873bbc2b51cf3dfec0ed3c9b850696336cc093b24a8765a936d14dd56edc6bf518272169f75e67b74ba452d0aae90416a997c8f31e2e9d54ffea296dc69462debc8347b3e1af6a2d53bdfdfda601134f98db42b609df0a08c9347590c8d86e845bb6373d65a26ab85f67b50569c85401a396b8ad76c2b53ff62bcfbf033e435ef47b9b591d05117c6dc681d68e",
369
+ "d5d7316b8fdee152942148bff007c22e4b2022c6bc7be3c18c5f2e52e004e0b5dc12206bf002bd",
370
+ "f2c39423ee630dfe961da81909159dba018ce09b1073a12a477108316af5b7a31f86be6a0548b572d604bd115ea737dde899e0bd7f7ac9b23e38910dc457551ecc15c814a9f46d8432a1a36097dc1afe2712d1ba0838fa88cb55d9f65a2e9bece0dbf8999562503989041a2c87d7eb80ef649769d2f4978ce5cf9664f2bd0849646aa81cb976e45e1ade2f17a8126219e917aadbb4bae5e2c4b3f57bbc7f13fcc807df7842d9727a1b389e0b749e5191482adacabd812627c6eae2c7a30caf0844ad2a22e08f39edddf0ae10413e47db433dfe3febbb5a5cec9ade21fbba1e548247579395880b747669a8eb7e2ec0c1bff7fed2defdb92b07a14edf07b1bde29c31ab052ff1214e6b5ebbefcb8f21b5d6f8f6e07ee57ad6e14d4e142cb3f51bb465ab3a28a2a12f01b7514ad0463f2bde0d71d221",
371
+ },
372
+ { //key=32, plaintext=293
373
+ "5394e890d37ba55ec9d5f327f15680f6a63ef5279c79331643ad0af6d2623525",
374
+ "815e840b7aca7af3b324583f",
375
+ "8e63067cd15359f796b43c68f093f55fdf3589fc5f2fdfad5f9d156668a617f7091d73da71cdd207810e6f71a165d0809a597df9885ca6e8f9bb4e616166586b83cc45f49917fc1a256b8bc7d05c476ab5c4633e20092619c4747b26dad3915e9fd65238ee4e5213badeda8a3a22f5efe6582d0762532026c89b4ca26fdd000eb45347a2a199b55b7790e6b1b2dba19833ce9f9522c0bcea5b088ccae68dd99ae0203c81b9f1dd3181c3e2339e83ccd1526b67742b235e872bea5111772aab574ae7d904d9b6355a79178e179b5ae8edc54f61f172bf789ea9c9af21f45b783e4251421b077776808f04972a5e801723cf781442378ce0e0568f014aea7a882dcbcb48d342be53d1c2ebfb206b12443a8a587cc1e55ca23beca385d61d0d03e9d84cbc1b0a",
376
+ "0feccdfae8ed65fa31a0858a1c466f79e8aa658c2f3ba93c3f92158b4e30955e1c62580450beff",
377
+ "b69a7e17bb5af688883274550a4ded0d1aff49a0b18343f4b382f745c163f7f714c9206a32a1ff012427e19431951edd0a755e5f491b0eedfd7df68bbc6085dd2888607a2f998c3e881eb1694109250db28291e71f4ad344a125624fb92e16ea9815047cd1111cabfdc9cb8c3b4b0f40aa91d31774009781231400789ed545404af6c3f76d07ddc984a7bd8f52728159782832e298cc4d529be96d17be898efd83e44dc7b0e2efc645849fd2bba61fef0ae7be0dcab233cc4e2b7ba4e887de9c64b97f2a1818aa54371a8d629dae37975f7784e5e3cc77055ed6e975b1e5f55e6bbacdc9f295ce4ada2c16113cd5b323cf78b7dde39f4a87aa8c141a31174e3584ccbd380cf5ec6d1dba539928b084fa9683e9c0953acf47cc3ac384a2c38914f1da01fb2cfd78905c2b58d36b2574b9df15535d82",
378
+ },
379
+ // These cases test non-standard tag sizes.
380
+ {
381
+ "89c54b0d3bc3c397d5039058c220685f",
382
+ "bc7f45c00868758d62d4bb4d",
383
+ "582670b0baf5540a3775b6615605bd05",
384
+ "48d16cda0337105a50e2ed76fd18e114",
385
+ "fc2d4c4eee2209ddbba6663c02765e6955e783b00156f5da0446e2970b877f",
386
+ },
387
+ {
388
+ "bad6049678bf75c9087b3e3ae7e72c13",
389
+ "a0a017b83a67d8f1b883e561",
390
+ "a1be93012f05a1958440f74a5311f4a1",
391
+ "f7c27b51d5367161dc2ff1e9e3edc6f2",
392
+ "36f032f7e3dc3275ca22aedcdc68436b99a2227f8bb69d45ea5d8842cd08",
393
+ },
394
+ {
395
+ "66a3c722ccf9709525650973ecc100a9",
396
+ "1621d42d3a6d42a2d2bf9494",
397
+ "61fa9dbbed2190fbc2ffabf5d2ea4ff8",
398
+ "d7a9b6523b8827068a6354a6d166c6b9",
399
+ "fef3b20f40e08a49637cc82f4c89b8603fd5c0132acfab97b5fff651c4",
400
+ },
401
+ {
402
+ "562ae8aadb8d23e0f271a99a7d1bd4d1",
403
+ "f7a5e2399413b89b6ad31aff",
404
+ "bbdc3504d803682aa08a773cde5f231a",
405
+ "2b9680b886b3efb7c6354b38c63b5373",
406
+ "e2b7e5ed5ff27fc8664148f5a628a46dcbf2015184fffb82f2651c36",
407
+ },
408
+ {
409
+ "11754cd72aec309bf52f7687212e8957",
410
+ "",
411
+ "",
412
+ "",
413
+ "250327c674aaf477aef2675748cf6971",
414
+ },
415
+ }
416
+
417
+ func TestAESGCM(t *testing.T) {
418
+ testAllImplementations(t, testAESGCM)
419
+ }
420
+
421
+ func testAESGCM(t *testing.T, newCipher func(key []byte) cipher.Block) {
422
+ for i, test := range aesGCMTests {
423
+ key, _ := hex.DecodeString(test.key)
424
+ aes := newCipher(key)
425
+
426
+ nonce, _ := hex.DecodeString(test.nonce)
427
+ plaintext, _ := hex.DecodeString(test.plaintext)
428
+ ad, _ := hex.DecodeString(test.ad)
429
+ tagSize := (len(test.result) - len(test.plaintext)) / 2
430
+
431
+ var err error
432
+ var aesgcm cipher.AEAD
433
+ switch {
434
+ // Handle non-standard tag sizes
435
+ case tagSize != 16:
436
+ aesgcm, err = cipher.NewGCMWithTagSize(aes, tagSize)
437
+ if err != nil {
438
+ t.Fatal(err)
439
+ }
440
+
441
+ // Handle 0 nonce size (expect error and continue)
442
+ case len(nonce) == 0:
443
+ aesgcm, err = cipher.NewGCMWithNonceSize(aes, 0)
444
+ if err == nil {
445
+ t.Fatal("expected error for zero nonce size")
446
+ }
447
+ continue
448
+
449
+ // Handle non-standard nonce sizes
450
+ case len(nonce) != 12:
451
+ aesgcm, err = cipher.NewGCMWithNonceSize(aes, len(nonce))
452
+ if err != nil {
453
+ t.Fatal(err)
454
+ }
455
+
456
+ default:
457
+ aesgcm, err = cipher.NewGCM(aes)
458
+ if err != nil {
459
+ t.Fatal(err)
460
+ }
461
+ }
462
+
463
+ ct := aesgcm.Seal(nil, nonce, plaintext, ad)
464
+ if ctHex := hex.EncodeToString(ct); ctHex != test.result {
465
+ t.Errorf("#%d: got %s, want %s", i, ctHex, test.result)
466
+ continue
467
+ }
468
+
469
+ plaintext2, err := aesgcm.Open(nil, nonce, ct, ad)
470
+ if err != nil {
471
+ t.Errorf("#%d: Open failed", i)
472
+ continue
473
+ }
474
+
475
+ if !bytes.Equal(plaintext, plaintext2) {
476
+ t.Errorf("#%d: plaintext's don't match: got %x vs %x", i, plaintext2, plaintext)
477
+ continue
478
+ }
479
+
480
+ if len(ad) > 0 {
481
+ ad[0] ^= 0x80
482
+ if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil {
483
+ t.Errorf("#%d: Open was successful after altering additional data", i)
484
+ }
485
+ ad[0] ^= 0x80
486
+ }
487
+
488
+ nonce[0] ^= 0x80
489
+ if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil {
490
+ t.Errorf("#%d: Open was successful after altering nonce", i)
491
+ }
492
+ nonce[0] ^= 0x80
493
+
494
+ ct[0] ^= 0x80
495
+ if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil {
496
+ t.Errorf("#%d: Open was successful after altering ciphertext", i)
497
+ }
498
+ ct[0] ^= 0x80
499
+ }
500
+ }
501
+
502
+ func TestGCMInvalidTagSize(t *testing.T) {
503
+ testAllImplementations(t, testGCMInvalidTagSize)
504
+ }
505
+
506
+ func testGCMInvalidTagSize(t *testing.T, newCipher func(key []byte) cipher.Block) {
507
+ key, _ := hex.DecodeString("ab72c77b97cb5fe9a382d9fe81ffdbed")
508
+ aes := newCipher(key)
509
+
510
+ for _, tagSize := range []int{0, 1, aes.BlockSize() + 1} {
511
+ aesgcm, err := cipher.NewGCMWithTagSize(aes, tagSize)
512
+ if aesgcm != nil || err == nil {
513
+ t.Fatalf("NewGCMWithTagSize was successful with an invalid %d-byte tag size", tagSize)
514
+ }
515
+ }
516
+ }
517
+
518
+ func TestTagFailureOverwrite(t *testing.T) {
519
+ testAllImplementations(t, testTagFailureOverwrite)
520
+ }
521
+
522
+ func testTagFailureOverwrite(t *testing.T, newCipher func(key []byte) cipher.Block) {
523
+ // The AESNI GCM code decrypts and authenticates concurrently and so
524
+ // overwrites the output buffer before checking the authentication tag.
525
+ // In order to be consistent across platforms, all implementations
526
+ // should do this and this test checks that.
527
+
528
+ key, _ := hex.DecodeString("ab72c77b97cb5fe9a382d9fe81ffdbed")
529
+ nonce, _ := hex.DecodeString("54cc7dc2c37ec006bcc6d1db")
530
+ ciphertext, _ := hex.DecodeString("0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c")
531
+
532
+ aes := newCipher(key)
533
+ aesgcm, _ := cipher.NewGCM(aes)
534
+
535
+ dst := make([]byte, len(ciphertext)-16)
536
+ for i := range dst {
537
+ dst[i] = 42
538
+ }
539
+
540
+ result, err := aesgcm.Open(dst[:0], nonce, ciphertext, nil)
541
+ if err == nil {
542
+ t.Fatal("Bad Open still resulted in nil error.")
543
+ }
544
+
545
+ if result != nil {
546
+ t.Fatal("Failed Open returned non-nil result.")
547
+ }
548
+
549
+ for i := range dst {
550
+ if dst[i] != 0 {
551
+ t.Fatal("Failed Open didn't zero dst buffer")
552
+ }
553
+ }
554
+ }
555
+
556
+ func TestGCMCounterWrap(t *testing.T) {
557
+ testAllImplementations(t, testGCMCounterWrap)
558
+ }
559
+
560
+ func testGCMCounterWrap(t *testing.T, newCipher func(key []byte) cipher.Block) {
561
+ // Test that the last 32-bits of the counter wrap correctly.
562
+ tests := []struct {
563
+ nonce, tag string
564
+ }{
565
+ {"0fa72e25", "37e1948cdfff09fbde0c40ad99fee4a7"}, // counter: 7eb59e4d961dad0dfdd75aaffffffff0
566
+ {"afe05cc1", "438f3aa9fee5e54903b1927bca26bbdf"}, // counter: 75d492a7e6e6bfc979ad3a8ffffffff4
567
+ {"9ffecbef", "7b88ca424df9703e9e8611071ec7e16e"}, // counter: c8bb108b0ecdc71747b9d57ffffffff5
568
+ {"ffc3e5b3", "38d49c86e0abe853ac250e66da54c01a"}, // counter: 706414d2de9b36ab3b900a9ffffffff6
569
+ {"cfdd729d", "e08402eaac36a1a402e09b1bd56500e8"}, // counter: cd0b96fe36b04e750584e56ffffffff7
570
+ {"010ae3d486", "5405bb490b1f95d01e2ba735687154bc"}, // counter: e36c18e69406c49722808104fffffff8
571
+ {"01b1107a9d", "939a585f342e01e17844627492d44dbf"}, // counter: e6d56eaf9127912b6d62c6dcffffffff
572
+ }
573
+ key := newCipher(make([]byte, 16))
574
+ plaintext := make([]byte, 16*17+1)
575
+ for i, test := range tests {
576
+ nonce, _ := hex.DecodeString(test.nonce)
577
+ want, _ := hex.DecodeString(test.tag)
578
+ aead, err := cipher.NewGCMWithNonceSize(key, len(nonce))
579
+ if err != nil {
580
+ t.Fatal(err)
581
+ }
582
+ got := aead.Seal(nil, nonce, plaintext, nil)
583
+ if !bytes.Equal(got[len(plaintext):], want) {
584
+ t.Errorf("test[%v]: got: %x, want: %x", i, got[len(plaintext):], want)
585
+ }
586
+ _, err = aead.Open(nil, nonce, got, nil)
587
+ if err != nil {
588
+ t.Errorf("test[%v]: authentication failed", i)
589
+ }
590
+ }
591
+ }
592
+
593
+ func TestGCMAsm(t *testing.T) {
594
+ // Create a new pair of AEADs, one using the assembly implementation
595
+ // and one using the generic Go implementation.
596
+ newAESGCM := func(key []byte) (asm, generic cipher.AEAD, err error) {
597
+ block, err := aes.NewCipher(key[:])
598
+ if err != nil {
599
+ return nil, nil, err
600
+ }
601
+ asm, err = cipher.NewGCM(block)
602
+ if err != nil {
603
+ return nil, nil, err
604
+ }
605
+ generic, err = cipher.NewGCM(wrap(block))
606
+ if err != nil {
607
+ return nil, nil, err
608
+ }
609
+ return asm, generic, nil
610
+ }
611
+
612
+ // check for assembly implementation
613
+ var key [16]byte
614
+ asm, generic, err := newAESGCM(key[:])
615
+ if err != nil {
616
+ t.Fatal(err)
617
+ }
618
+ if reflect.TypeOf(asm) == reflect.TypeOf(generic) {
619
+ t.Skipf("no assembly implementation of GCM")
620
+ }
621
+
622
+ // generate permutations
623
+ type pair struct{ align, length int }
624
+ lengths := []int{0, 156, 8192, 8193, 8208}
625
+ keySizes := []int{16, 24, 32}
626
+ alignments := []int{0, 1, 2, 3}
627
+ if testing.Short() {
628
+ keySizes = []int{16}
629
+ alignments = []int{1}
630
+ }
631
+ perms := make([]pair, 0)
632
+ for _, l := range lengths {
633
+ for _, a := range alignments {
634
+ if a != 0 && l == 0 {
635
+ continue
636
+ }
637
+ perms = append(perms, pair{align: a, length: l})
638
+ }
639
+ }
640
+
641
+ // run test for all permutations
642
+ test := func(ks int, pt, ad []byte) error {
643
+ key := make([]byte, ks)
644
+ if _, err := io.ReadFull(rand.Reader, key); err != nil {
645
+ return err
646
+ }
647
+ asm, generic, err := newAESGCM(key)
648
+ if err != nil {
649
+ return err
650
+ }
651
+ if _, err := io.ReadFull(rand.Reader, pt); err != nil {
652
+ return err
653
+ }
654
+ if _, err := io.ReadFull(rand.Reader, ad); err != nil {
655
+ return err
656
+ }
657
+ nonce := make([]byte, 12)
658
+ if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
659
+ return err
660
+ }
661
+ want := generic.Seal(nil, nonce, pt, ad)
662
+ got := asm.Seal(nil, nonce, pt, ad)
663
+ if !bytes.Equal(want, got) {
664
+ return errors.New("incorrect Seal output")
665
+ }
666
+ got, err = asm.Open(nil, nonce, want, ad)
667
+ if err != nil {
668
+ return errors.New("authentication failed")
669
+ }
670
+ if !bytes.Equal(pt, got) {
671
+ return errors.New("incorrect Open output")
672
+ }
673
+ return nil
674
+ }
675
+ for _, a := range perms {
676
+ ad := make([]byte, a.align+a.length)
677
+ ad = ad[a.align:]
678
+ for _, p := range perms {
679
+ pt := make([]byte, p.align+p.length)
680
+ pt = pt[p.align:]
681
+ for _, ks := range keySizes {
682
+ if err := test(ks, pt, ad); err != nil {
683
+ t.Error(err)
684
+ t.Errorf(" key size: %v", ks)
685
+ t.Errorf(" plaintext alignment: %v", p.align)
686
+ t.Errorf(" plaintext length: %v", p.length)
687
+ t.Errorf(" additionalData alignment: %v", a.align)
688
+ t.Fatalf(" additionalData length: %v", a.length)
689
+ }
690
+ }
691
+ }
692
+ }
693
+ }
694
+
695
+ // Test GCM against the general cipher.AEAD interface tester.
696
+ func TestGCMAEAD(t *testing.T) {
697
+ testAllImplementations(t, testGCMAEAD)
698
+ }
699
+
700
+ func testGCMAEAD(t *testing.T, newCipher func(key []byte) cipher.Block) {
701
+ minTagSize := 12
702
+
703
+ for _, keySize := range []int{128, 192, 256} {
704
+ // Use AES as underlying block cipher at different key sizes for GCM.
705
+ t.Run(fmt.Sprintf("AES-%d", keySize), func(t *testing.T) {
706
+ rng := newRandReader(t)
707
+
708
+ key := make([]byte, keySize/8)
709
+ rng.Read(key)
710
+
711
+ block := newCipher(key)
712
+
713
+ // Test GCM with the current AES block with the standard nonce and tag
714
+ // sizes.
715
+ cryptotest.TestAEAD(t, func() (cipher.AEAD, error) { return cipher.NewGCM(block) })
716
+
717
+ // Test non-standard tag sizes.
718
+ t.Run("MinTagSize", func(t *testing.T) {
719
+ cryptotest.TestAEAD(t, func() (cipher.AEAD, error) { return cipher.NewGCMWithTagSize(block, minTagSize) })
720
+ })
721
+
722
+ // Test non-standard nonce sizes.
723
+ for _, nonceSize := range []int{1, 16, 100} {
724
+ t.Run(fmt.Sprintf("NonceSize-%d", nonceSize), func(t *testing.T) {
725
+ cryptotest.TestAEAD(t, func() (cipher.AEAD, error) { return cipher.NewGCMWithNonceSize(block, nonceSize) })
726
+ })
727
+ }
728
+
729
+ // Test NewGCMWithRandomNonce.
730
+ t.Run("GCMWithRandomNonce", func(t *testing.T) {
731
+ if _, ok := block.(*wrapper); ok || boring.Enabled {
732
+ t.Skip("NewGCMWithRandomNonce requires an AES block cipher")
733
+ }
734
+ cryptotest.TestAEAD(t, func() (cipher.AEAD, error) { return cipher.NewGCMWithRandomNonce(block) })
735
+ })
736
+ })
737
+ }
738
+ }
739
+
740
+ func TestGCMExtraMethods(t *testing.T) {
741
+ testAllImplementations(t, func(t *testing.T, newCipher func([]byte) cipher.Block) {
742
+ t.Run("NewGCM", func(t *testing.T) {
743
+ a, _ := cipher.NewGCM(newCipher(make([]byte, 16)))
744
+ cryptotest.NoExtraMethods(t, &a)
745
+ })
746
+ t.Run("NewGCMWithTagSize", func(t *testing.T) {
747
+ a, _ := cipher.NewGCMWithTagSize(newCipher(make([]byte, 16)), 12)
748
+ cryptotest.NoExtraMethods(t, &a)
749
+ })
750
+ t.Run("NewGCMWithNonceSize", func(t *testing.T) {
751
+ a, _ := cipher.NewGCMWithNonceSize(newCipher(make([]byte, 16)), 12)
752
+ cryptotest.NoExtraMethods(t, &a)
753
+ })
754
+ t.Run("NewGCMWithRandomNonce", func(t *testing.T) {
755
+ block := newCipher(make([]byte, 16))
756
+ if _, ok := block.(*wrapper); ok || boring.Enabled {
757
+ t.Skip("NewGCMWithRandomNonce requires an AES block cipher")
758
+ }
759
+ a, _ := cipher.NewGCMWithRandomNonce(block)
760
+ cryptotest.NoExtraMethods(t, &a)
761
+ })
762
+ })
763
+ }
764
+
765
+ func TestGCMNoncesFIPSV1(t *testing.T) {
766
+ cryptotest.MustSupportFIPS140(t)
767
+ if !fips140.Enabled {
768
+ cmd := testenv.Command(t, testenv.Executable(t), "-test.run=^TestGCMNoncesFIPSV1$", "-test.v")
769
+ cmd.Env = append(cmd.Environ(), "GODEBUG=fips140=on")
770
+ out, err := cmd.CombinedOutput()
771
+ t.Logf("running with GODEBUG=fips140=on:\n%s", out)
772
+ if err != nil {
773
+ t.Errorf("fips140=on subprocess failed: %v", err)
774
+ }
775
+ return
776
+ }
777
+
778
+ tryNonce := func(aead cipher.AEAD, nonce []byte) bool {
779
+ fips140.ResetServiceIndicator()
780
+ aead.Seal(nil, nonce, []byte("x"), nil)
781
+ return fips140.ServiceIndicator()
782
+ }
783
+ expectOK := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
784
+ t.Helper()
785
+ if !tryNonce(aead, nonce) {
786
+ t.Errorf("expected service indicator true for %x", nonce)
787
+ }
788
+ }
789
+ expectPanic := func(t *testing.T, aead cipher.AEAD, nonce []byte) {
790
+ t.Helper()
791
+ defer func() {
792
+ t.Helper()
793
+ if recover() == nil {
794
+ t.Errorf("expected panic for %x", nonce)
795
+ }
796
+ }()
797
+ tryNonce(aead, nonce)
798
+ }
799
+
800
+ t.Run("NewGCMWithCounterNonce", func(t *testing.T) {
801
+ newGCM := func() cipher.AEAD {
802
+ key := make([]byte, 16)
803
+ block, _ := fipsaes.New(key)
804
+ aead, _ := gcm.NewGCMWithCounterNonce(block)
805
+ return aead
806
+ }
807
+
808
+ g := newGCM()
809
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
810
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})
811
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100})
812
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0})
813
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0})
814
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0})
815
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0})
816
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0})
817
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0})
818
+ expectOK(t, g, []byte{0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0})
819
+ // Changed name.
820
+ expectPanic(t, g, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
821
+
822
+ g = newGCM()
823
+ expectOK(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})
824
+ // Went down.
825
+ expectPanic(t, g, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
826
+
827
+ g = newGCM()
828
+ expectOK(t, g, []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
829
+ expectOK(t, g, []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13})
830
+ // Did not increment.
831
+ expectPanic(t, g, []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13})
832
+
833
+ g = newGCM()
834
+ expectOK(t, g, []byte{1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00})
835
+ expectOK(t, g, []byte{1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})
836
+ // Wrap is ok as long as we don't run out of values.
837
+ expectOK(t, g, []byte{1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0})
838
+ expectOK(t, g, []byte{1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe})
839
+ // Run out of counters.
840
+ expectPanic(t, g, []byte{1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff})
841
+
842
+ g = newGCM()
843
+ expectOK(t, g, []byte{1, 2, 3, 4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})
844
+ // Wrap with overflow.
845
+ expectPanic(t, g, []byte{1, 2, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0})
846
+ })
847
+
848
+ t.Run("NewGCMForSSH", func(t *testing.T) {
849
+ newGCM := func() cipher.AEAD {
850
+ key := make([]byte, 16)
851
+ block, _ := fipsaes.New(key)
852
+ aead, _ := gcm.NewGCMForSSH(block)
853
+ return aead
854
+ }
855
+ // incIV from x/crypto/ssh/cipher.go.
856
+ incIV := func(iv []byte) {
857
+ for i := 4 + 7; i >= 4; i-- {
858
+ iv[i]++
859
+ if iv[i] != 0 {
860
+ break
861
+ }
862
+ }
863
+ }
864
+
865
+ aead := newGCM()
866
+ iv := decodeHex(t, "11223344"+"0000000000000000")
867
+ expectOK(t, aead, iv)
868
+ incIV(iv)
869
+ expectOK(t, aead, iv)
870
+ iv = decodeHex(t, "11223344"+"fffffffffffffffe")
871
+ expectOK(t, aead, iv)
872
+ incIV(iv)
873
+ expectPanic(t, aead, iv)
874
+
875
+ // Wrapping is ok as long as we don't run out of values.
876
+ aead = newGCM()
877
+ iv = decodeHex(t, "11223344"+"fffffffffffffffe")
878
+ expectOK(t, aead, iv)
879
+ incIV(iv)
880
+ expectOK(t, aead, iv)
881
+ incIV(iv)
882
+ expectOK(t, aead, iv)
883
+ incIV(iv)
884
+ expectOK(t, aead, iv)
885
+
886
+ aead = newGCM()
887
+ iv = decodeHex(t, "11223344"+"aaaaaaaaaaaaaaaa")
888
+ expectOK(t, aead, iv)
889
+ iv = decodeHex(t, "11223344"+"ffffffffffffffff")
890
+ expectOK(t, aead, iv)
891
+ incIV(iv)
892
+ expectOK(t, aead, iv)
893
+ iv = decodeHex(t, "11223344"+"aaaaaaaaaaaaaaa8")
894
+ expectOK(t, aead, iv)
895
+ incIV(iv)
896
+ expectPanic(t, aead, iv)
897
+ iv = decodeHex(t, "11223344"+"bbbbbbbbbbbbbbbb")
898
+ expectPanic(t, aead, iv)
899
+ })
900
+ }
901
+
902
+ func decodeHex(t *testing.T, s string) []byte {
903
+ t.Helper()
904
+ b, err := hex.DecodeString(s)
905
+ if err != nil {
906
+ t.Fatal(err)
907
+ }
908
+ return b
909
+ }
go/src/crypto/cipher/io.go ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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 "io"
8
+
9
+ // The Stream* objects are so simple that all their members are public. Users
10
+ // can create them themselves.
11
+
12
+ // StreamReader wraps a [Stream] into an [io.Reader]. It calls XORKeyStream
13
+ // to process each slice of data which passes through.
14
+ type StreamReader struct {
15
+ S Stream
16
+ R io.Reader
17
+ }
18
+
19
+ func (r StreamReader) Read(dst []byte) (n int, err error) {
20
+ n, err = r.R.Read(dst)
21
+ r.S.XORKeyStream(dst[:n], dst[:n])
22
+ return
23
+ }
24
+
25
+ // StreamWriter wraps a [Stream] into an io.Writer. It calls XORKeyStream
26
+ // to process each slice of data which passes through. If any [StreamWriter.Write]
27
+ // call returns short then the StreamWriter is out of sync and must be discarded.
28
+ // A StreamWriter has no internal buffering; [StreamWriter.Close] does not need
29
+ // to be called to flush write data.
30
+ type StreamWriter struct {
31
+ S Stream
32
+ W io.Writer
33
+ Err error // unused
34
+ }
35
+
36
+ func (w StreamWriter) Write(src []byte) (n int, err error) {
37
+ c := make([]byte, len(src))
38
+ w.S.XORKeyStream(c, src)
39
+ n, err = w.W.Write(c)
40
+ if n != len(src) && err == nil { // should never happen
41
+ err = io.ErrShortWrite
42
+ }
43
+ return
44
+ }
45
+
46
+ // Close closes the underlying Writer and returns its Close return value, if the Writer
47
+ // is also an io.Closer. Otherwise it returns nil.
48
+ func (w StreamWriter) Close() error {
49
+ if c, ok := w.W.(io.Closer); ok {
50
+ return c.Close()
51
+ }
52
+ return nil
53
+ }
go/src/crypto/cipher/modes_test.go ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 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_test
6
+
7
+ import (
8
+ . "crypto/cipher"
9
+ "reflect"
10
+ "testing"
11
+ )
12
+
13
+ // Historically, crypto/aes's Block would implement some undocumented
14
+ // methods for crypto/cipher to use from NewCTR, NewCBCEncrypter, etc.
15
+ // This is no longer the case, but for now test that the mechanism is
16
+ // still working until we explicitly decide to remove it.
17
+
18
+ type block struct {
19
+ Block
20
+ }
21
+
22
+ func (block) BlockSize() int {
23
+ return 16
24
+ }
25
+
26
+ type specialCTR struct {
27
+ Stream
28
+ }
29
+
30
+ func (block) NewCTR(iv []byte) Stream {
31
+ return specialCTR{}
32
+ }
33
+
34
+ func TestCTRAble(t *testing.T) {
35
+ b := block{}
36
+ s := NewCTR(b, make([]byte, 16))
37
+ if _, ok := s.(specialCTR); !ok {
38
+ t.Errorf("NewCTR did not return specialCTR")
39
+ }
40
+ }
41
+
42
+ type specialCBC struct {
43
+ BlockMode
44
+ }
45
+
46
+ func (block) NewCBCEncrypter(iv []byte) BlockMode {
47
+ return specialCBC{}
48
+ }
49
+
50
+ func (block) NewCBCDecrypter(iv []byte) BlockMode {
51
+ return specialCBC{}
52
+ }
53
+
54
+ func TestCBCAble(t *testing.T) {
55
+ b := block{}
56
+ s := NewCBCEncrypter(b, make([]byte, 16))
57
+ if _, ok := s.(specialCBC); !ok {
58
+ t.Errorf("NewCBCEncrypter did not return specialCBC")
59
+ }
60
+ s = NewCBCDecrypter(b, make([]byte, 16))
61
+ if _, ok := s.(specialCBC); !ok {
62
+ t.Errorf("NewCBCDecrypter did not return specialCBC")
63
+ }
64
+ }
65
+
66
+ type specialGCM struct {
67
+ AEAD
68
+ }
69
+
70
+ func (block) NewGCM(nonceSize, tagSize int) (AEAD, error) {
71
+ return specialGCM{}, nil
72
+ }
73
+
74
+ func TestGCM(t *testing.T) {
75
+ b := block{}
76
+ s, err := NewGCM(b)
77
+ if err != nil {
78
+ t.Errorf("NewGCM failed: %v", err)
79
+ }
80
+ if _, ok := s.(specialGCM); !ok {
81
+ t.Errorf("NewGCM did not return specialGCM")
82
+ }
83
+ }
84
+
85
+ // TestNoExtraMethods makes sure we don't accidentally expose methods on the
86
+ // underlying implementations of modes.
87
+ func TestNoExtraMethods(t *testing.T) {
88
+ testAllImplementations(t, testNoExtraMethods)
89
+ }
90
+
91
+ func testNoExtraMethods(t *testing.T, newBlock func([]byte) Block) {
92
+ b := newBlock(make([]byte, 16))
93
+
94
+ ctr := NewCTR(b, make([]byte, 16))
95
+ ctrExpected := []string{"XORKeyStream"}
96
+ if got := exportedMethods(ctr); !reflect.DeepEqual(got, ctrExpected) {
97
+ t.Errorf("CTR: got %v, want %v", got, ctrExpected)
98
+ }
99
+
100
+ cbc := NewCBCEncrypter(b, make([]byte, 16))
101
+ cbcExpected := []string{"BlockSize", "CryptBlocks", "SetIV"}
102
+ if got := exportedMethods(cbc); !reflect.DeepEqual(got, cbcExpected) {
103
+ t.Errorf("CBC: got %v, want %v", got, cbcExpected)
104
+ }
105
+ cbc = NewCBCDecrypter(b, make([]byte, 16))
106
+ if got := exportedMethods(cbc); !reflect.DeepEqual(got, cbcExpected) {
107
+ t.Errorf("CBC: got %v, want %v", got, cbcExpected)
108
+ }
109
+
110
+ gcm, _ := NewGCM(b)
111
+ gcmExpected := []string{"NonceSize", "Open", "Overhead", "Seal"}
112
+ if got := exportedMethods(gcm); !reflect.DeepEqual(got, gcmExpected) {
113
+ t.Errorf("GCM: got %v, want %v", got, gcmExpected)
114
+ }
115
+ }
116
+
117
+ func exportedMethods(x any) []string {
118
+ var methods []string
119
+ v := reflect.ValueOf(x)
120
+ for i := 0; i < v.NumMethod(); i++ {
121
+ if v.Type().Method(i).IsExported() {
122
+ methods = append(methods, v.Type().Method(i).Name)
123
+ }
124
+ }
125
+ return methods
126
+ }
go/src/crypto/cipher/ofb.go ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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
+ // OFB (Output Feedback) Mode.
6
+
7
+ package cipher
8
+
9
+ import (
10
+ "crypto/internal/fips140/alias"
11
+ "crypto/internal/fips140only"
12
+ "crypto/subtle"
13
+ )
14
+
15
+ type ofb struct {
16
+ b Block
17
+ cipher []byte
18
+ out []byte
19
+ outUsed int
20
+ }
21
+
22
+ // NewOFB returns a [Stream] that encrypts or decrypts using the block cipher b
23
+ // in output feedback mode. The initialization vector iv's length must be equal
24
+ // to b's block size.
25
+ //
26
+ // Deprecated: OFB mode is not authenticated, which generally enables active
27
+ // attacks to manipulate and recover the plaintext. It is recommended that
28
+ // applications use [AEAD] modes instead. The standard library implementation of
29
+ // OFB is also unoptimized and not validated as part of the FIPS 140-3 module.
30
+ // If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
31
+ func NewOFB(b Block, iv []byte) Stream {
32
+ if fips140only.Enforced() {
33
+ panic("crypto/cipher: use of OFB is not allowed in FIPS 140-only mode")
34
+ }
35
+
36
+ blockSize := b.BlockSize()
37
+ if len(iv) != blockSize {
38
+ panic("cipher.NewOFB: IV length must equal block size")
39
+ }
40
+ bufSize := streamBufferSize
41
+ if bufSize < blockSize {
42
+ bufSize = blockSize
43
+ }
44
+ x := &ofb{
45
+ b: b,
46
+ cipher: make([]byte, blockSize),
47
+ out: make([]byte, 0, bufSize),
48
+ outUsed: 0,
49
+ }
50
+
51
+ copy(x.cipher, iv)
52
+ return x
53
+ }
54
+
55
+ func (x *ofb) refill() {
56
+ bs := x.b.BlockSize()
57
+ remain := len(x.out) - x.outUsed
58
+ if remain > x.outUsed {
59
+ return
60
+ }
61
+ copy(x.out, x.out[x.outUsed:])
62
+ x.out = x.out[:cap(x.out)]
63
+ for remain < len(x.out)-bs {
64
+ x.b.Encrypt(x.cipher, x.cipher)
65
+ copy(x.out[remain:], x.cipher)
66
+ remain += bs
67
+ }
68
+ x.out = x.out[:remain]
69
+ x.outUsed = 0
70
+ }
71
+
72
+ func (x *ofb) XORKeyStream(dst, src []byte) {
73
+ if len(dst) < len(src) {
74
+ panic("crypto/cipher: output smaller than input")
75
+ }
76
+ if alias.InexactOverlap(dst[:len(src)], src) {
77
+ panic("crypto/cipher: invalid buffer overlap")
78
+ }
79
+ for len(src) > 0 {
80
+ if x.outUsed >= len(x.out)-x.b.BlockSize() {
81
+ x.refill()
82
+ }
83
+ n := subtle.XORBytes(dst, src, x.out[x.outUsed:])
84
+ dst = dst[n:]
85
+ src = src[n:]
86
+ x.outUsed += n
87
+ }
88
+ }
go/src/crypto/cipher/ofb_test.go ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // OFB AES test vectors.
6
+
7
+ // See U.S. National Institute of Standards and Technology (NIST)
8
+ // Special Publication 800-38A, ``Recommendation for Block Cipher
9
+ // Modes of Operation,'' 2001 Edition, pp. 52-55.
10
+
11
+ package cipher_test
12
+
13
+ import (
14
+ "bytes"
15
+ "crypto/aes"
16
+ "crypto/cipher"
17
+ "crypto/des"
18
+ "crypto/internal/cryptotest"
19
+ "fmt"
20
+ "testing"
21
+ )
22
+
23
+ type ofbTest struct {
24
+ name string
25
+ key []byte
26
+ iv []byte
27
+ in []byte
28
+ out []byte
29
+ }
30
+
31
+ var ofbTests = []ofbTest{
32
+ // NIST SP 800-38A pp 52-55
33
+ {
34
+ "OFB-AES128",
35
+ commonKey128,
36
+ commonIV,
37
+ commonInput,
38
+ []byte{
39
+ 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a,
40
+ 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25,
41
+ 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc,
42
+ 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e,
43
+ },
44
+ },
45
+ {
46
+ "OFB-AES192",
47
+ commonKey192,
48
+ commonIV,
49
+ commonInput,
50
+ []byte{
51
+ 0xcd, 0xc8, 0x0d, 0x6f, 0xdd, 0xf1, 0x8c, 0xab, 0x34, 0xc2, 0x59, 0x09, 0xc9, 0x9a, 0x41, 0x74,
52
+ 0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c, 0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01,
53
+ 0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f, 0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2,
54
+ 0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e, 0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a,
55
+ },
56
+ },
57
+ {
58
+ "OFB-AES256",
59
+ commonKey256,
60
+ commonIV,
61
+ commonInput,
62
+ []byte{
63
+ 0xdc, 0x7e, 0x84, 0xbf, 0xda, 0x79, 0x16, 0x4b, 0x7e, 0xcd, 0x84, 0x86, 0x98, 0x5d, 0x38, 0x60,
64
+ 0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a, 0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d,
65
+ 0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed, 0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08,
66
+ 0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8, 0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84,
67
+ },
68
+ },
69
+ }
70
+
71
+ func TestOFB(t *testing.T) {
72
+ for _, tt := range ofbTests {
73
+ test := tt.name
74
+
75
+ c, err := aes.NewCipher(tt.key)
76
+ if err != nil {
77
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
78
+ continue
79
+ }
80
+
81
+ for j := 0; j <= 5; j += 5 {
82
+ plaintext := tt.in[0 : len(tt.in)-j]
83
+ ofb := cipher.NewOFB(c, tt.iv)
84
+ ciphertext := make([]byte, len(plaintext))
85
+ ofb.XORKeyStream(ciphertext, plaintext)
86
+ if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) {
87
+ t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out)
88
+ }
89
+ }
90
+
91
+ for j := 0; j <= 5; j += 5 {
92
+ ciphertext := tt.out[0 : len(tt.in)-j]
93
+ ofb := cipher.NewOFB(c, tt.iv)
94
+ plaintext := make([]byte, len(ciphertext))
95
+ ofb.XORKeyStream(plaintext, ciphertext)
96
+ if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) {
97
+ t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in)
98
+ }
99
+ }
100
+
101
+ if t.Failed() {
102
+ break
103
+ }
104
+ }
105
+ }
106
+
107
+ func TestOFBStream(t *testing.T) {
108
+
109
+ for _, keylen := range []int{128, 192, 256} {
110
+
111
+ t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
112
+ rng := newRandReader(t)
113
+
114
+ key := make([]byte, keylen/8)
115
+ rng.Read(key)
116
+
117
+ block, err := aes.NewCipher(key)
118
+ if err != nil {
119
+ panic(err)
120
+ }
121
+
122
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewOFB)
123
+ })
124
+ }
125
+
126
+ t.Run("DES", func(t *testing.T) {
127
+ rng := newRandReader(t)
128
+
129
+ key := make([]byte, 8)
130
+ rng.Read(key)
131
+
132
+ block, err := des.NewCipher(key)
133
+ if err != nil {
134
+ panic(err)
135
+ }
136
+
137
+ cryptotest.TestStreamFromBlock(t, block, cipher.NewOFB)
138
+ })
139
+ }
go/src/crypto/des/block.go ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 des
6
+
7
+ import (
8
+ "internal/byteorder"
9
+ "sync"
10
+ )
11
+
12
+ func cryptBlock(subkeys []uint64, dst, src []byte, decrypt bool) {
13
+ b := byteorder.BEUint64(src)
14
+ b = permuteInitialBlock(b)
15
+ left, right := uint32(b>>32), uint32(b)
16
+
17
+ left = (left << 1) | (left >> 31)
18
+ right = (right << 1) | (right >> 31)
19
+
20
+ if decrypt {
21
+ for i := 0; i < 8; i++ {
22
+ left, right = feistel(left, right, subkeys[15-2*i], subkeys[15-(2*i+1)])
23
+ }
24
+ } else {
25
+ for i := 0; i < 8; i++ {
26
+ left, right = feistel(left, right, subkeys[2*i], subkeys[2*i+1])
27
+ }
28
+ }
29
+
30
+ left = (left << 31) | (left >> 1)
31
+ right = (right << 31) | (right >> 1)
32
+
33
+ // switch left & right and perform final permutation
34
+ preOutput := (uint64(right) << 32) | uint64(left)
35
+ byteorder.BEPutUint64(dst, permuteFinalBlock(preOutput))
36
+ }
37
+
38
+ // DES Feistel function. feistelBox must be initialized via
39
+ // feistelBoxOnce.Do(initFeistelBox) first.
40
+ func feistel(l, r uint32, k0, k1 uint64) (lout, rout uint32) {
41
+ var t uint32
42
+
43
+ t = r ^ uint32(k0>>32)
44
+ l ^= feistelBox[7][t&0x3f] ^
45
+ feistelBox[5][(t>>8)&0x3f] ^
46
+ feistelBox[3][(t>>16)&0x3f] ^
47
+ feistelBox[1][(t>>24)&0x3f]
48
+
49
+ t = ((r << 28) | (r >> 4)) ^ uint32(k0)
50
+ l ^= feistelBox[6][(t)&0x3f] ^
51
+ feistelBox[4][(t>>8)&0x3f] ^
52
+ feistelBox[2][(t>>16)&0x3f] ^
53
+ feistelBox[0][(t>>24)&0x3f]
54
+
55
+ t = l ^ uint32(k1>>32)
56
+ r ^= feistelBox[7][t&0x3f] ^
57
+ feistelBox[5][(t>>8)&0x3f] ^
58
+ feistelBox[3][(t>>16)&0x3f] ^
59
+ feistelBox[1][(t>>24)&0x3f]
60
+
61
+ t = ((l << 28) | (l >> 4)) ^ uint32(k1)
62
+ r ^= feistelBox[6][(t)&0x3f] ^
63
+ feistelBox[4][(t>>8)&0x3f] ^
64
+ feistelBox[2][(t>>16)&0x3f] ^
65
+ feistelBox[0][(t>>24)&0x3f]
66
+
67
+ return l, r
68
+ }
69
+
70
+ // feistelBox[s][16*i+j] contains the output of permutationFunction
71
+ // for sBoxes[s][i][j] << 4*(7-s)
72
+ var feistelBox [8][64]uint32
73
+
74
+ var feistelBoxOnce sync.Once
75
+
76
+ // general purpose function to perform DES block permutations.
77
+ func permuteBlock(src uint64, permutation []uint8) (block uint64) {
78
+ for position, n := range permutation {
79
+ bit := (src >> n) & 1
80
+ block |= bit << uint((len(permutation)-1)-position)
81
+ }
82
+ return
83
+ }
84
+
85
+ func initFeistelBox() {
86
+ for s := range sBoxes {
87
+ for i := 0; i < 4; i++ {
88
+ for j := 0; j < 16; j++ {
89
+ f := uint64(sBoxes[s][i][j]) << (4 * (7 - uint(s)))
90
+ f = permuteBlock(f, permutationFunction[:])
91
+
92
+ // Row is determined by the 1st and 6th bit.
93
+ // Column is the middle four bits.
94
+ row := uint8(((i & 2) << 4) | i&1)
95
+ col := uint8(j << 1)
96
+ t := row | col
97
+
98
+ // The rotation was performed in the feistel rounds, being factored out and now mixed into the feistelBox.
99
+ f = (f << 1) | (f >> 31)
100
+
101
+ feistelBox[s][t] = uint32(f)
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ // permuteInitialBlock is equivalent to the permutation defined
108
+ // by initialPermutation.
109
+ func permuteInitialBlock(block uint64) uint64 {
110
+ // block = b7 b6 b5 b4 b3 b2 b1 b0 (8 bytes)
111
+ b1 := block >> 48
112
+ b2 := block << 48
113
+ block ^= b1 ^ b2 ^ b1<<48 ^ b2>>48
114
+
115
+ // block = b1 b0 b5 b4 b3 b2 b7 b6
116
+ b1 = block >> 32 & 0xff00ff
117
+ b2 = (block & 0xff00ff00)
118
+ block ^= b1<<32 ^ b2 ^ b1<<8 ^ b2<<24 // exchange b0 b4 with b3 b7
119
+
120
+ // block is now b1 b3 b5 b7 b0 b2 b4 b6, the permutation:
121
+ // ... 8
122
+ // ... 24
123
+ // ... 40
124
+ // ... 56
125
+ // 7 6 5 4 3 2 1 0
126
+ // 23 22 21 20 19 18 17 16
127
+ // ... 32
128
+ // ... 48
129
+
130
+ // exchange 4,5,6,7 with 32,33,34,35 etc.
131
+ b1 = block & 0x0f0f00000f0f0000
132
+ b2 = block & 0x0000f0f00000f0f0
133
+ block ^= b1 ^ b2 ^ b1>>12 ^ b2<<12
134
+
135
+ // block is the permutation:
136
+ //
137
+ // [+8] [+40]
138
+ //
139
+ // 7 6 5 4
140
+ // 23 22 21 20
141
+ // 3 2 1 0
142
+ // 19 18 17 16 [+32]
143
+
144
+ // exchange 0,1,4,5 with 18,19,22,23
145
+ b1 = block & 0x3300330033003300
146
+ b2 = block & 0x00cc00cc00cc00cc
147
+ block ^= b1 ^ b2 ^ b1>>6 ^ b2<<6
148
+
149
+ // block is the permutation:
150
+ // 15 14
151
+ // 13 12
152
+ // 11 10
153
+ // 9 8
154
+ // 7 6
155
+ // 5 4
156
+ // 3 2
157
+ // 1 0 [+16] [+32] [+64]
158
+
159
+ // exchange 0,2,4,6 with 9,11,13,15:
160
+ b1 = block & 0xaaaaaaaa55555555
161
+ block ^= b1 ^ b1>>33 ^ b1<<33
162
+
163
+ // block is the permutation:
164
+ // 6 14 22 30 38 46 54 62
165
+ // 4 12 20 28 36 44 52 60
166
+ // 2 10 18 26 34 42 50 58
167
+ // 0 8 16 24 32 40 48 56
168
+ // 7 15 23 31 39 47 55 63
169
+ // 5 13 21 29 37 45 53 61
170
+ // 3 11 19 27 35 43 51 59
171
+ // 1 9 17 25 33 41 49 57
172
+ return block
173
+ }
174
+
175
+ // permuteFinalBlock is equivalent to the permutation defined
176
+ // by finalPermutation.
177
+ func permuteFinalBlock(block uint64) uint64 {
178
+ // Perform the same bit exchanges as permuteInitialBlock
179
+ // but in reverse order.
180
+ b1 := block & 0xaaaaaaaa55555555
181
+ block ^= b1 ^ b1>>33 ^ b1<<33
182
+
183
+ b1 = block & 0x3300330033003300
184
+ b2 := block & 0x00cc00cc00cc00cc
185
+ block ^= b1 ^ b2 ^ b1>>6 ^ b2<<6
186
+
187
+ b1 = block & 0x0f0f00000f0f0000
188
+ b2 = block & 0x0000f0f00000f0f0
189
+ block ^= b1 ^ b2 ^ b1>>12 ^ b2<<12
190
+
191
+ b1 = block >> 32 & 0xff00ff
192
+ b2 = (block & 0xff00ff00)
193
+ block ^= b1<<32 ^ b2 ^ b1<<8 ^ b2<<24
194
+
195
+ b1 = block >> 48
196
+ b2 = block << 48
197
+ block ^= b1 ^ b2 ^ b1<<48 ^ b2>>48
198
+ return block
199
+ }
200
+
201
+ // creates 16 28-bit blocks rotated according
202
+ // to the rotation schedule.
203
+ func ksRotate(in uint32) (out []uint32) {
204
+ out = make([]uint32, 16)
205
+ last := in
206
+ for i := 0; i < 16; i++ {
207
+ // 28-bit circular left shift
208
+ left := (last << (4 + ksRotations[i])) >> 4
209
+ right := (last << 4) >> (32 - ksRotations[i])
210
+ out[i] = left | right
211
+ last = out[i]
212
+ }
213
+ return
214
+ }
215
+
216
+ // creates 16 56-bit subkeys from the original key.
217
+ func (c *desCipher) generateSubkeys(keyBytes []byte) {
218
+ feistelBoxOnce.Do(initFeistelBox)
219
+
220
+ // apply PC1 permutation to key
221
+ key := byteorder.BEUint64(keyBytes)
222
+ permutedKey := permuteBlock(key, permutedChoice1[:])
223
+
224
+ // rotate halves of permuted key according to the rotation schedule
225
+ leftRotations := ksRotate(uint32(permutedKey >> 28))
226
+ rightRotations := ksRotate(uint32(permutedKey<<4) >> 4)
227
+
228
+ // generate subkeys
229
+ for i := 0; i < 16; i++ {
230
+ // combine halves to form 56-bit input to PC2
231
+ pc2Input := uint64(leftRotations[i])<<28 | uint64(rightRotations[i])
232
+ // apply PC2 permutation to 7 byte input
233
+ c.subkeys[i] = unpack(permuteBlock(pc2Input, permutedChoice2[:]))
234
+ }
235
+ }
236
+
237
+ // Expand 48-bit input to 64-bit, with each 6-bit block padded by extra two bits at the top.
238
+ // By doing so, we can have the input blocks (four bits each), and the key blocks (six bits each) well-aligned without
239
+ // extra shifts/rotations for alignments.
240
+ func unpack(x uint64) uint64 {
241
+ return ((x>>(6*1))&0xff)<<(8*0) |
242
+ ((x>>(6*3))&0xff)<<(8*1) |
243
+ ((x>>(6*5))&0xff)<<(8*2) |
244
+ ((x>>(6*7))&0xff)<<(8*3) |
245
+ ((x>>(6*0))&0xff)<<(8*4) |
246
+ ((x>>(6*2))&0xff)<<(8*5) |
247
+ ((x>>(6*4))&0xff)<<(8*6) |
248
+ ((x>>(6*6))&0xff)<<(8*7)
249
+ }
go/src/crypto/des/cipher.go ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 des
6
+
7
+ import (
8
+ "crypto/cipher"
9
+ "crypto/internal/fips140/alias"
10
+ "crypto/internal/fips140only"
11
+ "errors"
12
+ "internal/byteorder"
13
+ "strconv"
14
+ )
15
+
16
+ // The DES block size in bytes.
17
+ const BlockSize = 8
18
+
19
+ type KeySizeError int
20
+
21
+ func (k KeySizeError) Error() string {
22
+ return "crypto/des: invalid key size " + strconv.Itoa(int(k))
23
+ }
24
+
25
+ // desCipher is an instance of DES encryption.
26
+ type desCipher struct {
27
+ subkeys [16]uint64
28
+ }
29
+
30
+ // NewCipher creates and returns a new [cipher.Block].
31
+ func NewCipher(key []byte) (cipher.Block, error) {
32
+ if fips140only.Enforced() {
33
+ return nil, errors.New("crypto/des: use of DES is not allowed in FIPS 140-only mode")
34
+ }
35
+
36
+ if len(key) != 8 {
37
+ return nil, KeySizeError(len(key))
38
+ }
39
+
40
+ c := new(desCipher)
41
+ c.generateSubkeys(key)
42
+ return c, nil
43
+ }
44
+
45
+ func (c *desCipher) BlockSize() int { return BlockSize }
46
+
47
+ func (c *desCipher) Encrypt(dst, src []byte) {
48
+ if len(src) < BlockSize {
49
+ panic("crypto/des: input not full block")
50
+ }
51
+ if len(dst) < BlockSize {
52
+ panic("crypto/des: output not full block")
53
+ }
54
+ if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
55
+ panic("crypto/des: invalid buffer overlap")
56
+ }
57
+ cryptBlock(c.subkeys[:], dst, src, false)
58
+ }
59
+
60
+ func (c *desCipher) Decrypt(dst, src []byte) {
61
+ if len(src) < BlockSize {
62
+ panic("crypto/des: input not full block")
63
+ }
64
+ if len(dst) < BlockSize {
65
+ panic("crypto/des: output not full block")
66
+ }
67
+ if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
68
+ panic("crypto/des: invalid buffer overlap")
69
+ }
70
+ cryptBlock(c.subkeys[:], dst, src, true)
71
+ }
72
+
73
+ // A tripleDESCipher is an instance of TripleDES encryption.
74
+ type tripleDESCipher struct {
75
+ cipher1, cipher2, cipher3 desCipher
76
+ }
77
+
78
+ // NewTripleDESCipher creates and returns a new [cipher.Block].
79
+ func NewTripleDESCipher(key []byte) (cipher.Block, error) {
80
+ if fips140only.Enforced() {
81
+ return nil, errors.New("crypto/des: use of TripleDES is not allowed in FIPS 140-only mode")
82
+ }
83
+
84
+ if len(key) != 24 {
85
+ return nil, KeySizeError(len(key))
86
+ }
87
+
88
+ c := new(tripleDESCipher)
89
+ c.cipher1.generateSubkeys(key[:8])
90
+ c.cipher2.generateSubkeys(key[8:16])
91
+ c.cipher3.generateSubkeys(key[16:])
92
+ return c, nil
93
+ }
94
+
95
+ func (c *tripleDESCipher) BlockSize() int { return BlockSize }
96
+
97
+ func (c *tripleDESCipher) Encrypt(dst, src []byte) {
98
+ if len(src) < BlockSize {
99
+ panic("crypto/des: input not full block")
100
+ }
101
+ if len(dst) < BlockSize {
102
+ panic("crypto/des: output not full block")
103
+ }
104
+ if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
105
+ panic("crypto/des: invalid buffer overlap")
106
+ }
107
+
108
+ b := byteorder.BEUint64(src)
109
+ b = permuteInitialBlock(b)
110
+ left, right := uint32(b>>32), uint32(b)
111
+
112
+ left = (left << 1) | (left >> 31)
113
+ right = (right << 1) | (right >> 31)
114
+
115
+ for i := 0; i < 8; i++ {
116
+ left, right = feistel(left, right, c.cipher1.subkeys[2*i], c.cipher1.subkeys[2*i+1])
117
+ }
118
+ for i := 0; i < 8; i++ {
119
+ right, left = feistel(right, left, c.cipher2.subkeys[15-2*i], c.cipher2.subkeys[15-(2*i+1)])
120
+ }
121
+ for i := 0; i < 8; i++ {
122
+ left, right = feistel(left, right, c.cipher3.subkeys[2*i], c.cipher3.subkeys[2*i+1])
123
+ }
124
+
125
+ left = (left << 31) | (left >> 1)
126
+ right = (right << 31) | (right >> 1)
127
+
128
+ preOutput := (uint64(right) << 32) | uint64(left)
129
+ byteorder.BEPutUint64(dst, permuteFinalBlock(preOutput))
130
+ }
131
+
132
+ func (c *tripleDESCipher) Decrypt(dst, src []byte) {
133
+ if len(src) < BlockSize {
134
+ panic("crypto/des: input not full block")
135
+ }
136
+ if len(dst) < BlockSize {
137
+ panic("crypto/des: output not full block")
138
+ }
139
+ if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
140
+ panic("crypto/des: invalid buffer overlap")
141
+ }
142
+
143
+ b := byteorder.BEUint64(src)
144
+ b = permuteInitialBlock(b)
145
+ left, right := uint32(b>>32), uint32(b)
146
+
147
+ left = (left << 1) | (left >> 31)
148
+ right = (right << 1) | (right >> 31)
149
+
150
+ for i := 0; i < 8; i++ {
151
+ left, right = feistel(left, right, c.cipher3.subkeys[15-2*i], c.cipher3.subkeys[15-(2*i+1)])
152
+ }
153
+ for i := 0; i < 8; i++ {
154
+ right, left = feistel(right, left, c.cipher2.subkeys[2*i], c.cipher2.subkeys[2*i+1])
155
+ }
156
+ for i := 0; i < 8; i++ {
157
+ left, right = feistel(left, right, c.cipher1.subkeys[15-2*i], c.cipher1.subkeys[15-(2*i+1)])
158
+ }
159
+
160
+ left = (left << 31) | (left >> 1)
161
+ right = (right << 31) | (right >> 1)
162
+
163
+ preOutput := (uint64(right) << 32) | uint64(left)
164
+ byteorder.BEPutUint64(dst, permuteFinalBlock(preOutput))
165
+ }
go/src/crypto/des/const.go ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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 des implements the Data Encryption Standard (DES) and the
6
+ // Triple Data Encryption Algorithm (TDEA) as defined
7
+ // in U.S. Federal Information Processing Standards Publication 46-3.
8
+ //
9
+ // DES is cryptographically broken and should not be used for secure
10
+ // applications.
11
+ package des
12
+
13
+ // Used to perform an initial permutation of a 64-bit input block.
14
+ var initialPermutation = [64]byte{
15
+ 6, 14, 22, 30, 38, 46, 54, 62,
16
+ 4, 12, 20, 28, 36, 44, 52, 60,
17
+ 2, 10, 18, 26, 34, 42, 50, 58,
18
+ 0, 8, 16, 24, 32, 40, 48, 56,
19
+ 7, 15, 23, 31, 39, 47, 55, 63,
20
+ 5, 13, 21, 29, 37, 45, 53, 61,
21
+ 3, 11, 19, 27, 35, 43, 51, 59,
22
+ 1, 9, 17, 25, 33, 41, 49, 57,
23
+ }
24
+
25
+ // Used to perform a final permutation of a 4-bit preoutput block. This is the
26
+ // inverse of initialPermutation
27
+ var finalPermutation = [64]byte{
28
+ 24, 56, 16, 48, 8, 40, 0, 32,
29
+ 25, 57, 17, 49, 9, 41, 1, 33,
30
+ 26, 58, 18, 50, 10, 42, 2, 34,
31
+ 27, 59, 19, 51, 11, 43, 3, 35,
32
+ 28, 60, 20, 52, 12, 44, 4, 36,
33
+ 29, 61, 21, 53, 13, 45, 5, 37,
34
+ 30, 62, 22, 54, 14, 46, 6, 38,
35
+ 31, 63, 23, 55, 15, 47, 7, 39,
36
+ }
37
+
38
+ // Used to expand an input block of 32 bits, producing an output block of 48
39
+ // bits.
40
+ var expansionFunction = [48]byte{
41
+ 0, 31, 30, 29, 28, 27, 28, 27,
42
+ 26, 25, 24, 23, 24, 23, 22, 21,
43
+ 20, 19, 20, 19, 18, 17, 16, 15,
44
+ 16, 15, 14, 13, 12, 11, 12, 11,
45
+ 10, 9, 8, 7, 8, 7, 6, 5,
46
+ 4, 3, 4, 3, 2, 1, 0, 31,
47
+ }
48
+
49
+ // Yields a 32-bit output from a 32-bit input
50
+ var permutationFunction = [32]byte{
51
+ 16, 25, 12, 11, 3, 20, 4, 15,
52
+ 31, 17, 9, 6, 27, 14, 1, 22,
53
+ 30, 24, 8, 18, 0, 5, 29, 23,
54
+ 13, 19, 2, 26, 10, 21, 28, 7,
55
+ }
56
+
57
+ // Used in the key schedule to select 56 bits
58
+ // from a 64-bit input.
59
+ var permutedChoice1 = [56]byte{
60
+ 7, 15, 23, 31, 39, 47, 55, 63,
61
+ 6, 14, 22, 30, 38, 46, 54, 62,
62
+ 5, 13, 21, 29, 37, 45, 53, 61,
63
+ 4, 12, 20, 28, 1, 9, 17, 25,
64
+ 33, 41, 49, 57, 2, 10, 18, 26,
65
+ 34, 42, 50, 58, 3, 11, 19, 27,
66
+ 35, 43, 51, 59, 36, 44, 52, 60,
67
+ }
68
+
69
+ // Used in the key schedule to produce each subkey by selecting 48 bits from
70
+ // the 56-bit input
71
+ var permutedChoice2 = [48]byte{
72
+ 42, 39, 45, 32, 55, 51, 53, 28,
73
+ 41, 50, 35, 46, 33, 37, 44, 52,
74
+ 30, 48, 40, 49, 29, 36, 43, 54,
75
+ 15, 4, 25, 19, 9, 1, 26, 16,
76
+ 5, 11, 23, 8, 12, 7, 17, 0,
77
+ 22, 3, 10, 14, 6, 20, 27, 24,
78
+ }
79
+
80
+ // 8 S-boxes composed of 4 rows and 16 columns
81
+ // Used in the DES cipher function
82
+ var sBoxes = [8][4][16]uint8{
83
+ // S-box 1
84
+ {
85
+ {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
86
+ {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
87
+ {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
88
+ {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
89
+ },
90
+ // S-box 2
91
+ {
92
+ {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
93
+ {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
94
+ {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
95
+ {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
96
+ },
97
+ // S-box 3
98
+ {
99
+ {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
100
+ {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
101
+ {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
102
+ {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
103
+ },
104
+ // S-box 4
105
+ {
106
+ {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
107
+ {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
108
+ {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
109
+ {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
110
+ },
111
+ // S-box 5
112
+ {
113
+ {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
114
+ {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
115
+ {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
116
+ {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
117
+ },
118
+ // S-box 6
119
+ {
120
+ {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
121
+ {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
122
+ {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
123
+ {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
124
+ },
125
+ // S-box 7
126
+ {
127
+ {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
128
+ {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
129
+ {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
130
+ {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
131
+ },
132
+ // S-box 8
133
+ {
134
+ {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
135
+ {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
136
+ {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
137
+ {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11},
138
+ },
139
+ }
140
+
141
+ // Size of left rotation per round in each half of the key schedule
142
+ var ksRotations = [16]uint8{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}
go/src/crypto/des/des_test.go ADDED
@@ -0,0 +1,1575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 des_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/cipher"
10
+ "crypto/des"
11
+ "crypto/internal/cryptotest"
12
+ "testing"
13
+ )
14
+
15
+ type CryptTest struct {
16
+ key []byte
17
+ in []byte
18
+ out []byte
19
+ }
20
+
21
+ // some custom tests for DES
22
+ var encryptDESTests = []CryptTest{
23
+ {
24
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
25
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
26
+ []byte{0x8c, 0xa6, 0x4d, 0xe9, 0xc1, 0xb1, 0x23, 0xa7}},
27
+ {
28
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
29
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
30
+ []byte{0x35, 0x55, 0x50, 0xb2, 0x15, 0x0e, 0x24, 0x51}},
31
+ {
32
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
33
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
34
+ []byte{0x61, 0x7b, 0x3a, 0x0c, 0xe8, 0xf0, 0x71, 0x00}},
35
+ {
36
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
37
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
38
+ []byte{0x92, 0x31, 0xf2, 0x36, 0xff, 0x9a, 0xa9, 0x5c}},
39
+ {
40
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
41
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
42
+ []byte{0xca, 0xaa, 0xaf, 0x4d, 0xea, 0xf1, 0xdb, 0xae}},
43
+ {
44
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
45
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
46
+ []byte{0x73, 0x59, 0xb2, 0x16, 0x3e, 0x4e, 0xdc, 0x58}},
47
+ {
48
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
49
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
50
+ []byte{0x6d, 0xce, 0x0d, 0xc9, 0x00, 0x65, 0x56, 0xa3}},
51
+ {
52
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
53
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
54
+ []byte{0x9e, 0x84, 0xc5, 0xf3, 0x17, 0x0f, 0x8e, 0xff}},
55
+ {
56
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
57
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
58
+ []byte{0xd5, 0xd4, 0x4f, 0xf7, 0x20, 0x68, 0x3d, 0x0d}},
59
+ {
60
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
61
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
62
+ []byte{0x59, 0x73, 0x23, 0x56, 0xf3, 0x6f, 0xde, 0x06}},
63
+ {
64
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
65
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
66
+ []byte{0x56, 0xcc, 0x09, 0xe7, 0xcf, 0xdc, 0x4c, 0xef}},
67
+ {
68
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
69
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
70
+ []byte{0x12, 0xc6, 0x26, 0xaf, 0x05, 0x8b, 0x43, 0x3b}},
71
+ {
72
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
73
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
74
+ []byte{0xa6, 0x8c, 0xdc, 0xa9, 0x0c, 0x90, 0x21, 0xf9}},
75
+ {
76
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
77
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
78
+ []byte{0x2a, 0x2b, 0xb0, 0x08, 0xdf, 0x97, 0xc2, 0xf2}},
79
+ {
80
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
81
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
82
+ []byte{0xed, 0x39, 0xd9, 0x50, 0xfa, 0x74, 0xbc, 0xc4}},
83
+ {
84
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
85
+ []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10},
86
+ []byte{0xa9, 0x33, 0xf6, 0x18, 0x30, 0x23, 0xb3, 0x10}},
87
+ {
88
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
89
+ []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
90
+ []byte{0x17, 0x66, 0x8d, 0xfc, 0x72, 0x92, 0x53, 0x2d}},
91
+ {
92
+ []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
93
+ []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
94
+ []byte{0xb4, 0xfd, 0x23, 0x16, 0x47, 0xa5, 0xbe, 0xc0}},
95
+ {
96
+ []byte{0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73},
97
+ []byte{0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87},
98
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
99
+ {
100
+ []byte{0x73, 0x65, 0x63, 0x52, 0x33, 0x74, 0x24, 0x3b}, // "secR3t$;"
101
+ []byte{0x61, 0x20, 0x74, 0x65, 0x73, 0x74, 0x31, 0x32}, // "a test12"
102
+ []byte{0x37, 0x0d, 0xee, 0x2c, 0x1f, 0xb4, 0xf7, 0xa5}},
103
+ {
104
+ []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh"
105
+ []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh"
106
+ []byte{0x2a, 0x8d, 0x69, 0xde, 0x9d, 0x5f, 0xdf, 0xf9}},
107
+ {
108
+ []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh"
109
+ []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678"
110
+ []byte{0x21, 0xc6, 0x0d, 0xa5, 0x34, 0x24, 0x8b, 0xce}},
111
+ {
112
+ []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678"
113
+ []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh"
114
+ []byte{0x94, 0xd4, 0x43, 0x6b, 0xc3, 0xb5, 0xb6, 0x93}},
115
+ {
116
+ []byte{0x1f, 0x79, 0x90, 0x5f, 0x88, 0x01, 0xc8, 0x88}, // random
117
+ []byte{0xc7, 0x46, 0x18, 0x73, 0xaf, 0x48, 0x5f, 0xb3}, // random
118
+ []byte{0xb0, 0x93, 0x50, 0x88, 0xf9, 0x92, 0x44, 0x6a}},
119
+ {
120
+ []byte{0xe6, 0xf4, 0xf2, 0xdb, 0x31, 0x42, 0x53, 0x01}, // random
121
+ []byte{0xff, 0x3d, 0x25, 0x50, 0x12, 0xe3, 0x4a, 0xc5}, // random
122
+ []byte{0x86, 0x08, 0xd3, 0xd1, 0x6c, 0x2f, 0xd2, 0x55}},
123
+ {
124
+ []byte{0x69, 0xc1, 0x9d, 0xc1, 0x15, 0xc5, 0xfb, 0x2b}, // random
125
+ []byte{0x1a, 0x22, 0x5c, 0xaf, 0x1f, 0x1d, 0xa3, 0xf9}, // random
126
+ []byte{0x64, 0xba, 0x31, 0x67, 0x56, 0x91, 0x1e, 0xa7}},
127
+ {
128
+ []byte{0x6e, 0x5e, 0xe2, 0x47, 0xc4, 0xbf, 0xf6, 0x51}, // random
129
+ []byte{0x11, 0xc9, 0x57, 0xff, 0x66, 0x89, 0x0e, 0xf0}, // random
130
+ []byte{0x94, 0xc5, 0x35, 0xb2, 0xc5, 0x8b, 0x39, 0x72}},
131
+ }
132
+
133
+ var weakKeyTests = []CryptTest{
134
+ {
135
+ []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
136
+ []byte{0x55, 0x74, 0xc0, 0xbd, 0x7c, 0xdf, 0xf7, 0x39}, // random
137
+ nil},
138
+ {
139
+ []byte{0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe},
140
+ []byte{0xe8, 0xe1, 0xa7, 0xc1, 0xde, 0x11, 0x89, 0xaa}, // random
141
+ nil},
142
+ {
143
+ []byte{0xe0, 0xe0, 0xe0, 0xe0, 0xf1, 0xf1, 0xf1, 0xf1},
144
+ []byte{0x50, 0x6a, 0x4b, 0x94, 0x3b, 0xed, 0x7d, 0xdc}, // random
145
+ nil},
146
+ {
147
+ []byte{0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e},
148
+ []byte{0x88, 0x81, 0x56, 0x38, 0xec, 0x3b, 0x1c, 0x97}, // random
149
+ nil},
150
+ {
151
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
152
+ []byte{0x17, 0xa0, 0x83, 0x62, 0x32, 0xfe, 0x9a, 0x0b}, // random
153
+ nil},
154
+ {
155
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
156
+ []byte{0xca, 0x8f, 0xca, 0x1f, 0x50, 0xc5, 0x7b, 0x49}, // random
157
+ nil},
158
+ {
159
+ []byte{0xe1, 0xe1, 0xe1, 0xe1, 0xf0, 0xf0, 0xf0, 0xf0},
160
+ []byte{0xb1, 0xea, 0xad, 0x7d, 0xe7, 0xc3, 0x7a, 0x43}, // random
161
+ nil},
162
+ {
163
+ []byte{0x1e, 0x1e, 0x1e, 0x1e, 0x0f, 0x0f, 0x0f, 0x0f},
164
+ []byte{0xae, 0x74, 0x7d, 0x6f, 0xef, 0x16, 0xbb, 0x81}, // random
165
+ nil},
166
+ }
167
+
168
+ var semiWeakKeyTests = []CryptTest{
169
+ // key and out contain the semi-weak key pair
170
+ {
171
+ []byte{0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e},
172
+ []byte{0x12, 0xfa, 0x31, 0x16, 0xf9, 0xc5, 0x0a, 0xe4}, // random
173
+ []byte{0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01}},
174
+ {
175
+ []byte{0x01, 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1},
176
+ []byte{0xb0, 0x4c, 0x7a, 0xee, 0xd2, 0xe5, 0x4d, 0xb7}, // random
177
+ []byte{0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1, 0x01}},
178
+ {
179
+ []byte{0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe},
180
+ []byte{0xa4, 0x81, 0xcd, 0xb1, 0x64, 0x6f, 0xd3, 0xbc}, // random
181
+ []byte{0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01}},
182
+ {
183
+ []byte{0x1f, 0xe0, 0x1f, 0xe0, 0x0e, 0xf1, 0x0e, 0xf1},
184
+ []byte{0xee, 0x27, 0xdd, 0x88, 0x4c, 0x22, 0xcd, 0xce}, // random
185
+ []byte{0xe0, 0x1f, 0xe0, 0x1f, 0xf1, 0x0e, 0xf1, 0x0e}},
186
+ {
187
+ []byte{0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe},
188
+ []byte{0x19, 0x3d, 0xcf, 0x97, 0x70, 0xfb, 0xab, 0xe1}, // random
189
+ []byte{0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e}},
190
+ {
191
+ []byte{0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe},
192
+ []byte{0x7c, 0x82, 0x69, 0xe4, 0x1e, 0x86, 0x99, 0xd7}, // random
193
+ []byte{0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1}},
194
+ }
195
+
196
+ // some custom tests for TripleDES
197
+ var encryptTripleDESTests = []CryptTest{
198
+ {
199
+ []byte{
200
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
201
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
202
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
203
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
204
+ []byte{0x92, 0x95, 0xb5, 0x9b, 0xb3, 0x84, 0x73, 0x6e}},
205
+ {
206
+ []byte{
207
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
208
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
209
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
210
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
211
+ []byte{0xc1, 0x97, 0xf5, 0x58, 0x74, 0x8a, 0x20, 0xe7}},
212
+ {
213
+ []byte{
214
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
215
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
216
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
217
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
218
+ []byte{0x3e, 0x68, 0x0a, 0xa7, 0x8b, 0x75, 0xdf, 0x18}},
219
+ {
220
+ []byte{
221
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
222
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
223
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
224
+ []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
225
+ []byte{0x6d, 0x6a, 0x4a, 0x64, 0x4c, 0x7b, 0x8c, 0x91}},
226
+ {
227
+ []byte{ // "abcdefgh12345678ABCDEFGH"
228
+ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
229
+ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
230
+ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48},
231
+ []byte{0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, // "00000000"
232
+ []byte{0xe4, 0x61, 0xb7, 0x59, 0x68, 0x8b, 0xff, 0x66}},
233
+ {
234
+ []byte{ // "abcdefgh12345678ABCDEFGH"
235
+ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
236
+ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
237
+ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48},
238
+ []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678"
239
+ []byte{0xdb, 0xd0, 0x92, 0xde, 0xf8, 0x34, 0xff, 0x58}},
240
+ {
241
+ []byte{ // "abcdefgh12345678ABCDEFGH"
242
+ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
243
+ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
244
+ 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48},
245
+ []byte{0xf0, 0xc5, 0x82, 0x22, 0xd3, 0xe6, 0x12, 0xd2}, // random
246
+ []byte{0xba, 0xe4, 0x41, 0xb1, 0x3c, 0x37, 0x4d, 0xf4}},
247
+ {
248
+ []byte{ // random
249
+ 0xd3, 0x7d, 0x45, 0xee, 0x22, 0xe9, 0xcf, 0x52,
250
+ 0xf4, 0x65, 0xa2, 0x4f, 0x70, 0xd1, 0x81, 0x8a,
251
+ 0x3d, 0xbe, 0x2f, 0x39, 0xc7, 0x71, 0xd2, 0xe9},
252
+ []byte{0x49, 0x53, 0xc3, 0xe9, 0x78, 0xdf, 0x9f, 0xaf}, // random
253
+ []byte{0x53, 0x40, 0x51, 0x24, 0xd8, 0x3c, 0xf9, 0x88}},
254
+ {
255
+ []byte{ // random
256
+ 0xcb, 0x10, 0x7d, 0xda, 0x7e, 0x96, 0x57, 0x0a,
257
+ 0xe8, 0xeb, 0xe8, 0x07, 0x8e, 0x87, 0xd3, 0x57,
258
+ 0xb2, 0x61, 0x12, 0xb8, 0x2a, 0x90, 0xb7, 0x2f},
259
+ []byte{0xa3, 0xc2, 0x60, 0xb1, 0x0b, 0xb7, 0x28, 0x6e}, // random
260
+ []byte{0x56, 0x73, 0x7d, 0xfb, 0xb5, 0xa1, 0xc3, 0xde}},
261
+ }
262
+
263
+ // NIST Special Publication 800-20, Appendix A
264
+ // Key for use with Table A.1 tests
265
+ var tableA1Key = []byte{
266
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
267
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
268
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
269
+ }
270
+
271
+ // Table A.1 Resulting Ciphertext from the Variable Plaintext Known Answer Test
272
+ var tableA1Tests = []CryptTest{
273
+ {nil, // 0
274
+ []byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
275
+ []byte{0x95, 0xf8, 0xa5, 0xe5, 0xdd, 0x31, 0xd9, 0x00}},
276
+ {nil, // 1
277
+ []byte{0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
278
+ []byte{0xdd, 0x7f, 0x12, 0x1c, 0xa5, 0x01, 0x56, 0x19}},
279
+ {nil, // 2
280
+ []byte{0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
281
+ []byte{0x2e, 0x86, 0x53, 0x10, 0x4f, 0x38, 0x34, 0xea}},
282
+ {nil, // 3
283
+ []byte{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
284
+ []byte{0x4b, 0xd3, 0x88, 0xff, 0x6c, 0xd8, 0x1d, 0x4f}},
285
+ {nil, // 4
286
+ []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
287
+ []byte{0x20, 0xb9, 0xe7, 0x67, 0xb2, 0xfb, 0x14, 0x56}},
288
+ {nil, // 5
289
+ []byte{0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
290
+ []byte{0x55, 0x57, 0x93, 0x80, 0xd7, 0x71, 0x38, 0xef}},
291
+ {nil, // 6
292
+ []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
293
+ []byte{0x6c, 0xc5, 0xde, 0xfa, 0xaf, 0x04, 0x51, 0x2f}},
294
+ {nil, // 7
295
+ []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
296
+ []byte{0x0d, 0x9f, 0x27, 0x9b, 0xa5, 0xd8, 0x72, 0x60}},
297
+ {nil, // 8
298
+ []byte{0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
299
+ []byte{0xd9, 0x03, 0x1b, 0x02, 0x71, 0xbd, 0x5a, 0x0a}},
300
+ {nil, // 9
301
+ []byte{0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
302
+ []byte{0x42, 0x42, 0x50, 0xb3, 0x7c, 0x3d, 0xd9, 0x51}},
303
+ {nil, // 10
304
+ []byte{0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
305
+ []byte{0xb8, 0x06, 0x1b, 0x7e, 0xcd, 0x9a, 0x21, 0xe5}},
306
+ {nil, // 11
307
+ []byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
308
+ []byte{0xf1, 0x5d, 0x0f, 0x28, 0x6b, 0x65, 0xbd, 0x28}},
309
+ {nil, // 12
310
+ []byte{0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
311
+ []byte{0xad, 0xd0, 0xcc, 0x8d, 0x6e, 0x5d, 0xeb, 0xa1}},
312
+ {nil, // 13
313
+ []byte{0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
314
+ []byte{0xe6, 0xd5, 0xf8, 0x27, 0x52, 0xad, 0x63, 0xd1}},
315
+ {nil, // 14
316
+ []byte{0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
317
+ []byte{0xec, 0xbf, 0xe3, 0xbd, 0x3f, 0x59, 0x1a, 0x5e}},
318
+ {nil, // 15
319
+ []byte{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
320
+ []byte{0xf3, 0x56, 0x83, 0x43, 0x79, 0xd1, 0x65, 0xcd}},
321
+ {nil, // 16
322
+ []byte{0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00},
323
+ []byte{0x2b, 0x9f, 0x98, 0x2f, 0x20, 0x03, 0x7f, 0xa9}},
324
+ {nil, // 17
325
+ []byte{0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00},
326
+ []byte{0x88, 0x9d, 0xe0, 0x68, 0xa1, 0x6f, 0x0b, 0xe6}},
327
+ {nil, // 18
328
+ []byte{0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00},
329
+ []byte{0xe1, 0x9e, 0x27, 0x5d, 0x84, 0x6a, 0x12, 0x98}},
330
+ {nil, // 19
331
+ []byte{0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00},
332
+ []byte{0x32, 0x9a, 0x8e, 0xd5, 0x23, 0xd7, 0x1a, 0xec}},
333
+ {nil, // 20
334
+ []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00},
335
+ []byte{0xe7, 0xfc, 0xe2, 0x25, 0x57, 0xd2, 0x3c, 0x97}},
336
+ {nil, // 21
337
+ []byte{0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00},
338
+ []byte{0x12, 0xa9, 0xf5, 0x81, 0x7f, 0xf2, 0xd6, 0x5d}},
339
+ {nil, // 22
340
+ []byte{0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
341
+ []byte{0xa4, 0x84, 0xc3, 0xad, 0x38, 0xdc, 0x9c, 0x19}},
342
+ {nil, // 23
343
+ []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00},
344
+ []byte{0xfb, 0xe0, 0x0a, 0x8a, 0x1e, 0xf8, 0xad, 0x72}},
345
+ {nil, // 24
346
+ []byte{0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00},
347
+ []byte{0x75, 0x0d, 0x07, 0x94, 0x07, 0x52, 0x13, 0x63}},
348
+ {nil, // 25
349
+ []byte{0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00},
350
+ []byte{0x64, 0xfe, 0xed, 0x9c, 0x72, 0x4c, 0x2f, 0xaf}},
351
+ {nil, // 26
352
+ []byte{0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00},
353
+ []byte{0xf0, 0x2b, 0x26, 0x3b, 0x32, 0x8e, 0x2b, 0x60}},
354
+ {nil, // 27
355
+ []byte{0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00},
356
+ []byte{0x9d, 0x64, 0x55, 0x5a, 0x9a, 0x10, 0xb8, 0x52}},
357
+ {nil, // 28
358
+ []byte{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00},
359
+ []byte{0xd1, 0x06, 0xff, 0x0b, 0xed, 0x52, 0x55, 0xd7}},
360
+ {nil, // 29
361
+ []byte{0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00},
362
+ []byte{0xe1, 0x65, 0x2c, 0x6b, 0x13, 0x8c, 0x64, 0xa5}},
363
+ {nil, // 30
364
+ []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00},
365
+ []byte{0xe4, 0x28, 0x58, 0x11, 0x86, 0xec, 0x8f, 0x46}},
366
+ {nil, // 31
367
+ []byte{0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00},
368
+ []byte{0xae, 0xb5, 0xf5, 0xed, 0xe2, 0x2d, 0x1a, 0x36}},
369
+ {nil, // 32
370
+ []byte{0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00},
371
+ []byte{0xe9, 0x43, 0xd7, 0x56, 0x8a, 0xec, 0x0c, 0x5c}},
372
+ {nil, // 33
373
+ []byte{0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00},
374
+ []byte{0xdf, 0x98, 0xc8, 0x27, 0x6f, 0x54, 0xb0, 0x4b}},
375
+ {nil, // 34
376
+ []byte{0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00},
377
+ []byte{0xb1, 0x60, 0xe4, 0x68, 0x0f, 0x6c, 0x69, 0x6f}},
378
+ {nil, // 35
379
+ []byte{0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00},
380
+ []byte{0xfa, 0x07, 0x52, 0xb0, 0x7d, 0x9c, 0x4a, 0xb8}},
381
+ {nil, // 36
382
+ []byte{0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00},
383
+ []byte{0xca, 0x3a, 0x2b, 0x03, 0x6d, 0xbc, 0x85, 0x02}},
384
+ {nil, // 37
385
+ []byte{0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00},
386
+ []byte{0x5e, 0x09, 0x05, 0x51, 0x7b, 0xb5, 0x9b, 0xcf}},
387
+ {nil, // 38
388
+ []byte{0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00},
389
+ []byte{0x81, 0x4e, 0xeb, 0x3b, 0x91, 0xd9, 0x07, 0x26}},
390
+ {nil, // 39
391
+ []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00},
392
+ []byte{0x4d, 0x49, 0xdb, 0x15, 0x32, 0x91, 0x9c, 0x9f}},
393
+ {nil, // 40
394
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00},
395
+ []byte{0x25, 0xeb, 0x5f, 0xc3, 0xf8, 0xcf, 0x06, 0x21}},
396
+ {nil, // 41
397
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00},
398
+ []byte{0xab, 0x6a, 0x20, 0xc0, 0x62, 0x0d, 0x1c, 0x6f}},
399
+ {nil, // 42
400
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00},
401
+ []byte{0x79, 0xe9, 0x0d, 0xbc, 0x98, 0xf9, 0x2c, 0xca}},
402
+ {nil, // 43
403
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00},
404
+ []byte{0x86, 0x6e, 0xce, 0xdd, 0x80, 0x72, 0xbb, 0x0e}},
405
+ {nil, // 44
406
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00},
407
+ []byte{0x8b, 0x54, 0x53, 0x6f, 0x2f, 0x3e, 0x64, 0xa8}},
408
+ {nil, // 45
409
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00},
410
+ []byte{0xea, 0x51, 0xd3, 0x97, 0x55, 0x95, 0xb8, 0x6b}},
411
+ {nil, // 46
412
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00},
413
+ []byte{0xca, 0xff, 0xc6, 0xac, 0x45, 0x42, 0xde, 0x31}},
414
+ {nil, // 47
415
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00},
416
+ []byte{0x8d, 0xd4, 0x5a, 0x2d, 0xdf, 0x90, 0x79, 0x6c}},
417
+ {nil, // 48
418
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00},
419
+ []byte{0x10, 0x29, 0xd5, 0x5e, 0x88, 0x0e, 0xc2, 0xd0}},
420
+ {nil, // 49
421
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00},
422
+ []byte{0x5d, 0x86, 0xcb, 0x23, 0x63, 0x9d, 0xbe, 0xa9}},
423
+ {nil, // 50
424
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00},
425
+ []byte{0x1d, 0x1c, 0xa8, 0x53, 0xae, 0x7c, 0x0c, 0x5f}},
426
+ {nil, // 51
427
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00},
428
+ []byte{0xce, 0x33, 0x23, 0x29, 0x24, 0x8f, 0x32, 0x28}},
429
+ {nil, // 52
430
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00},
431
+ []byte{0x84, 0x05, 0xd1, 0xab, 0xe2, 0x4f, 0xb9, 0x42}},
432
+ {nil, // 53
433
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00},
434
+ []byte{0xe6, 0x43, 0xd7, 0x80, 0x90, 0xca, 0x42, 0x07}},
435
+ {nil, // 54
436
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00},
437
+ []byte{0x48, 0x22, 0x1b, 0x99, 0x37, 0x74, 0x8a, 0x23}},
438
+ {nil, // 55
439
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00},
440
+ []byte{0xdd, 0x7c, 0x0b, 0xbd, 0x61, 0xfa, 0xfd, 0x54}},
441
+ {nil, // 56
442
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80},
443
+ []byte{0x2f, 0xbc, 0x29, 0x1a, 0x57, 0x0d, 0xb5, 0xc4}},
444
+ {nil, // 57
445
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40},
446
+ []byte{0xe0, 0x7c, 0x30, 0xd7, 0xe4, 0xe2, 0x6e, 0x12}},
447
+ {nil, // 58
448
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20},
449
+ []byte{0x09, 0x53, 0xe2, 0x25, 0x8e, 0x8e, 0x90, 0xa1}},
450
+ {nil, // 59
451
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10},
452
+ []byte{0x5b, 0x71, 0x1b, 0xc4, 0xce, 0xeb, 0xf2, 0xee}},
453
+ {nil, // 60
454
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08},
455
+ []byte{0xcc, 0x08, 0x3f, 0x1e, 0x6d, 0x9e, 0x85, 0xf6}},
456
+ {nil, // 61
457
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04},
458
+ []byte{0xd2, 0xfd, 0x88, 0x67, 0xd5, 0x0d, 0x2d, 0xfe}},
459
+ {nil, // 62
460
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
461
+ []byte{0x06, 0xe7, 0xea, 0x22, 0xce, 0x92, 0x70, 0x8f}},
462
+ {nil, // 63
463
+ []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
464
+ []byte{0x16, 0x6b, 0x40, 0xb4, 0x4a, 0xba, 0x4b, 0xd6}},
465
+ }
466
+
467
+ // Plaintext for use with Table A.2 tests
468
+ var tableA2Plaintext = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
469
+
470
+ // Table A.2 Resulting Ciphertext from the Variable Key Known Answer Test
471
+ var tableA2Tests = []CryptTest{
472
+ { // 0
473
+ []byte{
474
+ 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
475
+ 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
476
+ 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
477
+ nil,
478
+ []byte{0x95, 0xa8, 0xd7, 0x28, 0x13, 0xda, 0xa9, 0x4d}},
479
+ { // 1
480
+ []byte{
481
+ 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
482
+ 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
483
+ 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
484
+ nil,
485
+ []byte{0x0e, 0xec, 0x14, 0x87, 0xdd, 0x8c, 0x26, 0xd5}},
486
+ { // 2
487
+ []byte{
488
+ 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
489
+ 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
490
+ 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
491
+ nil,
492
+ []byte{0x7a, 0xd1, 0x6f, 0xfb, 0x79, 0xc4, 0x59, 0x26}},
493
+ { // 3
494
+ []byte{
495
+ 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
496
+ 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
497
+ 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
498
+ nil,
499
+ []byte{0xd3, 0x74, 0x62, 0x94, 0xca, 0x6a, 0x6c, 0xf3}},
500
+ { // 4
501
+ []byte{
502
+ 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
503
+ 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
504
+ 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
505
+ nil,
506
+ []byte{0x80, 0x9f, 0x5f, 0x87, 0x3c, 0x1f, 0xd7, 0x61}},
507
+ { // 5
508
+ []byte{
509
+ 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
510
+ 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
511
+ 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
512
+ nil,
513
+ []byte{0xc0, 0x2f, 0xaf, 0xfe, 0xc9, 0x89, 0xd1, 0xfc}},
514
+ { // 6
515
+ []byte{
516
+ 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
517
+ 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
518
+ 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
519
+ nil,
520
+ []byte{0x46, 0x15, 0xaa, 0x1d, 0x33, 0xe7, 0x2f, 0x10}},
521
+ { // 7
522
+ []byte{
523
+ 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
524
+ 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
525
+ 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
526
+ nil,
527
+ []byte{0x20, 0x55, 0x12, 0x33, 0x50, 0xc0, 0x08, 0x58}},
528
+ { // 8
529
+ []byte{
530
+ 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
531
+ 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
532
+ 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
533
+ nil,
534
+ []byte{0xdf, 0x3b, 0x99, 0xd6, 0x57, 0x73, 0x97, 0xc8}},
535
+ { // 9
536
+ []byte{
537
+ 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
538
+ 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
539
+ 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
540
+ nil,
541
+ []byte{0x31, 0xfe, 0x17, 0x36, 0x9b, 0x52, 0x88, 0xc9}},
542
+ { // 10
543
+ []byte{
544
+ 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
545
+ 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
546
+ 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
547
+ nil,
548
+ []byte{0xdf, 0xdd, 0x3c, 0xc6, 0x4d, 0xae, 0x16, 0x42}},
549
+ { // 11
550
+ []byte{
551
+ 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
552
+ 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
553
+ 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
554
+ nil,
555
+ []byte{0x17, 0x8c, 0x83, 0xce, 0x2b, 0x39, 0x9d, 0x94}},
556
+ { // 12
557
+ []byte{
558
+ 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
559
+ 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
560
+ 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
561
+ nil,
562
+ []byte{0x50, 0xf6, 0x36, 0x32, 0x4a, 0x9b, 0x7f, 0x80}},
563
+ { // 13
564
+ []byte{
565
+ 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
566
+ 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
567
+ 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
568
+ nil,
569
+ []byte{0xa8, 0x46, 0x8e, 0xe3, 0xbc, 0x18, 0xf0, 0x6d}},
570
+ { // 14
571
+ []byte{
572
+ 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01,
573
+ 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01,
574
+ 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01},
575
+ nil,
576
+ []byte{0xa2, 0xdc, 0x9e, 0x92, 0xfd, 0x3c, 0xde, 0x92}},
577
+ { // 15
578
+ []byte{
579
+ 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01,
580
+ 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01,
581
+ 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01},
582
+ nil,
583
+ []byte{0xca, 0xc0, 0x9f, 0x79, 0x7d, 0x03, 0x12, 0x87}},
584
+ { // 16
585
+ []byte{
586
+ 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01,
587
+ 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01,
588
+ 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01},
589
+ nil,
590
+ []byte{0x90, 0xba, 0x68, 0x0b, 0x22, 0xae, 0xb5, 0x25}},
591
+ { // 17
592
+ []byte{
593
+ 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01,
594
+ 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01,
595
+ 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01},
596
+ nil,
597
+ []byte{0xce, 0x7a, 0x24, 0xf3, 0x50, 0xe2, 0x80, 0xb6}},
598
+ { // 18
599
+ []byte{
600
+ 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01,
601
+ 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01,
602
+ 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01},
603
+ nil,
604
+ []byte{0x88, 0x2b, 0xff, 0x0a, 0xa0, 0x1a, 0x0b, 0x87}},
605
+ { // 19
606
+ []byte{
607
+ 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01,
608
+ 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01,
609
+ 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01},
610
+ nil,
611
+ []byte{0x25, 0x61, 0x02, 0x88, 0x92, 0x45, 0x11, 0xc2}},
612
+ { // 20
613
+ []byte{
614
+ 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01,
615
+ 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01,
616
+ 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01},
617
+ nil,
618
+ []byte{0xc7, 0x15, 0x16, 0xc2, 0x9c, 0x75, 0xd1, 0x70}},
619
+ { // 21
620
+ []byte{
621
+ 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01,
622
+ 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01,
623
+ 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01},
624
+ nil,
625
+ []byte{0x51, 0x99, 0xc2, 0x9a, 0x52, 0xc9, 0xf0, 0x59}},
626
+ { // 22
627
+ []byte{
628
+ 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01,
629
+ 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01,
630
+ 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01},
631
+ nil,
632
+ []byte{0xc2, 0x2f, 0x0a, 0x29, 0x4a, 0x71, 0xf2, 0x9f}},
633
+ { // 23
634
+ []byte{
635
+ 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01,
636
+ 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01,
637
+ 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01},
638
+ nil,
639
+ []byte{0xee, 0x37, 0x14, 0x83, 0x71, 0x4c, 0x02, 0xea}},
640
+ { // 24
641
+ []byte{
642
+ 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01,
643
+ 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01,
644
+ 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01},
645
+ nil,
646
+ []byte{0xa8, 0x1f, 0xbd, 0x44, 0x8f, 0x9e, 0x52, 0x2f}},
647
+ { // 25
648
+ []byte{
649
+ 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01,
650
+ 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01,
651
+ 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01},
652
+ nil,
653
+ []byte{0x4f, 0x64, 0x4c, 0x92, 0xe1, 0x92, 0xdf, 0xed}},
654
+ { // 26
655
+ []byte{
656
+ 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01,
657
+ 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01,
658
+ 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01},
659
+ nil,
660
+ []byte{0x1a, 0xfa, 0x9a, 0x66, 0xa6, 0xdf, 0x92, 0xae}},
661
+ { // 27
662
+ []byte{
663
+ 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
664
+ 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
665
+ 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01},
666
+ nil,
667
+ []byte{0xb3, 0xc1, 0xcc, 0x71, 0x5c, 0xb8, 0x79, 0xd8}},
668
+ { // 28
669
+ []byte{
670
+ 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01,
671
+ 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01,
672
+ 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01},
673
+ nil,
674
+ []byte{0x19, 0xd0, 0x32, 0xe6, 0x4a, 0xb0, 0xbd, 0x8b}},
675
+ { // 29
676
+ []byte{
677
+ 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01,
678
+ 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01,
679
+ 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01},
680
+ nil,
681
+ []byte{0x3c, 0xfa, 0xa7, 0xa7, 0xdc, 0x87, 0x20, 0xdc}},
682
+ { // 30
683
+ []byte{
684
+ 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01,
685
+ 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01,
686
+ 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01},
687
+ nil,
688
+ []byte{0xb7, 0x26, 0x5f, 0x7f, 0x44, 0x7a, 0xc6, 0xf3}},
689
+ { // 31
690
+ []byte{
691
+ 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01,
692
+ 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01,
693
+ 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01},
694
+ nil,
695
+ []byte{0x9d, 0xb7, 0x3b, 0x3c, 0x0d, 0x16, 0x3f, 0x54}},
696
+ { // 32
697
+ []byte{
698
+ 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01,
699
+ 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01,
700
+ 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01},
701
+ nil,
702
+ []byte{0x81, 0x81, 0xb6, 0x5b, 0xab, 0xf4, 0xa9, 0x75}},
703
+ { // 33
704
+ []byte{
705
+ 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01,
706
+ 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01,
707
+ 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01},
708
+ nil,
709
+ []byte{0x93, 0xc9, 0xb6, 0x40, 0x42, 0xea, 0xa2, 0x40}},
710
+ { // 34
711
+ []byte{
712
+ 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
713
+ 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
714
+ 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01},
715
+ nil,
716
+ []byte{0x55, 0x70, 0x53, 0x08, 0x29, 0x70, 0x55, 0x92}},
717
+ { // 35
718
+ []byte{
719
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01,
720
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01,
721
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01},
722
+ nil,
723
+ []byte{0x86, 0x38, 0x80, 0x9e, 0x87, 0x87, 0x87, 0xa0}},
724
+ { // 36
725
+ []byte{
726
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01,
727
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01,
728
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01},
729
+ nil,
730
+ []byte{0x41, 0xb9, 0xa7, 0x9a, 0xf7, 0x9a, 0xc2, 0x08}},
731
+ { // 37
732
+ []byte{
733
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01,
734
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01,
735
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01},
736
+ nil,
737
+ []byte{0x7a, 0x9b, 0xe4, 0x2f, 0x20, 0x09, 0xa8, 0x92}},
738
+ { // 38
739
+ []byte{
740
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01,
741
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01,
742
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01},
743
+ nil,
744
+ []byte{0x29, 0x03, 0x8d, 0x56, 0xba, 0x6d, 0x27, 0x45}},
745
+ { // 39
746
+ []byte{
747
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01,
748
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01,
749
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01},
750
+ nil,
751
+ []byte{0x54, 0x95, 0xc6, 0xab, 0xf1, 0xe5, 0xdf, 0x51}},
752
+ { // 40
753
+ []byte{
754
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01,
755
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01,
756
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01},
757
+ nil,
758
+ []byte{0xae, 0x13, 0xdb, 0xd5, 0x61, 0x48, 0x89, 0x33}},
759
+ { // 41
760
+ []byte{
761
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01,
762
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01,
763
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01},
764
+ nil,
765
+ []byte{0x02, 0x4d, 0x1f, 0xfa, 0x89, 0x04, 0xe3, 0x89}},
766
+ { // 42
767
+ []byte{
768
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01,
769
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01,
770
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01},
771
+ nil,
772
+ []byte{0xd1, 0x39, 0x97, 0x12, 0xf9, 0x9b, 0xf0, 0x2e}},
773
+ { // 43
774
+ []byte{
775
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01,
776
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01,
777
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01},
778
+ nil,
779
+ []byte{0x14, 0xc1, 0xd7, 0xc1, 0xcf, 0xfe, 0xc7, 0x9e}},
780
+ { // 44
781
+ []byte{
782
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01,
783
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01,
784
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01},
785
+ nil,
786
+ []byte{0x1d, 0xe5, 0x27, 0x9d, 0xae, 0x3b, 0xed, 0x6f}},
787
+ { // 45
788
+ []byte{
789
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01,
790
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01,
791
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01},
792
+ nil,
793
+ []byte{0xe9, 0x41, 0xa3, 0x3f, 0x85, 0x50, 0x13, 0x03}},
794
+ { // 46
795
+ []byte{
796
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01,
797
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01,
798
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01},
799
+ nil,
800
+ []byte{0xda, 0x99, 0xdb, 0xbc, 0x9a, 0x03, 0xf3, 0x79}},
801
+ { // 47
802
+ []byte{
803
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01,
804
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01,
805
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01},
806
+ nil,
807
+ []byte{0xb7, 0xfc, 0x92, 0xf9, 0x1d, 0x8e, 0x92, 0xe9}},
808
+ { // 48
809
+ []byte{
810
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01,
811
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01,
812
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01},
813
+ nil,
814
+ []byte{0xae, 0x8e, 0x5c, 0xaa, 0x3c, 0xa0, 0x4e, 0x85}},
815
+ { // 49
816
+ []byte{
817
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80,
818
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80,
819
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80},
820
+ nil,
821
+ []byte{0x9c, 0xc6, 0x2d, 0xf4, 0x3b, 0x6e, 0xed, 0x74}},
822
+ { // 50
823
+ []byte{
824
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40,
825
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40,
826
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40},
827
+ nil,
828
+ []byte{0xd8, 0x63, 0xdb, 0xb5, 0xc5, 0x9a, 0x91, 0xa0}},
829
+ { // 50
830
+ []byte{
831
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20,
832
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20,
833
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20},
834
+ nil,
835
+ []byte{0xa1, 0xab, 0x21, 0x90, 0x54, 0x5b, 0x91, 0xd7}},
836
+ { // 52
837
+ []byte{
838
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10,
839
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10,
840
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10},
841
+ nil,
842
+ []byte{0x08, 0x75, 0x04, 0x1e, 0x64, 0xc5, 0x70, 0xf7}},
843
+ { // 53
844
+ []byte{
845
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08,
846
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08,
847
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08},
848
+ nil,
849
+ []byte{0x5a, 0x59, 0x45, 0x28, 0xbe, 0xbe, 0xf1, 0xcc}},
850
+ { // 54
851
+ []byte{
852
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04,
853
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04,
854
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04},
855
+ nil,
856
+ []byte{0xfc, 0xdb, 0x32, 0x91, 0xde, 0x21, 0xf0, 0xc0}},
857
+ { // 55
858
+ []byte{
859
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02,
860
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02,
861
+ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02},
862
+ nil,
863
+ []byte{0x86, 0x9e, 0xfd, 0x7f, 0x9f, 0x26, 0x5a, 0x09}},
864
+ }
865
+
866
+ // Plaintext for use with Table A.3 tests
867
+ var tableA3Plaintext = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
868
+
869
+ // Table A.3 Values To Be Used for the Permutation Operation Known Answer Test
870
+ var tableA3Tests = []CryptTest{
871
+ { // 0
872
+ []byte{
873
+ 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31,
874
+ 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31,
875
+ 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31,
876
+ },
877
+ nil,
878
+ []byte{0x88, 0xd5, 0x5e, 0x54, 0xf5, 0x4c, 0x97, 0xb4}},
879
+ { // 1
880
+ []byte{
881
+ 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
882
+ 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
883
+ 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
884
+ },
885
+ nil,
886
+ []byte{0x0c, 0x0c, 0xc0, 0x0c, 0x83, 0xea, 0x48, 0xfd}},
887
+ { // 2
888
+ []byte{
889
+ 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20,
890
+ 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20,
891
+ 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20,
892
+ },
893
+ nil,
894
+ []byte{0x83, 0xbc, 0x8e, 0xf3, 0xa6, 0x57, 0x01, 0x83}},
895
+ { // 3
896
+ []byte{
897
+ 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
898
+ 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
899
+ 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20,
900
+ },
901
+ nil,
902
+ []byte{0xdf, 0x72, 0x5d, 0xca, 0xd9, 0x4e, 0xa2, 0xe9}},
903
+ { // 4
904
+ []byte{
905
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01,
906
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01,
907
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01,
908
+ },
909
+ nil,
910
+ []byte{0xe6, 0x52, 0xb5, 0x3b, 0x55, 0x0b, 0xe8, 0xb0}},
911
+ { // 5
912
+ []byte{
913
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01,
914
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01,
915
+ 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01,
916
+ },
917
+ nil,
918
+ []byte{0xaf, 0x52, 0x71, 0x20, 0xc4, 0x85, 0xcb, 0xb0}},
919
+ { // 6
920
+ []byte{
921
+ 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01,
922
+ 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01,
923
+ 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01,
924
+ },
925
+ nil,
926
+ []byte{0x0f, 0x04, 0xce, 0x39, 0x3d, 0xb9, 0x26, 0xd5}},
927
+ { // 7
928
+ []byte{
929
+ 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01,
930
+ 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01,
931
+ 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01,
932
+ },
933
+ nil,
934
+ []byte{0xc9, 0xf0, 0x0f, 0xfc, 0x74, 0x07, 0x90, 0x67}},
935
+ { // 8
936
+ []byte{
937
+ 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01,
938
+ 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01,
939
+ 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01,
940
+ },
941
+ nil,
942
+ []byte{0x7c, 0xfd, 0x82, 0xa5, 0x93, 0x25, 0x2b, 0x4e}},
943
+ { // 9
944
+ []byte{
945
+ 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01,
946
+ 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01,
947
+ 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01,
948
+ },
949
+ nil,
950
+ []byte{0xcb, 0x49, 0xa2, 0xf9, 0xe9, 0x13, 0x63, 0xe3}},
951
+ { // 10
952
+ []byte{
953
+ 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40,
954
+ 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40,
955
+ 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40,
956
+ },
957
+ nil,
958
+ []byte{0x00, 0xb5, 0x88, 0xbe, 0x70, 0xd2, 0x3f, 0x56}},
959
+ { // 11
960
+ []byte{
961
+ 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40,
962
+ 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40,
963
+ 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40,
964
+ },
965
+ nil,
966
+ []byte{0x40, 0x6a, 0x9a, 0x6a, 0xb4, 0x33, 0x99, 0xae}},
967
+ { // 12
968
+ []byte{
969
+ 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01,
970
+ 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01,
971
+ 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01,
972
+ },
973
+ nil,
974
+ []byte{0x6c, 0xb7, 0x73, 0x61, 0x1d, 0xca, 0x9a, 0xda}},
975
+ { // 13
976
+ []byte{
977
+ 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01,
978
+ 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01,
979
+ 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01,
980
+ },
981
+ nil,
982
+ []byte{0x67, 0xfd, 0x21, 0xc1, 0x7d, 0xbb, 0x5d, 0x70}},
983
+ { // 14
984
+ []byte{
985
+ 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01,
986
+ 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01,
987
+ 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01,
988
+ },
989
+ nil,
990
+ []byte{0x95, 0x92, 0xcb, 0x41, 0x10, 0x43, 0x07, 0x87}},
991
+ { // 15
992
+ []byte{
993
+ 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20,
994
+ 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20,
995
+ 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20,
996
+ },
997
+ nil,
998
+ []byte{0xa6, 0xb7, 0xff, 0x68, 0xa3, 0x18, 0xdd, 0xd3}},
999
+ { // 16
1000
+ []byte{
1001
+ 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01,
1002
+ 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01,
1003
+ 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01,
1004
+ },
1005
+ nil,
1006
+ []byte{0x4d, 0x10, 0x21, 0x96, 0xc9, 0x14, 0xca, 0x16}},
1007
+ { // 17
1008
+ []byte{
1009
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01,
1010
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01,
1011
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01,
1012
+ },
1013
+ nil,
1014
+ []byte{0x2d, 0xfa, 0x9f, 0x45, 0x73, 0x59, 0x49, 0x65}},
1015
+ { // 18
1016
+ []byte{
1017
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01,
1018
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01,
1019
+ 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01,
1020
+ },
1021
+ nil,
1022
+ []byte{0xb4, 0x66, 0x04, 0x81, 0x6c, 0x0e, 0x07, 0x74}},
1023
+ { // 19
1024
+ []byte{
1025
+ 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01,
1026
+ 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01,
1027
+ 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01,
1028
+ },
1029
+ nil,
1030
+ []byte{0x6e, 0x7e, 0x62, 0x21, 0xa4, 0xf3, 0x4e, 0x87}},
1031
+ { // 20
1032
+ []byte{
1033
+ 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01,
1034
+ 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01,
1035
+ 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01,
1036
+ },
1037
+ nil,
1038
+ []byte{0xaa, 0x85, 0xe7, 0x46, 0x43, 0x23, 0x31, 0x99}},
1039
+ { // 21
1040
+ []byte{
1041
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01,
1042
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01,
1043
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01,
1044
+ },
1045
+ nil,
1046
+ []byte{0x2e, 0x5a, 0x19, 0xdb, 0x4d, 0x19, 0x62, 0xd6}},
1047
+ { // 22
1048
+ []byte{
1049
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01,
1050
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01,
1051
+ 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01,
1052
+ },
1053
+ nil,
1054
+ []byte{0x23, 0xa8, 0x66, 0xa8, 0x09, 0xd3, 0x08, 0x94}},
1055
+ { // 23
1056
+ []byte{
1057
+ 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01,
1058
+ 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01,
1059
+ 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01,
1060
+ },
1061
+ nil,
1062
+ []byte{0xd8, 0x12, 0xd9, 0x61, 0xf0, 0x17, 0xd3, 0x20}},
1063
+ { // 24
1064
+ []byte{
1065
+ 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b,
1066
+ 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b,
1067
+ 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b,
1068
+ },
1069
+ nil,
1070
+ []byte{0x05, 0x56, 0x05, 0x81, 0x6e, 0x58, 0x60, 0x8f}},
1071
+ { // 25
1072
+ []byte{
1073
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01,
1074
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01,
1075
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01,
1076
+ },
1077
+ nil,
1078
+ []byte{0xab, 0xd8, 0x8e, 0x8b, 0x1b, 0x77, 0x16, 0xf1}},
1079
+ { // 26
1080
+ []byte{
1081
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02,
1082
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02,
1083
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02,
1084
+ },
1085
+ nil,
1086
+ []byte{0x53, 0x7a, 0xc9, 0x5b, 0xe6, 0x9d, 0xa1, 0xe1}},
1087
+ { // 27
1088
+ []byte{
1089
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08,
1090
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08,
1091
+ 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08,
1092
+ },
1093
+ nil,
1094
+ []byte{0xae, 0xd0, 0xf6, 0xae, 0x3c, 0x25, 0xcd, 0xd8}},
1095
+ { // 28
1096
+ []byte{
1097
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04,
1098
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04,
1099
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04,
1100
+ },
1101
+ nil,
1102
+ []byte{0xb3, 0xe3, 0x5a, 0x5e, 0xe5, 0x3e, 0x7b, 0x8d}},
1103
+ { // 29
1104
+ []byte{
1105
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04,
1106
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04,
1107
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04,
1108
+ },
1109
+ nil,
1110
+ []byte{0x61, 0xc7, 0x9c, 0x71, 0x92, 0x1a, 0x2e, 0xf8}},
1111
+ { // 30
1112
+ []byte{
1113
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01,
1114
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01,
1115
+ 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01,
1116
+ },
1117
+ nil,
1118
+ []byte{0xe2, 0xf5, 0x72, 0x8f, 0x09, 0x95, 0x01, 0x3c}},
1119
+ { // 31
1120
+ []byte{
1121
+ 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01,
1122
+ 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01,
1123
+ 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01,
1124
+ },
1125
+ nil,
1126
+ []byte{0x1a, 0xea, 0xc3, 0x9a, 0x61, 0xf0, 0xa4, 0x64}},
1127
+ }
1128
+
1129
+ // Table A.4 Values To Be Used for the Substitution Table Known Answer Test
1130
+ var tableA4Tests = []CryptTest{
1131
+ { // 0
1132
+ []byte{
1133
+ 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57,
1134
+ 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57,
1135
+ 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57},
1136
+ []byte{0x01, 0xa1, 0xd6, 0xd0, 0x39, 0x77, 0x67, 0x42},
1137
+ []byte{0x69, 0x0f, 0x5b, 0x0d, 0x9a, 0x26, 0x93, 0x9b}},
1138
+ { // 1
1139
+ []byte{
1140
+ 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e,
1141
+ 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e,
1142
+ 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e},
1143
+ []byte{0x5c, 0xd5, 0x4c, 0xa8, 0x3d, 0xef, 0x57, 0xda},
1144
+ []byte{0x7a, 0x38, 0x9d, 0x10, 0x35, 0x4b, 0xd2, 0x71}},
1145
+ { // 2
1146
+ []byte{
1147
+ 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86,
1148
+ 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86,
1149
+ 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86},
1150
+ []byte{0x02, 0x48, 0xd4, 0x38, 0x06, 0xf6, 0x71, 0x72},
1151
+ []byte{0x86, 0x8e, 0xbb, 0x51, 0xca, 0xb4, 0x59, 0x9a}},
1152
+ { // 3
1153
+ []byte{
1154
+ 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e,
1155
+ 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e,
1156
+ 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e},
1157
+ []byte{0x51, 0x45, 0x4b, 0x58, 0x2d, 0xdf, 0x44, 0x0a},
1158
+ []byte{0x71, 0x78, 0x87, 0x6e, 0x01, 0xf1, 0x9b, 0x2a}},
1159
+ { // 4
1160
+ []byte{
1161
+ 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6,
1162
+ 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6,
1163
+ 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6},
1164
+ []byte{0x42, 0xfd, 0x44, 0x30, 0x59, 0x57, 0x7f, 0xa2},
1165
+ []byte{0xaf, 0x37, 0xfb, 0x42, 0x1f, 0x8c, 0x40, 0x95}},
1166
+ { // 5
1167
+ []byte{
1168
+ 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce,
1169
+ 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce,
1170
+ 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce},
1171
+ []byte{0x05, 0x9b, 0x5e, 0x08, 0x51, 0xcf, 0x14, 0x3a},
1172
+ []byte{0x86, 0xa5, 0x60, 0xf1, 0x0e, 0xc6, 0xd8, 0x5b}},
1173
+ { // 6
1174
+ []byte{
1175
+ 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6,
1176
+ 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6,
1177
+ 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6},
1178
+ []byte{0x07, 0x56, 0xd8, 0xe0, 0x77, 0x47, 0x61, 0xd2},
1179
+ []byte{0x0c, 0xd3, 0xda, 0x02, 0x00, 0x21, 0xdc, 0x09}},
1180
+ { // 7
1181
+ []byte{
1182
+ 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe,
1183
+ 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe,
1184
+ 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe},
1185
+ []byte{0x76, 0x25, 0x14, 0xb8, 0x29, 0xbf, 0x48, 0x6a},
1186
+ []byte{0xea, 0x67, 0x6b, 0x2c, 0xb7, 0xdb, 0x2b, 0x7a}},
1187
+ { // 8
1188
+ []byte{
1189
+ 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16,
1190
+ 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16,
1191
+ 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16},
1192
+ []byte{0x3b, 0xdd, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02},
1193
+ []byte{0xdf, 0xd6, 0x4a, 0x81, 0x5c, 0xaf, 0x1a, 0x0f}},
1194
+ { // 9
1195
+ []byte{
1196
+ 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f,
1197
+ 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f,
1198
+ 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f},
1199
+ []byte{0x26, 0x95, 0x5f, 0x68, 0x35, 0xaf, 0x60, 0x9a},
1200
+ []byte{0x5c, 0x51, 0x3c, 0x9c, 0x48, 0x86, 0xc0, 0x88}},
1201
+ { // 10
1202
+ []byte{
1203
+ 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46,
1204
+ 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46,
1205
+ 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46},
1206
+ []byte{0x16, 0x4d, 0x5e, 0x40, 0x4f, 0x27, 0x52, 0x32},
1207
+ []byte{0x0a, 0x2a, 0xee, 0xae, 0x3f, 0xf4, 0xab, 0x77}},
1208
+ { // 11
1209
+ []byte{
1210
+ 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e,
1211
+ 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e,
1212
+ 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e},
1213
+ []byte{0x6b, 0x05, 0x6e, 0x18, 0x75, 0x9f, 0x5c, 0xca},
1214
+ []byte{0xef, 0x1b, 0xf0, 0x3e, 0x5d, 0xfa, 0x57, 0x5a}},
1215
+ { // 12
1216
+ []byte{
1217
+ 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76,
1218
+ 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76,
1219
+ 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76},
1220
+ []byte{0x00, 0x4b, 0xd6, 0xef, 0x09, 0x17, 0x60, 0x62},
1221
+ []byte{0x88, 0xbf, 0x0d, 0xb6, 0xd7, 0x0d, 0xee, 0x56}},
1222
+ { // 13
1223
+ []byte{
1224
+ 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07,
1225
+ 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07,
1226
+ 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07},
1227
+ []byte{0x48, 0x0d, 0x39, 0x00, 0x6e, 0xe7, 0x62, 0xf2},
1228
+ []byte{0xa1, 0xf9, 0x91, 0x55, 0x41, 0x02, 0x0b, 0x56}},
1229
+ { // 14
1230
+ []byte{
1231
+ 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f,
1232
+ 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f,
1233
+ 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f},
1234
+ []byte{0x43, 0x75, 0x40, 0xc8, 0x69, 0x8f, 0x3c, 0xfa},
1235
+ []byte{0x6f, 0xbf, 0x1c, 0xaf, 0xcf, 0xfd, 0x05, 0x56}},
1236
+ { // 15
1237
+ []byte{
1238
+ 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7,
1239
+ 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7,
1240
+ 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7},
1241
+ []byte{0x07, 0x2d, 0x43, 0xa0, 0x77, 0x07, 0x52, 0x92},
1242
+ []byte{0x2f, 0x22, 0xe4, 0x9b, 0xab, 0x7c, 0xa1, 0xac}},
1243
+ { // 16
1244
+ []byte{
1245
+ 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf,
1246
+ 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf,
1247
+ 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf},
1248
+ []byte{0x02, 0xfe, 0x55, 0x77, 0x81, 0x17, 0xf1, 0x2a},
1249
+ []byte{0x5a, 0x6b, 0x61, 0x2c, 0xc2, 0x6c, 0xce, 0x4a}},
1250
+ { // 17
1251
+ []byte{
1252
+ 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6,
1253
+ 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6,
1254
+ 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6},
1255
+ []byte{0x1d, 0x9d, 0x5c, 0x50, 0x18, 0xf7, 0x28, 0xc2},
1256
+ []byte{0x5f, 0x4c, 0x03, 0x8e, 0xd1, 0x2b, 0x2e, 0x41}},
1257
+ { // 18
1258
+ []byte{
1259
+ 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef,
1260
+ 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef,
1261
+ 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef},
1262
+ []byte{0x30, 0x55, 0x32, 0x28, 0x6d, 0x6f, 0x29, 0x5a},
1263
+ []byte{0x63, 0xfa, 0xc0, 0xd0, 0x34, 0xd9, 0xf7, 0x93}},
1264
+ }
1265
+
1266
+ func newCipher(key []byte) cipher.Block {
1267
+ c, err := des.NewCipher(key)
1268
+ if err != nil {
1269
+ panic("NewCipher failed: " + err.Error())
1270
+ }
1271
+ return c
1272
+ }
1273
+
1274
+ // Use the known weak keys to test DES implementation
1275
+ func TestWeakKeys(t *testing.T) {
1276
+ for i, tt := range weakKeyTests {
1277
+ var encrypt = func(in []byte) (out []byte) {
1278
+ c := newCipher(tt.key)
1279
+ out = make([]byte, len(in))
1280
+ c.Encrypt(out, in)
1281
+ return
1282
+ }
1283
+
1284
+ // Encrypting twice with a DES weak
1285
+ // key should reproduce the original input
1286
+ result := encrypt(tt.in)
1287
+ result = encrypt(result)
1288
+
1289
+ if !bytes.Equal(result, tt.in) {
1290
+ t.Errorf("#%d: result: %x want: %x", i, result, tt.in)
1291
+ }
1292
+ }
1293
+ }
1294
+
1295
+ // Use the known semi-weak key pairs to test DES implementation
1296
+ func TestSemiWeakKeyPairs(t *testing.T) {
1297
+ for i, tt := range semiWeakKeyTests {
1298
+ var encrypt = func(key, in []byte) (out []byte) {
1299
+ c := newCipher(key)
1300
+ out = make([]byte, len(in))
1301
+ c.Encrypt(out, in)
1302
+ return
1303
+ }
1304
+
1305
+ // Encrypting with one member of the semi-weak pair
1306
+ // and then encrypting the result with the other member
1307
+ // should reproduce the original input.
1308
+ result := encrypt(tt.key, tt.in)
1309
+ result = encrypt(tt.out, result)
1310
+
1311
+ if !bytes.Equal(result, tt.in) {
1312
+ t.Errorf("#%d: result: %x want: %x", i, result, tt.in)
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ func TestDESEncryptBlock(t *testing.T) {
1318
+ for i, tt := range encryptDESTests {
1319
+ c := newCipher(tt.key)
1320
+ out := make([]byte, len(tt.in))
1321
+ c.Encrypt(out, tt.in)
1322
+
1323
+ if !bytes.Equal(out, tt.out) {
1324
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1325
+ }
1326
+ }
1327
+ }
1328
+
1329
+ func TestDESDecryptBlock(t *testing.T) {
1330
+ for i, tt := range encryptDESTests {
1331
+ c := newCipher(tt.key)
1332
+ plain := make([]byte, len(tt.in))
1333
+ c.Decrypt(plain, tt.out)
1334
+
1335
+ if !bytes.Equal(plain, tt.in) {
1336
+ t.Errorf("#%d: result: %x want: %x", i, plain, tt.in)
1337
+ }
1338
+ }
1339
+ }
1340
+
1341
+ func TestEncryptTripleDES(t *testing.T) {
1342
+ for i, tt := range encryptTripleDESTests {
1343
+ c, _ := des.NewTripleDESCipher(tt.key)
1344
+ out := make([]byte, len(tt.in))
1345
+ c.Encrypt(out, tt.in)
1346
+
1347
+ if !bytes.Equal(out, tt.out) {
1348
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1349
+ }
1350
+ }
1351
+ }
1352
+
1353
+ func TestDecryptTripleDES(t *testing.T) {
1354
+ for i, tt := range encryptTripleDESTests {
1355
+ c, _ := des.NewTripleDESCipher(tt.key)
1356
+
1357
+ plain := make([]byte, len(tt.in))
1358
+ c.Decrypt(plain, tt.out)
1359
+
1360
+ if !bytes.Equal(plain, tt.in) {
1361
+ t.Errorf("#%d: result: %x want: %x", i, plain, tt.in)
1362
+ }
1363
+ }
1364
+ }
1365
+
1366
+ // Defined in Pub 800-20
1367
+ func TestVariablePlaintextKnownAnswer(t *testing.T) {
1368
+ for i, tt := range tableA1Tests {
1369
+ c, _ := des.NewTripleDESCipher(tableA1Key)
1370
+
1371
+ out := make([]byte, len(tt.in))
1372
+ c.Encrypt(out, tt.in)
1373
+
1374
+ if !bytes.Equal(out, tt.out) {
1375
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ // Defined in Pub 800-20
1381
+ func TestVariableCiphertextKnownAnswer(t *testing.T) {
1382
+ for i, tt := range tableA1Tests {
1383
+ c, _ := des.NewTripleDESCipher(tableA1Key)
1384
+
1385
+ plain := make([]byte, len(tt.out))
1386
+ c.Decrypt(plain, tt.out)
1387
+
1388
+ if !bytes.Equal(plain, tt.in) {
1389
+ t.Errorf("#%d: result: %x want: %x", i, plain, tt.in)
1390
+ }
1391
+ }
1392
+ }
1393
+
1394
+ // Defined in Pub 800-20
1395
+ // Encrypting the Table A.1 ciphertext with the
1396
+ // 0x01... key produces the original plaintext
1397
+ func TestInversePermutationKnownAnswer(t *testing.T) {
1398
+ for i, tt := range tableA1Tests {
1399
+ c, _ := des.NewTripleDESCipher(tableA1Key)
1400
+
1401
+ plain := make([]byte, len(tt.in))
1402
+ c.Encrypt(plain, tt.out)
1403
+
1404
+ if !bytes.Equal(plain, tt.in) {
1405
+ t.Errorf("#%d: result: %x want: %x", i, plain, tt.in)
1406
+ }
1407
+ }
1408
+ }
1409
+
1410
+ // Defined in Pub 800-20
1411
+ // Decrypting the Table A.1 plaintext with the
1412
+ // 0x01... key produces the corresponding ciphertext
1413
+ func TestInitialPermutationKnownAnswer(t *testing.T) {
1414
+ for i, tt := range tableA1Tests {
1415
+ c, _ := des.NewTripleDESCipher(tableA1Key)
1416
+
1417
+ out := make([]byte, len(tt.in))
1418
+ c.Decrypt(out, tt.in)
1419
+
1420
+ if !bytes.Equal(out, tt.out) {
1421
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1422
+ }
1423
+ }
1424
+ }
1425
+
1426
+ // Defined in Pub 800-20
1427
+ func TestVariableKeyKnownAnswerEncrypt(t *testing.T) {
1428
+ for i, tt := range tableA2Tests {
1429
+ c, _ := des.NewTripleDESCipher(tt.key)
1430
+
1431
+ out := make([]byte, len(tableA2Plaintext))
1432
+ c.Encrypt(out, tableA2Plaintext)
1433
+
1434
+ if !bytes.Equal(out, tt.out) {
1435
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1436
+ }
1437
+ }
1438
+ }
1439
+
1440
+ // Defined in Pub 800-20
1441
+ func TestVariableKeyKnownAnswerDecrypt(t *testing.T) {
1442
+ for i, tt := range tableA2Tests {
1443
+ c, _ := des.NewTripleDESCipher(tt.key)
1444
+
1445
+ out := make([]byte, len(tt.out))
1446
+ c.Decrypt(out, tt.out)
1447
+
1448
+ if !bytes.Equal(out, tableA2Plaintext) {
1449
+ t.Errorf("#%d: result: %x want: %x", i, out, tableA2Plaintext)
1450
+ }
1451
+ }
1452
+ }
1453
+
1454
+ // Defined in Pub 800-20
1455
+ func TestPermutationOperationKnownAnswerEncrypt(t *testing.T) {
1456
+ for i, tt := range tableA3Tests {
1457
+ c, _ := des.NewTripleDESCipher(tt.key)
1458
+
1459
+ out := make([]byte, len(tableA3Plaintext))
1460
+ c.Encrypt(out, tableA3Plaintext)
1461
+
1462
+ if !bytes.Equal(out, tt.out) {
1463
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1464
+ }
1465
+ }
1466
+ }
1467
+
1468
+ // Defined in Pub 800-20
1469
+ func TestPermutationOperationKnownAnswerDecrypt(t *testing.T) {
1470
+ for i, tt := range tableA3Tests {
1471
+ c, _ := des.NewTripleDESCipher(tt.key)
1472
+
1473
+ out := make([]byte, len(tt.out))
1474
+ c.Decrypt(out, tt.out)
1475
+
1476
+ if !bytes.Equal(out, tableA3Plaintext) {
1477
+ t.Errorf("#%d: result: %x want: %x", i, out, tableA3Plaintext)
1478
+ }
1479
+ }
1480
+ }
1481
+
1482
+ // Defined in Pub 800-20
1483
+ func TestSubstitutionTableKnownAnswerEncrypt(t *testing.T) {
1484
+ for i, tt := range tableA4Tests {
1485
+ c, _ := des.NewTripleDESCipher(tt.key)
1486
+
1487
+ out := make([]byte, len(tt.in))
1488
+ c.Encrypt(out, tt.in)
1489
+
1490
+ if !bytes.Equal(out, tt.out) {
1491
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.out)
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ // Defined in Pub 800-20
1497
+ func TestSubstitutionTableKnownAnswerDecrypt(t *testing.T) {
1498
+ for i, tt := range tableA4Tests {
1499
+ c, _ := des.NewTripleDESCipher(tt.key)
1500
+
1501
+ out := make([]byte, len(tt.out))
1502
+ c.Decrypt(out, tt.out)
1503
+
1504
+ if !bytes.Equal(out, tt.in) {
1505
+ t.Errorf("#%d: result: %x want: %x", i, out, tt.in)
1506
+ }
1507
+ }
1508
+ }
1509
+
1510
+ // Test DES against the general cipher.Block interface tester
1511
+ func TestDESBlock(t *testing.T) {
1512
+ t.Run("DES", func(t *testing.T) {
1513
+ cryptotest.TestBlock(t, 8, des.NewCipher)
1514
+ })
1515
+
1516
+ t.Run("TripleDES", func(t *testing.T) {
1517
+ cryptotest.TestBlock(t, 24, des.NewTripleDESCipher)
1518
+ })
1519
+ }
1520
+
1521
+ func BenchmarkEncrypt(b *testing.B) {
1522
+ tt := encryptDESTests[0]
1523
+ c, err := des.NewCipher(tt.key)
1524
+ if err != nil {
1525
+ b.Fatal("NewCipher:", err)
1526
+ }
1527
+ out := make([]byte, len(tt.in))
1528
+ b.SetBytes(int64(len(out)))
1529
+ b.ResetTimer()
1530
+ for i := 0; i < b.N; i++ {
1531
+ c.Encrypt(out, tt.in)
1532
+ }
1533
+ }
1534
+
1535
+ func BenchmarkDecrypt(b *testing.B) {
1536
+ tt := encryptDESTests[0]
1537
+ c, err := des.NewCipher(tt.key)
1538
+ if err != nil {
1539
+ b.Fatal("NewCipher:", err)
1540
+ }
1541
+ out := make([]byte, len(tt.out))
1542
+ b.SetBytes(int64(len(out)))
1543
+ b.ResetTimer()
1544
+ for i := 0; i < b.N; i++ {
1545
+ c.Decrypt(out, tt.out)
1546
+ }
1547
+ }
1548
+
1549
+ func BenchmarkTDESEncrypt(b *testing.B) {
1550
+ tt := encryptTripleDESTests[0]
1551
+ c, err := des.NewTripleDESCipher(tt.key)
1552
+ if err != nil {
1553
+ b.Fatal("NewCipher:", err)
1554
+ }
1555
+ out := make([]byte, len(tt.in))
1556
+ b.SetBytes(int64(len(out)))
1557
+ b.ResetTimer()
1558
+ for i := 0; i < b.N; i++ {
1559
+ c.Encrypt(out, tt.in)
1560
+ }
1561
+ }
1562
+
1563
+ func BenchmarkTDESDecrypt(b *testing.B) {
1564
+ tt := encryptTripleDESTests[0]
1565
+ c, err := des.NewTripleDESCipher(tt.key)
1566
+ if err != nil {
1567
+ b.Fatal("NewCipher:", err)
1568
+ }
1569
+ out := make([]byte, len(tt.out))
1570
+ b.SetBytes(int64(len(out)))
1571
+ b.ResetTimer()
1572
+ for i := 0; i < b.N; i++ {
1573
+ c.Decrypt(out, tt.out)
1574
+ }
1575
+ }
go/src/crypto/des/example_test.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 des_test
6
+
7
+ import "crypto/des"
8
+
9
+ func ExampleNewTripleDESCipher() {
10
+ // NewTripleDESCipher can also be used when EDE2 is required by
11
+ // duplicating the first 8 bytes of the 16-byte key.
12
+ ede2Key := []byte("example key 1234")
13
+
14
+ var tripleDESKey []byte
15
+ tripleDESKey = append(tripleDESKey, ede2Key[:16]...)
16
+ tripleDESKey = append(tripleDESKey, ede2Key[:8]...)
17
+
18
+ _, err := des.NewTripleDESCipher(tripleDESKey)
19
+ if err != nil {
20
+ panic(err)
21
+ }
22
+
23
+ // See crypto/cipher for how to use a cipher.Block for encryption and
24
+ // decryption.
25
+ }
go/src/crypto/des/internal_test.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 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 des
6
+
7
+ import "testing"
8
+
9
+ func TestInitialPermute(t *testing.T) {
10
+ for i := uint(0); i < 64; i++ {
11
+ bit := uint64(1) << i
12
+ got := permuteInitialBlock(bit)
13
+ want := uint64(1) << finalPermutation[63-i]
14
+ if got != want {
15
+ t.Errorf("permute(%x) = %x, want %x", bit, got, want)
16
+ }
17
+ }
18
+ }
19
+
20
+ func TestFinalPermute(t *testing.T) {
21
+ for i := uint(0); i < 64; i++ {
22
+ bit := uint64(1) << i
23
+ got := permuteFinalBlock(bit)
24
+ want := uint64(1) << initialPermutation[63-i]
25
+ if got != want {
26
+ t.Errorf("permute(%x) = %x, want %x", bit, got, want)
27
+ }
28
+ }
29
+ }
go/src/crypto/dsa/dsa.go ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
6
+ //
7
+ // The DSA operations in this package are not implemented using constant-time algorithms.
8
+ //
9
+ // Deprecated: DSA is a legacy algorithm, and modern alternatives such as
10
+ // Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys
11
+ // with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while
12
+ // bigger keys are not widely supported. Note that FIPS 186-5 no longer approves
13
+ // DSA for signature generation.
14
+ package dsa
15
+
16
+ import (
17
+ "errors"
18
+ "io"
19
+ "math/big"
20
+
21
+ "crypto/internal/fips140only"
22
+ "crypto/internal/rand"
23
+ )
24
+
25
+ // Parameters represents the domain parameters for a key. These parameters can
26
+ // be shared across many keys. The bit length of Q must be a multiple of 8.
27
+ type Parameters struct {
28
+ P, Q, G *big.Int
29
+ }
30
+
31
+ // PublicKey represents a DSA public key.
32
+ type PublicKey struct {
33
+ Parameters
34
+ Y *big.Int
35
+ }
36
+
37
+ // PrivateKey represents a DSA private key.
38
+ type PrivateKey struct {
39
+ PublicKey
40
+ X *big.Int
41
+ }
42
+
43
+ // ErrInvalidPublicKey results when a public key is not usable by this code.
44
+ // FIPS is quite strict about the format of DSA keys, but other code may be
45
+ // less so. Thus, when using keys which may have been generated by other code,
46
+ // this error must be handled.
47
+ var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")
48
+
49
+ // ParameterSizes is an enumeration of the acceptable bit lengths of the primes
50
+ // in a set of DSA parameters. See FIPS 186-3, section 4.2.
51
+ type ParameterSizes int
52
+
53
+ const (
54
+ L1024N160 ParameterSizes = iota
55
+ L2048N224
56
+ L2048N256
57
+ L3072N256
58
+ )
59
+
60
+ // numMRTests is the number of Miller-Rabin primality tests that we perform. We
61
+ // pick the largest recommended number from table C.1 of FIPS 186-3.
62
+ const numMRTests = 64
63
+
64
+ // GenerateParameters puts a random, valid set of DSA parameters into params.
65
+ // This function can take many seconds, even on fast machines.
66
+ func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error {
67
+ if fips140only.Enforced() {
68
+ return errors.New("crypto/dsa: use of DSA is not allowed in FIPS 140-only mode")
69
+ }
70
+
71
+ // This function doesn't follow FIPS 186-3 exactly in that it doesn't
72
+ // use a verification seed to generate the primes. The verification
73
+ // seed doesn't appear to be exported or used by other code and
74
+ // omitting it makes the code cleaner.
75
+
76
+ var L, N int
77
+ switch sizes {
78
+ case L1024N160:
79
+ L = 1024
80
+ N = 160
81
+ case L2048N224:
82
+ L = 2048
83
+ N = 224
84
+ case L2048N256:
85
+ L = 2048
86
+ N = 256
87
+ case L3072N256:
88
+ L = 3072
89
+ N = 256
90
+ default:
91
+ return errors.New("crypto/dsa: invalid ParameterSizes")
92
+ }
93
+
94
+ qBytes := make([]byte, N/8)
95
+ pBytes := make([]byte, L/8)
96
+
97
+ q := new(big.Int)
98
+ p := new(big.Int)
99
+ rem := new(big.Int)
100
+ one := new(big.Int)
101
+ one.SetInt64(1)
102
+
103
+ GeneratePrimes:
104
+ for {
105
+ if _, err := io.ReadFull(rand, qBytes); err != nil {
106
+ return err
107
+ }
108
+
109
+ qBytes[len(qBytes)-1] |= 1
110
+ qBytes[0] |= 0x80
111
+ q.SetBytes(qBytes)
112
+
113
+ if !q.ProbablyPrime(numMRTests) {
114
+ continue
115
+ }
116
+
117
+ for i := 0; i < 4*L; i++ {
118
+ if _, err := io.ReadFull(rand, pBytes); err != nil {
119
+ return err
120
+ }
121
+
122
+ pBytes[len(pBytes)-1] |= 1
123
+ pBytes[0] |= 0x80
124
+
125
+ p.SetBytes(pBytes)
126
+ rem.Mod(p, q)
127
+ rem.Sub(rem, one)
128
+ p.Sub(p, rem)
129
+ if p.BitLen() < L {
130
+ continue
131
+ }
132
+
133
+ if !p.ProbablyPrime(numMRTests) {
134
+ continue
135
+ }
136
+
137
+ params.P = p
138
+ params.Q = q
139
+ break GeneratePrimes
140
+ }
141
+ }
142
+
143
+ h := new(big.Int)
144
+ h.SetInt64(2)
145
+ g := new(big.Int)
146
+
147
+ pm1 := new(big.Int).Sub(p, one)
148
+ e := new(big.Int).Div(pm1, q)
149
+
150
+ for {
151
+ g.Exp(h, e, p)
152
+ if g.Cmp(one) == 0 {
153
+ h.Add(h, one)
154
+ continue
155
+ }
156
+
157
+ params.G = g
158
+ return nil
159
+ }
160
+ }
161
+
162
+ // GenerateKey generates a public&private key pair. The Parameters of the
163
+ // [PrivateKey] must already be valid (see [GenerateParameters]).
164
+ func GenerateKey(priv *PrivateKey, rand io.Reader) error {
165
+ if fips140only.Enforced() {
166
+ return errors.New("crypto/dsa: use of DSA is not allowed in FIPS 140-only mode")
167
+ }
168
+
169
+ if priv.P == nil || priv.Q == nil || priv.G == nil {
170
+ return errors.New("crypto/dsa: parameters not set up before generating key")
171
+ }
172
+
173
+ x := new(big.Int)
174
+ xBytes := make([]byte, priv.Q.BitLen()/8)
175
+
176
+ for {
177
+ _, err := io.ReadFull(rand, xBytes)
178
+ if err != nil {
179
+ return err
180
+ }
181
+ x.SetBytes(xBytes)
182
+ if x.Sign() != 0 && x.Cmp(priv.Q) < 0 {
183
+ break
184
+ }
185
+ }
186
+
187
+ priv.X = x
188
+ priv.Y = new(big.Int)
189
+ priv.Y.Exp(priv.G, x, priv.P)
190
+ return nil
191
+ }
192
+
193
+ // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
194
+ // This has better constant-time properties than Euclid's method (implemented
195
+ // in math/big.Int.ModInverse) although math/big itself isn't strictly
196
+ // constant-time so it's not perfect.
197
+ func fermatInverse(k, P *big.Int) *big.Int {
198
+ two := big.NewInt(2)
199
+ pMinus2 := new(big.Int).Sub(P, two)
200
+ return new(big.Int).Exp(k, pMinus2, P)
201
+ }
202
+
203
+ // Sign signs an arbitrary length hash (which should be the result of hashing a
204
+ // larger message) using the private key, priv. It returns the signature as a
205
+ // pair of integers. The security of the private key depends on the entropy of
206
+ // rand.
207
+ //
208
+ // Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
209
+ // to the byte-length of the subgroup. This function does not perform that
210
+ // truncation itself.
211
+ //
212
+ // Since Go 1.26, a secure source of random bytes is always used, and the Reader is
213
+ // ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed
214
+ // in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].
215
+ //
216
+ // Be aware that calling Sign with an attacker-controlled [PrivateKey] may
217
+ // require an arbitrary amount of CPU.
218
+ func Sign(random io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
219
+ if fips140only.Enforced() {
220
+ return nil, nil, errors.New("crypto/dsa: use of DSA is not allowed in FIPS 140-only mode")
221
+ }
222
+
223
+ random = rand.CustomReader(random)
224
+
225
+ // FIPS 186-3, section 4.6
226
+
227
+ n := priv.Q.BitLen()
228
+ if priv.Q.Sign() <= 0 || priv.P.Sign() <= 0 || priv.G.Sign() <= 0 || priv.X.Sign() <= 0 || n%8 != 0 {
229
+ err = ErrInvalidPublicKey
230
+ return
231
+ }
232
+ n >>= 3
233
+
234
+ var attempts int
235
+ for attempts = 10; attempts > 0; attempts-- {
236
+ k := new(big.Int)
237
+ buf := make([]byte, n)
238
+ for {
239
+ _, err = io.ReadFull(random, buf)
240
+ if err != nil {
241
+ return
242
+ }
243
+ k.SetBytes(buf)
244
+ // priv.Q must be >= 128 because the test above
245
+ // requires it to be > 0 and that
246
+ // ceil(log_2(Q)) mod 8 = 0
247
+ // Thus this loop will quickly terminate.
248
+ if k.Sign() > 0 && k.Cmp(priv.Q) < 0 {
249
+ break
250
+ }
251
+ }
252
+
253
+ kInv := fermatInverse(k, priv.Q)
254
+
255
+ r = new(big.Int).Exp(priv.G, k, priv.P)
256
+ r.Mod(r, priv.Q)
257
+
258
+ if r.Sign() == 0 {
259
+ continue
260
+ }
261
+
262
+ z := k.SetBytes(hash)
263
+
264
+ s = new(big.Int).Mul(priv.X, r)
265
+ s.Add(s, z)
266
+ s.Mod(s, priv.Q)
267
+ s.Mul(s, kInv)
268
+ s.Mod(s, priv.Q)
269
+
270
+ if s.Sign() != 0 {
271
+ break
272
+ }
273
+ }
274
+
275
+ // Only degenerate private keys will require more than a handful of
276
+ // attempts.
277
+ if attempts == 0 {
278
+ return nil, nil, ErrInvalidPublicKey
279
+ }
280
+
281
+ return
282
+ }
283
+
284
+ // Verify verifies the signature in r, s of hash using the public key, pub. It
285
+ // reports whether the signature is valid.
286
+ //
287
+ // Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
288
+ // to the byte-length of the subgroup. This function does not perform that
289
+ // truncation itself.
290
+ func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
291
+ if fips140only.Enforced() {
292
+ panic("crypto/dsa: use of DSA is not allowed in FIPS 140-only mode")
293
+ }
294
+
295
+ // FIPS 186-3, section 4.7
296
+
297
+ if pub.P.Sign() == 0 {
298
+ return false
299
+ }
300
+
301
+ if r.Sign() < 1 || r.Cmp(pub.Q) >= 0 {
302
+ return false
303
+ }
304
+ if s.Sign() < 1 || s.Cmp(pub.Q) >= 0 {
305
+ return false
306
+ }
307
+
308
+ w := new(big.Int).ModInverse(s, pub.Q)
309
+ if w == nil {
310
+ return false
311
+ }
312
+
313
+ n := pub.Q.BitLen()
314
+ if n%8 != 0 {
315
+ return false
316
+ }
317
+ z := new(big.Int).SetBytes(hash)
318
+
319
+ u1 := new(big.Int).Mul(z, w)
320
+ u1.Mod(u1, pub.Q)
321
+ u2 := w.Mul(r, w)
322
+ u2.Mod(u2, pub.Q)
323
+ v := u1.Exp(pub.G, u1, pub.P)
324
+ u2.Exp(pub.Y, u2, pub.P)
325
+ v.Mul(v, u2)
326
+ v.Mod(v, pub.P)
327
+ v.Mod(v, pub.Q)
328
+
329
+ return v.Cmp(r) == 0
330
+ }
go/src/crypto/dsa/dsa_test.go ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 dsa
6
+
7
+ import (
8
+ "crypto/rand"
9
+ "math/big"
10
+ "testing"
11
+ )
12
+
13
+ func testSignAndVerify(t *testing.T, i int, priv *PrivateKey) {
14
+ hashed := []byte("testing")
15
+ r, s, err := Sign(rand.Reader, priv, hashed)
16
+ if err != nil {
17
+ t.Errorf("%d: error signing: %s", i, err)
18
+ return
19
+ }
20
+
21
+ if !Verify(&priv.PublicKey, hashed, r, s) {
22
+ t.Errorf("%d: Verify failed", i)
23
+ }
24
+ }
25
+
26
+ func testParameterGeneration(t *testing.T, sizes ParameterSizes, L, N int) {
27
+ t.Helper()
28
+ var priv PrivateKey
29
+ params := &priv.Parameters
30
+
31
+ err := GenerateParameters(params, rand.Reader, sizes)
32
+ if err != nil {
33
+ t.Errorf("%d: %s", int(sizes), err)
34
+ return
35
+ }
36
+
37
+ if params.P.BitLen() != L {
38
+ t.Errorf("%d: params.BitLen got:%d want:%d", int(sizes), params.P.BitLen(), L)
39
+ }
40
+
41
+ if params.Q.BitLen() != N {
42
+ t.Errorf("%d: q.BitLen got:%d want:%d", int(sizes), params.Q.BitLen(), L)
43
+ }
44
+
45
+ one := new(big.Int)
46
+ one.SetInt64(1)
47
+ pm1 := new(big.Int).Sub(params.P, one)
48
+ quo, rem := new(big.Int).DivMod(pm1, params.Q, new(big.Int))
49
+ if rem.Sign() != 0 {
50
+ t.Errorf("%d: p-1 mod q != 0", int(sizes))
51
+ }
52
+ x := new(big.Int).Exp(params.G, quo, params.P)
53
+ if x.Cmp(one) == 0 {
54
+ t.Errorf("%d: invalid generator", int(sizes))
55
+ }
56
+
57
+ err = GenerateKey(&priv, rand.Reader)
58
+ if err != nil {
59
+ t.Errorf("error generating key: %s", err)
60
+ return
61
+ }
62
+
63
+ testSignAndVerify(t, int(sizes), &priv)
64
+ }
65
+
66
+ func TestParameterGeneration(t *testing.T) {
67
+ if testing.Short() {
68
+ t.Skip("skipping parameter generation test in short mode")
69
+ }
70
+
71
+ testParameterGeneration(t, L1024N160, 1024, 160)
72
+ testParameterGeneration(t, L2048N224, 2048, 224)
73
+ testParameterGeneration(t, L2048N256, 2048, 256)
74
+ testParameterGeneration(t, L3072N256, 3072, 256)
75
+ }
76
+
77
+ func fromHex(s string) *big.Int {
78
+ result, ok := new(big.Int).SetString(s, 16)
79
+ if !ok {
80
+ panic(s)
81
+ }
82
+ return result
83
+ }
84
+
85
+ func TestSignAndVerify(t *testing.T) {
86
+ priv := PrivateKey{
87
+ PublicKey: PublicKey{
88
+ Parameters: Parameters{
89
+ P: fromHex("A9B5B793FB4785793D246BAE77E8FF63CA52F442DA763C440259919FE1BC1D6065A9350637A04F75A2F039401D49F08E066C4D275A5A65DA5684BC563C14289D7AB8A67163BFBF79D85972619AD2CFF55AB0EE77A9002B0EF96293BDD0F42685EBB2C66C327079F6C98000FBCB79AACDE1BC6F9D5C7B1A97E3D9D54ED7951FEF"),
90
+ Q: fromHex("E1D3391245933D68A0714ED34BBCB7A1F422B9C1"),
91
+ G: fromHex("634364FC25248933D01D1993ECABD0657CC0CB2CEED7ED2E3E8AECDFCDC4A25C3B15E9E3B163ACA2984B5539181F3EFF1A5E8903D71D5B95DA4F27202B77D2C44B430BB53741A8D59A8F86887525C9F2A6A5980A195EAA7F2FF910064301DEF89D3AA213E1FAC7768D89365318E370AF54A112EFBA9246D9158386BA1B4EEFDA"),
92
+ },
93
+ Y: fromHex("32969E5780CFE1C849A1C276D7AEB4F38A23B591739AA2FE197349AEEBD31366AEE5EB7E6C6DDB7C57D02432B30DB5AA66D9884299FAA72568944E4EEDC92EA3FBC6F39F53412FBCC563208F7C15B737AC8910DBC2D9C9B8C001E72FDC40EB694AB1F06A5A2DBD18D9E36C66F31F566742F11EC0A52E9F7B89355C02FB5D32D2"),
94
+ },
95
+ X: fromHex("5078D4D29795CBE76D3AACFE48C9AF0BCDBEE91A"),
96
+ }
97
+
98
+ testSignAndVerify(t, 0, &priv)
99
+ }
100
+
101
+ func TestSignAndVerifyWithBadPublicKey(t *testing.T) {
102
+ pub := PublicKey{
103
+ Parameters: Parameters{
104
+ P: fromHex("A9B5B793FB4785793D246BAE77E8FF63CA52F442DA763C440259919FE1BC1D6065A9350637A04F75A2F039401D49F08E066C4D275A5A65DA5684BC563C14289D7AB8A67163BFBF79D85972619AD2CFF55AB0EE77A9002B0EF96293BDD0F42685EBB2C66C327079F6C98000FBCB79AACDE1BC6F9D5C7B1A97E3D9D54ED7951FEF"),
105
+ Q: fromHex("FA"),
106
+ G: fromHex("634364FC25248933D01D1993ECABD0657CC0CB2CEED7ED2E3E8AECDFCDC4A25C3B15E9E3B163ACA2984B5539181F3EFF1A5E8903D71D5B95DA4F27202B77D2C44B430BB53741A8D59A8F86887525C9F2A6A5980A195EAA7F2FF910064301DEF89D3AA213E1FAC7768D89365318E370AF54A112EFBA9246D9158386BA1B4EEFDA"),
107
+ },
108
+ Y: fromHex("32969E5780CFE1C849A1C276D7AEB4F38A23B591739AA2FE197349AEEBD31366AEE5EB7E6C6DDB7C57D02432B30DB5AA66D9884299FAA72568944E4EEDC92EA3FBC6F39F53412FBCC563208F7C15B737AC8910DBC2D9C9B8C001E72FDC40EB694AB1F06A5A2DBD18D9E36C66F31F566742F11EC0A52E9F7B89355C02FB5D32D2"),
109
+ }
110
+
111
+ if Verify(&pub, []byte("testing"), fromHex("2"), fromHex("4")) {
112
+ t.Errorf("Verify unexpected success with non-existent mod inverse of Q")
113
+ }
114
+ }
115
+
116
+ func TestSigningWithDegenerateKeys(t *testing.T) {
117
+ // Signing with degenerate private keys should not cause an infinite
118
+ // loop.
119
+ badKeys := []struct {
120
+ p, q, g, y, x string
121
+ }{
122
+ {"00", "01", "00", "00", "00"},
123
+ {"01", "ff", "00", "00", "00"},
124
+ }
125
+
126
+ for i, test := range badKeys {
127
+ priv := PrivateKey{
128
+ PublicKey: PublicKey{
129
+ Parameters: Parameters{
130
+ P: fromHex(test.p),
131
+ Q: fromHex(test.q),
132
+ G: fromHex(test.g),
133
+ },
134
+ Y: fromHex(test.y),
135
+ },
136
+ X: fromHex(test.x),
137
+ }
138
+
139
+ hashed := []byte("testing")
140
+ if _, _, err := Sign(rand.Reader, &priv, hashed); err == nil {
141
+ t.Errorf("#%d: unexpected success", i)
142
+ }
143
+ }
144
+ }
go/src/crypto/ecdh/ecdh.go ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 ecdh implements Elliptic Curve Diffie-Hellman over
6
+ // NIST curves and Curve25519.
7
+ package ecdh
8
+
9
+ import (
10
+ "crypto"
11
+ "crypto/internal/boring"
12
+ "crypto/internal/fips140/ecdh"
13
+ "crypto/subtle"
14
+ "errors"
15
+ "io"
16
+ )
17
+
18
+ type Curve interface {
19
+ // GenerateKey generates a random PrivateKey.
20
+ //
21
+ // Since Go 1.26, a secure source of random bytes is always used, and rand
22
+ // is ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be
23
+ // removed in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].
24
+ GenerateKey(rand io.Reader) (*PrivateKey, error)
25
+
26
+ // NewPrivateKey checks that key is valid and returns a PrivateKey.
27
+ //
28
+ // For NIST curves, this follows SEC 1, Version 2.0, Section 2.3.6, which
29
+ // amounts to decoding the bytes as a fixed length big endian integer and
30
+ // checking that the result is lower than the order of the curve. The zero
31
+ // private key is also rejected, as the encoding of the corresponding public
32
+ // key would be irregular.
33
+ //
34
+ // For X25519, this only checks the scalar length.
35
+ NewPrivateKey(key []byte) (*PrivateKey, error)
36
+
37
+ // NewPublicKey checks that key is valid and returns a PublicKey.
38
+ //
39
+ // For NIST curves, this decodes an uncompressed point according to SEC 1,
40
+ // Version 2.0, Section 2.3.4. Compressed encodings and the point at
41
+ // infinity are rejected.
42
+ //
43
+ // For X25519, this only checks the u-coordinate length. Adversarially
44
+ // selected public keys can cause ECDH to return an error.
45
+ NewPublicKey(key []byte) (*PublicKey, error)
46
+
47
+ // ecdh performs an ECDH exchange and returns the shared secret. It's exposed
48
+ // as the PrivateKey.ECDH method.
49
+ //
50
+ // The private method also allow us to expand the ECDH interface with more
51
+ // methods in the future without breaking backwards compatibility.
52
+ ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error)
53
+ }
54
+
55
+ // PublicKey is an ECDH public key, usually a peer's ECDH share sent over the wire.
56
+ //
57
+ // These keys can be parsed with [crypto/x509.ParsePKIXPublicKey] and encoded
58
+ // with [crypto/x509.MarshalPKIXPublicKey]. For NIST curves, they then need to
59
+ // be converted with [crypto/ecdsa.PublicKey.ECDH] after parsing.
60
+ type PublicKey struct {
61
+ curve Curve
62
+ publicKey []byte
63
+ boring *boring.PublicKeyECDH
64
+ fips *ecdh.PublicKey
65
+ }
66
+
67
+ // Bytes returns a copy of the encoding of the public key.
68
+ func (k *PublicKey) Bytes() []byte {
69
+ // Copy the public key to a fixed size buffer that can get allocated on the
70
+ // caller's stack after inlining.
71
+ var buf [133]byte
72
+ return append(buf[:0], k.publicKey...)
73
+ }
74
+
75
+ // Equal returns whether x represents the same public key as k.
76
+ //
77
+ // Note that there can be equivalent public keys with different encodings which
78
+ // would return false from this check but behave the same way as inputs to ECDH.
79
+ //
80
+ // This check is performed in constant time as long as the key types and their
81
+ // curve match.
82
+ func (k *PublicKey) Equal(x crypto.PublicKey) bool {
83
+ xx, ok := x.(*PublicKey)
84
+ if !ok {
85
+ return false
86
+ }
87
+ return k.curve == xx.curve &&
88
+ subtle.ConstantTimeCompare(k.publicKey, xx.publicKey) == 1
89
+ }
90
+
91
+ func (k *PublicKey) Curve() Curve {
92
+ return k.curve
93
+ }
94
+
95
+ // KeyExchanger is an interface for an opaque private key that can be used for
96
+ // key exchange operations. For example, an ECDH key kept in a hardware module.
97
+ //
98
+ // It is implemented by [PrivateKey].
99
+ type KeyExchanger interface {
100
+ PublicKey() *PublicKey
101
+ Curve() Curve
102
+ ECDH(*PublicKey) ([]byte, error)
103
+ }
104
+
105
+ var _ KeyExchanger = (*PrivateKey)(nil)
106
+
107
+ // PrivateKey is an ECDH private key, usually kept secret.
108
+ //
109
+ // These keys can be parsed with [crypto/x509.ParsePKCS8PrivateKey] and encoded
110
+ // with [crypto/x509.MarshalPKCS8PrivateKey]. For NIST curves, they then need to
111
+ // be converted with [crypto/ecdsa.PrivateKey.ECDH] after parsing.
112
+ type PrivateKey struct {
113
+ curve Curve
114
+ privateKey []byte
115
+ publicKey *PublicKey
116
+ boring *boring.PrivateKeyECDH
117
+ fips *ecdh.PrivateKey
118
+ }
119
+
120
+ // ECDH performs an ECDH exchange and returns the shared secret. The [PrivateKey]
121
+ // and [PublicKey] must use the same curve.
122
+ //
123
+ // For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0,
124
+ // Section 3.3.1, and returns the x-coordinate encoded according to SEC 1,
125
+ // Version 2.0, Section 2.3.5. The result is never the point at infinity.
126
+ // This is also known as the Shared Secret Computation of the Ephemeral Unified
127
+ // Model scheme specified in NIST SP 800-56A Rev. 3, Section 6.1.2.2.
128
+ //
129
+ // For [X25519], this performs ECDH as specified in RFC 7748, Section 6.1. If
130
+ // the result is the all-zero value, ECDH returns an error.
131
+ func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error) {
132
+ if k.curve != remote.curve {
133
+ return nil, errors.New("crypto/ecdh: private key and public key curves do not match")
134
+ }
135
+ return k.curve.ecdh(k, remote)
136
+ }
137
+
138
+ // Bytes returns a copy of the encoding of the private key.
139
+ func (k *PrivateKey) Bytes() []byte {
140
+ // Copy the private key to a fixed size buffer that can get allocated on the
141
+ // caller's stack after inlining.
142
+ var buf [66]byte
143
+ return append(buf[:0], k.privateKey...)
144
+ }
145
+
146
+ // Equal returns whether x represents the same private key as k.
147
+ //
148
+ // Note that there can be equivalent private keys with different encodings which
149
+ // would return false from this check but behave the same way as inputs to [ECDH].
150
+ //
151
+ // This check is performed in constant time as long as the key types and their
152
+ // curve match.
153
+ func (k *PrivateKey) Equal(x crypto.PrivateKey) bool {
154
+ xx, ok := x.(*PrivateKey)
155
+ if !ok {
156
+ return false
157
+ }
158
+ return k.curve == xx.curve &&
159
+ subtle.ConstantTimeCompare(k.privateKey, xx.privateKey) == 1
160
+ }
161
+
162
+ func (k *PrivateKey) Curve() Curve {
163
+ return k.curve
164
+ }
165
+
166
+ func (k *PrivateKey) PublicKey() *PublicKey {
167
+ return k.publicKey
168
+ }
169
+
170
+ // Public implements the implicit interface of all standard library private
171
+ // keys. See the docs of [crypto.PrivateKey].
172
+ func (k *PrivateKey) Public() crypto.PublicKey {
173
+ return k.PublicKey()
174
+ }
go/src/crypto/ecdh/ecdh_test.go ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 ecdh_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto"
10
+ "crypto/cipher"
11
+ "crypto/ecdh"
12
+ "crypto/rand"
13
+ "crypto/sha256"
14
+ "encoding/hex"
15
+ "fmt"
16
+ "internal/testenv"
17
+ "io"
18
+ "os"
19
+ "path/filepath"
20
+ "regexp"
21
+ "strings"
22
+ "testing"
23
+
24
+ "golang.org/x/crypto/chacha20"
25
+ )
26
+
27
+ // Check that PublicKey and PrivateKey implement the interfaces documented in
28
+ // crypto.PublicKey and crypto.PrivateKey.
29
+ var _ interface {
30
+ Equal(x crypto.PublicKey) bool
31
+ } = &ecdh.PublicKey{}
32
+ var _ interface {
33
+ Public() crypto.PublicKey
34
+ Equal(x crypto.PrivateKey) bool
35
+ } = &ecdh.PrivateKey{}
36
+
37
+ func TestECDH(t *testing.T) {
38
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
39
+ aliceKey, err := curve.GenerateKey(rand.Reader)
40
+ if err != nil {
41
+ t.Fatal(err)
42
+ }
43
+ bobKey, err := curve.GenerateKey(rand.Reader)
44
+ if err != nil {
45
+ t.Fatal(err)
46
+ }
47
+
48
+ alicePubKey, err := curve.NewPublicKey(aliceKey.PublicKey().Bytes())
49
+ if err != nil {
50
+ t.Error(err)
51
+ }
52
+ if !bytes.Equal(aliceKey.PublicKey().Bytes(), alicePubKey.Bytes()) {
53
+ t.Error("encoded and decoded public keys are different")
54
+ }
55
+ if !aliceKey.PublicKey().Equal(alicePubKey) {
56
+ t.Error("encoded and decoded public keys are different")
57
+ }
58
+
59
+ alicePrivKey, err := curve.NewPrivateKey(aliceKey.Bytes())
60
+ if err != nil {
61
+ t.Error(err)
62
+ }
63
+ if !bytes.Equal(aliceKey.Bytes(), alicePrivKey.Bytes()) {
64
+ t.Error("encoded and decoded private keys are different")
65
+ }
66
+ if !aliceKey.Equal(alicePrivKey) {
67
+ t.Error("encoded and decoded private keys are different")
68
+ }
69
+
70
+ bobSecret, err := bobKey.ECDH(aliceKey.PublicKey())
71
+ if err != nil {
72
+ t.Fatal(err)
73
+ }
74
+ aliceSecret, err := aliceKey.ECDH(bobKey.PublicKey())
75
+ if err != nil {
76
+ t.Fatal(err)
77
+ }
78
+
79
+ if !bytes.Equal(bobSecret, aliceSecret) {
80
+ t.Error("two ECDH computations came out different")
81
+ }
82
+ })
83
+ }
84
+
85
+ type countingReader struct {
86
+ r io.Reader
87
+ n int
88
+ }
89
+
90
+ func (r *countingReader) Read(p []byte) (int, error) {
91
+ n, err := r.r.Read(p)
92
+ r.n += n
93
+ return n, err
94
+ }
95
+
96
+ func TestGenerateKey(t *testing.T) {
97
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
98
+ r := &countingReader{r: rand.Reader}
99
+ k, err := curve.GenerateKey(r)
100
+ if err != nil {
101
+ t.Fatal(err)
102
+ }
103
+
104
+ // GenerateKey does rejection sampling. If the masking works correctly,
105
+ // the probability of a rejection is 1-ord(G)/2^ceil(log2(ord(G))),
106
+ // which for all curves is small enough (at most 2^-32, for P-256) that
107
+ // a bit flip is more likely to make this test fail than bad luck.
108
+ // Account for the extra MaybeReadByte byte, too.
109
+ if got, expected := r.n, len(k.Bytes())+1; got > expected {
110
+ t.Errorf("expected GenerateKey to consume at most %v bytes, got %v", expected, got)
111
+ }
112
+ })
113
+ }
114
+
115
+ var vectors = map[ecdh.Curve]struct {
116
+ PrivateKey, PublicKey string
117
+ PeerPublicKey string
118
+ SharedSecret string
119
+ }{
120
+ // NIST vectors from CAVS 14.1, ECC CDH Primitive (SP800-56A).
121
+ ecdh.P256(): {
122
+ PrivateKey: "7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534",
123
+ PublicKey: "04ead218590119e8876b29146ff89ca61770c4edbbf97d38ce385ed281d8a6b230" +
124
+ "28af61281fd35e2fa7002523acc85a429cb06ee6648325389f59edfce1405141",
125
+ PeerPublicKey: "04700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287" +
126
+ "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
127
+ SharedSecret: "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b",
128
+ },
129
+ ecdh.P384(): {
130
+ PrivateKey: "3cc3122a68f0d95027ad38c067916ba0eb8c38894d22e1b15618b6818a661774ad463b205da88cf699ab4d43c9cf98a1",
131
+ PublicKey: "049803807f2f6d2fd966cdd0290bd410c0190352fbec7ff6247de1302df86f25d34fe4a97bef60cff548355c015dbb3e5f" +
132
+ "ba26ca69ec2f5b5d9dad20cc9da711383a9dbe34ea3fa5a2af75b46502629ad54dd8b7d73a8abb06a3a3be47d650cc99",
133
+ PeerPublicKey: "04a7c76b970c3b5fe8b05d2838ae04ab47697b9eaf52e764592efda27fe7513272734466b400091adbf2d68c58e0c50066" +
134
+ "ac68f19f2e1cb879aed43a9969b91a0839c4c38a49749b661efedf243451915ed0905a32b060992b468c64766fc8437a",
135
+ SharedSecret: "5f9d29dc5e31a163060356213669c8ce132e22f57c9a04f40ba7fcead493b457e5621e766c40a2e3d4d6a04b25e533f1",
136
+ },
137
+ // For some reason all field elements in the test vector (both scalars and
138
+ // base field elements), but not the shared secret output, have two extra
139
+ // leading zero bytes (which in big-endian are irrelevant). Removed here.
140
+ ecdh.P521(): {
141
+ PrivateKey: "017eecc07ab4b329068fba65e56a1f8890aa935e57134ae0ffcce802735151f4eac6564f6ee9974c5e6887a1fefee5743ae2241bfeb95d5ce31ddcb6f9edb4d6fc47",
142
+ PublicKey: "0400602f9d0cf9e526b29e22381c203c48a886c2b0673033366314f1ffbcba240ba42f4ef38a76174635f91e6b4ed34275eb01c8467d05ca80315bf1a7bbd945f550a5" +
143
+ "01b7c85f26f5d4b2d7355cf6b02117659943762b6d1db5ab4f1dbc44ce7b2946eb6c7de342962893fd387d1b73d7a8672d1f236961170b7eb3579953ee5cdc88cd2d",
144
+ PeerPublicKey: "0400685a48e86c79f0f0875f7bc18d25eb5fc8c0b07e5da4f4370f3a9490340854334b1e1b87fa395464c60626124a4e70d0f785601d37c09870ebf176666877a2046d" +
145
+ "01ba52c56fc8776d9e8f5db4f0cc27636d0b741bbe05400697942e80b739884a83bde99e0f6716939e632bc8986fa18dccd443a348b6c3e522497955a4f3c302f676",
146
+ SharedSecret: "005fc70477c3e63bc3954bd0df3ea0d1f41ee21746ed95fc5e1fdf90930d5e136672d72cc770742d1711c3c3a4c334a0ad9759436a4d3c5bf6e74b9578fac148c831",
147
+ },
148
+ // X25519 test vector from RFC 7748, Section 6.1.
149
+ ecdh.X25519(): {
150
+ PrivateKey: "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
151
+ PublicKey: "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
152
+ PeerPublicKey: "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
153
+ SharedSecret: "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742",
154
+ },
155
+ }
156
+
157
+ func TestVectors(t *testing.T) {
158
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
159
+ v := vectors[curve]
160
+ key, err := curve.NewPrivateKey(hexDecode(t, v.PrivateKey))
161
+ if err != nil {
162
+ t.Fatal(err)
163
+ }
164
+ if !bytes.Equal(key.PublicKey().Bytes(), hexDecode(t, v.PublicKey)) {
165
+ t.Error("public key derived from the private key does not match")
166
+ }
167
+ peer, err := curve.NewPublicKey(hexDecode(t, v.PeerPublicKey))
168
+ if err != nil {
169
+ t.Fatal(err)
170
+ }
171
+ secret, err := key.ECDH(peer)
172
+ if err != nil {
173
+ t.Fatal(err)
174
+ }
175
+ if !bytes.Equal(secret, hexDecode(t, v.SharedSecret)) {
176
+ t.Errorf("shared secret does not match: %x %x %s %x", secret, sha256.Sum256(secret), v.SharedSecret,
177
+ sha256.Sum256(hexDecode(t, v.SharedSecret)))
178
+ }
179
+ })
180
+ }
181
+
182
+ func hexDecode(t *testing.T, s string) []byte {
183
+ b, err := hex.DecodeString(s)
184
+ if err != nil {
185
+ t.Fatal("invalid hex string:", s)
186
+ }
187
+ return b
188
+ }
189
+
190
+ func TestString(t *testing.T) {
191
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
192
+ s := fmt.Sprintf("%s", curve)
193
+ if s[:1] != "P" && s[:1] != "X" {
194
+ t.Errorf("unexpected Curve string encoding: %q", s)
195
+ }
196
+ })
197
+ }
198
+
199
+ func TestX25519Failure(t *testing.T) {
200
+ identity := hexDecode(t, "0000000000000000000000000000000000000000000000000000000000000000")
201
+ lowOrderPoint := hexDecode(t, "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")
202
+ randomScalar := make([]byte, 32)
203
+ rand.Read(randomScalar)
204
+
205
+ t.Run("identity point", func(t *testing.T) { testX25519Failure(t, randomScalar, identity) })
206
+ t.Run("low order point", func(t *testing.T) { testX25519Failure(t, randomScalar, lowOrderPoint) })
207
+ }
208
+
209
+ func testX25519Failure(t *testing.T, private, public []byte) {
210
+ priv, err := ecdh.X25519().NewPrivateKey(private)
211
+ if err != nil {
212
+ t.Fatal(err)
213
+ }
214
+ pub, err := ecdh.X25519().NewPublicKey(public)
215
+ if err != nil {
216
+ t.Fatal(err)
217
+ }
218
+ secret, err := priv.ECDH(pub)
219
+ if err == nil {
220
+ t.Error("expected ECDH error")
221
+ }
222
+ if secret != nil {
223
+ t.Errorf("unexpected ECDH output: %x", secret)
224
+ }
225
+ }
226
+
227
+ var invalidPrivateKeys = map[ecdh.Curve][]string{
228
+ ecdh.P256(): {
229
+ // Bad lengths.
230
+ "",
231
+ "01",
232
+ "01010101010101010101010101010101010101010101010101010101010101",
233
+ "000101010101010101010101010101010101010101010101010101010101010101",
234
+ strings.Repeat("01", 200),
235
+ // Zero.
236
+ "0000000000000000000000000000000000000000000000000000000000000000",
237
+ // Order of the curve and above.
238
+ "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
239
+ "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552",
240
+ "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
241
+ },
242
+ ecdh.P384(): {
243
+ // Bad lengths.
244
+ "",
245
+ "01",
246
+ "0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
247
+ "00010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
248
+ strings.Repeat("01", 200),
249
+ // Zero.
250
+ "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
251
+ // Order of the curve and above.
252
+ "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973",
253
+ "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52974",
254
+ "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
255
+ },
256
+ ecdh.P521(): {
257
+ // Bad lengths.
258
+ "",
259
+ "01",
260
+ "0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
261
+ "00010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
262
+ strings.Repeat("01", 200),
263
+ // Zero.
264
+ "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
265
+ // Order of the curve and above.
266
+ "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
267
+ "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e9138640a",
268
+ "11fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
269
+ "03fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4a30d0f077e5f2cd6ff980291ee134ba0776b937113388f5d76df6e3d2270c812",
270
+ },
271
+ ecdh.X25519(): {
272
+ // X25519 only rejects bad lengths.
273
+ "",
274
+ "01",
275
+ "01010101010101010101010101010101010101010101010101010101010101",
276
+ "000101010101010101010101010101010101010101010101010101010101010101",
277
+ strings.Repeat("01", 200),
278
+ },
279
+ }
280
+
281
+ func TestNewPrivateKey(t *testing.T) {
282
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
283
+ for _, input := range invalidPrivateKeys[curve] {
284
+ k, err := curve.NewPrivateKey(hexDecode(t, input))
285
+ if err == nil {
286
+ t.Errorf("unexpectedly accepted %q", input)
287
+ } else if k != nil {
288
+ t.Error("PrivateKey was not nil on error")
289
+ } else if strings.Contains(err.Error(), "boringcrypto") {
290
+ t.Errorf("boringcrypto error leaked out: %v", err)
291
+ }
292
+ }
293
+ })
294
+ }
295
+
296
+ var invalidPublicKeys = map[ecdh.Curve][]string{
297
+ ecdh.P256(): {
298
+ // Bad lengths.
299
+ "",
300
+ "04",
301
+ strings.Repeat("04", 200),
302
+ // Infinity.
303
+ "00",
304
+ // Compressed encodings.
305
+ "036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
306
+ "02e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852",
307
+ // Points not on the curve.
308
+ "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f6",
309
+ "0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
310
+ // Non-canonical encoding.
311
+ "04ffffffff00000001000000000000000000000001000000000000000000000004ba6dbc4555a7e7fa016ec431667e8521ee35afc49b265c3accbea3f7cdb70433",
312
+ },
313
+ ecdh.P384(): {
314
+ // Bad lengths.
315
+ "",
316
+ "04",
317
+ strings.Repeat("04", 200),
318
+ // Infinity.
319
+ "00",
320
+ // Compressed encodings.
321
+ "03aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
322
+ "0208d999057ba3d2d969260045c55b97f089025959a6f434d651d207d19fb96e9e4fe0e86ebe0e64f85b96a9c75295df61",
323
+ // Points not on the curve.
324
+ "04aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab73617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e60",
325
+ "04000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
326
+ // Non-canonical encoding.
327
+ "04fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff000000000000000100000001732152442fb6ee5c3e6ce1d920c059bc623563814d79042b903ce60f1d4487fccd450a86da03f3e6ed525d02017bfdb3",
328
+ },
329
+ ecdh.P521(): {
330
+ // Bad lengths.
331
+ "",
332
+ "04",
333
+ strings.Repeat("04", 200),
334
+ // Infinity.
335
+ "00",
336
+ // Compressed encodings.
337
+ "030035b5df64ae2ac204c354b483487c9070cdc61c891c5ff39afc06c5d55541d3ceac8659e24afe3d0750e8b88e9f078af066a1d5025b08e5a5e2fbc87412871902f3",
338
+ "0200c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66",
339
+ // Points not on the curve.
340
+ "0400c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16651",
341
+ "04000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
342
+ // Non-canonical encoding.
343
+ "0402000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100d9254fdf800496acb33790b103c5ee9fac12832fe546c632225b0f7fce3da4574b1a879b623d722fa8fc34d5fc2a8731aad691a9a8bb8b554c95a051d6aa505acf",
344
+ },
345
+ ecdh.X25519(): {},
346
+ }
347
+
348
+ func TestNewPublicKey(t *testing.T) {
349
+ testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
350
+ for _, input := range invalidPublicKeys[curve] {
351
+ k, err := curve.NewPublicKey(hexDecode(t, input))
352
+ if err == nil {
353
+ t.Errorf("unexpectedly accepted %q", input)
354
+ } else if k != nil {
355
+ t.Error("PublicKey was not nil on error")
356
+ } else if strings.Contains(err.Error(), "boringcrypto") {
357
+ t.Errorf("boringcrypto error leaked out: %v", err)
358
+ }
359
+ }
360
+ })
361
+ }
362
+
363
+ func testAllCurves(t *testing.T, f func(t *testing.T, curve ecdh.Curve)) {
364
+ t.Run("P256", func(t *testing.T) { f(t, ecdh.P256()) })
365
+ t.Run("P384", func(t *testing.T) { f(t, ecdh.P384()) })
366
+ t.Run("P521", func(t *testing.T) { f(t, ecdh.P521()) })
367
+ t.Run("X25519", func(t *testing.T) { f(t, ecdh.X25519()) })
368
+ }
369
+
370
+ func BenchmarkECDH(b *testing.B) {
371
+ benchmarkAllCurves(b, func(b *testing.B, curve ecdh.Curve) {
372
+ c, err := chacha20.NewUnauthenticatedCipher(make([]byte, 32), make([]byte, 12))
373
+ if err != nil {
374
+ b.Fatal(err)
375
+ }
376
+ rand := cipher.StreamReader{
377
+ S: c, R: zeroReader,
378
+ }
379
+
380
+ peerKey, err := curve.GenerateKey(rand)
381
+ if err != nil {
382
+ b.Fatal(err)
383
+ }
384
+ peerShare := peerKey.PublicKey().Bytes()
385
+ b.ResetTimer()
386
+ b.ReportAllocs()
387
+
388
+ var allocationsSink byte
389
+
390
+ for i := 0; i < b.N; i++ {
391
+ key, err := curve.GenerateKey(rand)
392
+ if err != nil {
393
+ b.Fatal(err)
394
+ }
395
+ share := key.PublicKey().Bytes()
396
+ peerPubKey, err := curve.NewPublicKey(peerShare)
397
+ if err != nil {
398
+ b.Fatal(err)
399
+ }
400
+ secret, err := key.ECDH(peerPubKey)
401
+ if err != nil {
402
+ b.Fatal(err)
403
+ }
404
+ allocationsSink ^= secret[0] ^ share[0]
405
+ }
406
+ })
407
+ }
408
+
409
+ func benchmarkAllCurves(b *testing.B, f func(b *testing.B, curve ecdh.Curve)) {
410
+ b.Run("P256", func(b *testing.B) { f(b, ecdh.P256()) })
411
+ b.Run("P384", func(b *testing.B) { f(b, ecdh.P384()) })
412
+ b.Run("P521", func(b *testing.B) { f(b, ecdh.P521()) })
413
+ b.Run("X25519", func(b *testing.B) { f(b, ecdh.X25519()) })
414
+ }
415
+
416
+ type zr struct{}
417
+
418
+ // Read replaces the contents of dst with zeros. It is safe for concurrent use.
419
+ func (zr) Read(dst []byte) (n int, err error) {
420
+ clear(dst)
421
+ return len(dst), nil
422
+ }
423
+
424
+ var zeroReader = zr{}
425
+
426
+ const linkerTestProgram = `
427
+ package main
428
+ import "crypto/ecdh"
429
+ import "crypto/rand"
430
+ func main() {
431
+ // Use P-256, since that's what the always-enabled CAST uses.
432
+ curve := ecdh.P256()
433
+ key, err := curve.GenerateKey(rand.Reader)
434
+ if err != nil { panic(err) }
435
+ _, err = curve.NewPublicKey(key.PublicKey().Bytes())
436
+ if err != nil { panic(err) }
437
+ _, err = curve.NewPrivateKey(key.Bytes())
438
+ if err != nil { panic(err) }
439
+ _, err = key.ECDH(key.PublicKey())
440
+ if err != nil { panic(err) }
441
+ println("OK")
442
+ }
443
+ `
444
+
445
+ // TestLinker ensures that using one curve does not bring all other
446
+ // implementations into the binary. This also guarantees that govulncheck can
447
+ // avoid warning about a curve-specific vulnerability if that curve is not used.
448
+ func TestLinker(t *testing.T) {
449
+ if testing.Short() {
450
+ t.Skip("test requires running 'go build'")
451
+ }
452
+
453
+ dir := t.TempDir()
454
+ hello := filepath.Join(dir, "hello.go")
455
+ err := os.WriteFile(hello, []byte(linkerTestProgram), 0664)
456
+ if err != nil {
457
+ t.Fatal(err)
458
+ }
459
+
460
+ run := func(args ...string) string {
461
+ cmd := testenv.Command(t, args[0], args[1:]...)
462
+ cmd.Dir = dir
463
+ out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
464
+ if err != nil {
465
+ t.Fatalf("%v: %v\n%s", args, err, string(out))
466
+ }
467
+ return string(out)
468
+ }
469
+
470
+ run(testenv.GoToolPath(t), "build", "-o", "hello.exe", "hello.go")
471
+ if out := run("./hello.exe"); out != "OK\n" {
472
+ t.Error("unexpected output:", out)
473
+ }
474
+
475
+ // List all text symbols under crypto/... and make sure there are some for
476
+ // P256, but none for the other curves.
477
+ var consistent bool
478
+ nm := run(testenv.GoToolPath(t), "tool", "nm", "hello.exe")
479
+ for _, match := range regexp.MustCompile(`(?m)T (crypto/.*)$`).FindAllStringSubmatch(nm, -1) {
480
+ symbol := strings.ToLower(match[1])
481
+ if strings.Contains(symbol, "p256") {
482
+ consistent = true
483
+ }
484
+ if strings.Contains(symbol, "p224") || strings.Contains(symbol, "p384") || strings.Contains(symbol, "p521") {
485
+ t.Errorf("unexpected symbol in program using only ecdh.P256: %s", match[1])
486
+ }
487
+ }
488
+ if !consistent {
489
+ t.Error("no P256 symbols found in program using ecdh.P256, test is broken")
490
+ }
491
+ }
492
+
493
+ func TestMismatchedCurves(t *testing.T) {
494
+ curves := []struct {
495
+ name string
496
+ curve ecdh.Curve
497
+ }{
498
+ {"P256", ecdh.P256()},
499
+ {"P384", ecdh.P384()},
500
+ {"P521", ecdh.P521()},
501
+ {"X25519", ecdh.X25519()},
502
+ }
503
+
504
+ for _, privCurve := range curves {
505
+ priv, err := privCurve.curve.GenerateKey(rand.Reader)
506
+ if err != nil {
507
+ t.Fatalf("failed to generate test key: %s", err)
508
+ }
509
+
510
+ for _, pubCurve := range curves {
511
+ if privCurve == pubCurve {
512
+ continue
513
+ }
514
+ t.Run(fmt.Sprintf("%s/%s", privCurve.name, pubCurve.name), func(t *testing.T) {
515
+ pub, err := pubCurve.curve.GenerateKey(rand.Reader)
516
+ if err != nil {
517
+ t.Fatalf("failed to generate test key: %s", err)
518
+ }
519
+ expected := "crypto/ecdh: private key and public key curves do not match"
520
+ _, err = priv.ECDH(pub.PublicKey())
521
+ if err.Error() != expected {
522
+ t.Fatalf("unexpected error: want %q, got %q", expected, err)
523
+ }
524
+ })
525
+ }
526
+ }
527
+ }
go/src/crypto/ecdh/nist.go ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 ecdh
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/internal/boring"
10
+ "crypto/internal/fips140/ecdh"
11
+ "crypto/internal/fips140only"
12
+ "crypto/internal/rand"
13
+ "errors"
14
+ "io"
15
+ )
16
+
17
+ type nistCurve struct {
18
+ name string
19
+ generate func(io.Reader) (*ecdh.PrivateKey, error)
20
+ newPrivateKey func([]byte) (*ecdh.PrivateKey, error)
21
+ newPublicKey func(publicKey []byte) (*ecdh.PublicKey, error)
22
+ sharedSecret func(*ecdh.PrivateKey, *ecdh.PublicKey) (sharedSecret []byte, err error)
23
+ }
24
+
25
+ func (c *nistCurve) String() string {
26
+ return c.name
27
+ }
28
+
29
+ func (c *nistCurve) GenerateKey(r io.Reader) (*PrivateKey, error) {
30
+ if boring.Enabled && rand.IsDefaultReader(r) {
31
+ key, bytes, err := boring.GenerateKeyECDH(c.name)
32
+ if err != nil {
33
+ return nil, err
34
+ }
35
+ pub, err := key.PublicKey()
36
+ if err != nil {
37
+ return nil, err
38
+ }
39
+ k := &PrivateKey{
40
+ curve: c,
41
+ privateKey: bytes,
42
+ publicKey: &PublicKey{curve: c, publicKey: pub.Bytes(), boring: pub},
43
+ boring: key,
44
+ }
45
+ return k, nil
46
+ }
47
+
48
+ r = rand.CustomReader(r)
49
+
50
+ if fips140only.Enforced() && !fips140only.ApprovedRandomReader(r) {
51
+ return nil, errors.New("crypto/ecdh: only crypto/rand.Reader is allowed in FIPS 140-only mode")
52
+ }
53
+
54
+ privateKey, err := c.generate(r)
55
+ if err != nil {
56
+ return nil, err
57
+ }
58
+
59
+ k := &PrivateKey{
60
+ curve: c,
61
+ privateKey: privateKey.Bytes(),
62
+ fips: privateKey,
63
+ publicKey: &PublicKey{
64
+ curve: c,
65
+ publicKey: privateKey.PublicKey().Bytes(),
66
+ fips: privateKey.PublicKey(),
67
+ },
68
+ }
69
+ if boring.Enabled {
70
+ bk, err := boring.NewPrivateKeyECDH(c.name, k.privateKey)
71
+ if err != nil {
72
+ return nil, err
73
+ }
74
+ pub, err := bk.PublicKey()
75
+ if err != nil {
76
+ return nil, err
77
+ }
78
+ k.boring = bk
79
+ k.publicKey.boring = pub
80
+ }
81
+ return k, nil
82
+ }
83
+
84
+ func (c *nistCurve) NewPrivateKey(key []byte) (*PrivateKey, error) {
85
+ if boring.Enabled {
86
+ bk, err := boring.NewPrivateKeyECDH(c.name, key)
87
+ if err != nil {
88
+ return nil, errors.New("crypto/ecdh: invalid private key")
89
+ }
90
+ pub, err := bk.PublicKey()
91
+ if err != nil {
92
+ return nil, errors.New("crypto/ecdh: invalid private key")
93
+ }
94
+ k := &PrivateKey{
95
+ curve: c,
96
+ privateKey: bytes.Clone(key),
97
+ publicKey: &PublicKey{curve: c, publicKey: pub.Bytes(), boring: pub},
98
+ boring: bk,
99
+ }
100
+ return k, nil
101
+ }
102
+
103
+ fk, err := c.newPrivateKey(key)
104
+ if err != nil {
105
+ return nil, err
106
+ }
107
+ k := &PrivateKey{
108
+ curve: c,
109
+ privateKey: bytes.Clone(key),
110
+ fips: fk,
111
+ publicKey: &PublicKey{
112
+ curve: c,
113
+ publicKey: fk.PublicKey().Bytes(),
114
+ fips: fk.PublicKey(),
115
+ },
116
+ }
117
+ return k, nil
118
+ }
119
+
120
+ func (c *nistCurve) NewPublicKey(key []byte) (*PublicKey, error) {
121
+ // Reject the point at infinity and compressed encodings.
122
+ // Note that boring.NewPublicKeyECDH would accept them.
123
+ if len(key) == 0 || key[0] != 4 {
124
+ return nil, errors.New("crypto/ecdh: invalid public key")
125
+ }
126
+ k := &PublicKey{
127
+ curve: c,
128
+ publicKey: bytes.Clone(key),
129
+ }
130
+ if boring.Enabled {
131
+ bk, err := boring.NewPublicKeyECDH(c.name, k.publicKey)
132
+ if err != nil {
133
+ return nil, errors.New("crypto/ecdh: invalid public key")
134
+ }
135
+ k.boring = bk
136
+ } else {
137
+ fk, err := c.newPublicKey(key)
138
+ if err != nil {
139
+ return nil, err
140
+ }
141
+ k.fips = fk
142
+ }
143
+ return k, nil
144
+ }
145
+
146
+ func (c *nistCurve) ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error) {
147
+ // Note that this function can't return an error, as NewPublicKey rejects
148
+ // invalid points and the point at infinity, and NewPrivateKey rejects
149
+ // invalid scalars and the zero value. BytesX returns an error for the point
150
+ // at infinity, but in a prime order group such as the NIST curves that can
151
+ // only be the result of a scalar multiplication if one of the inputs is the
152
+ // zero scalar or the point at infinity.
153
+
154
+ if boring.Enabled {
155
+ return boring.ECDH(local.boring, remote.boring)
156
+ }
157
+ return c.sharedSecret(local.fips, remote.fips)
158
+ }
159
+
160
+ // P256 returns a [Curve] which implements NIST P-256 (FIPS 186-3, section D.2.3),
161
+ // also known as secp256r1 or prime256v1.
162
+ //
163
+ // Multiple invocations of this function will return the same value, which can
164
+ // be used for equality checks and switch statements.
165
+ func P256() Curve { return p256 }
166
+
167
+ var p256 = &nistCurve{
168
+ name: "P-256",
169
+ generate: func(r io.Reader) (*ecdh.PrivateKey, error) {
170
+ return ecdh.GenerateKey(ecdh.P256(), r)
171
+ },
172
+ newPrivateKey: func(b []byte) (*ecdh.PrivateKey, error) {
173
+ return ecdh.NewPrivateKey(ecdh.P256(), b)
174
+ },
175
+ newPublicKey: func(publicKey []byte) (*ecdh.PublicKey, error) {
176
+ return ecdh.NewPublicKey(ecdh.P256(), publicKey)
177
+ },
178
+ sharedSecret: func(priv *ecdh.PrivateKey, pub *ecdh.PublicKey) (sharedSecret []byte, err error) {
179
+ return ecdh.ECDH(ecdh.P256(), priv, pub)
180
+ },
181
+ }
182
+
183
+ // P384 returns a [Curve] which implements NIST P-384 (FIPS 186-3, section D.2.4),
184
+ // also known as secp384r1.
185
+ //
186
+ // Multiple invocations of this function will return the same value, which can
187
+ // be used for equality checks and switch statements.
188
+ func P384() Curve { return p384 }
189
+
190
+ var p384 = &nistCurve{
191
+ name: "P-384",
192
+ generate: func(r io.Reader) (*ecdh.PrivateKey, error) {
193
+ return ecdh.GenerateKey(ecdh.P384(), r)
194
+ },
195
+ newPrivateKey: func(b []byte) (*ecdh.PrivateKey, error) {
196
+ return ecdh.NewPrivateKey(ecdh.P384(), b)
197
+ },
198
+ newPublicKey: func(publicKey []byte) (*ecdh.PublicKey, error) {
199
+ return ecdh.NewPublicKey(ecdh.P384(), publicKey)
200
+ },
201
+ sharedSecret: func(priv *ecdh.PrivateKey, pub *ecdh.PublicKey) (sharedSecret []byte, err error) {
202
+ return ecdh.ECDH(ecdh.P384(), priv, pub)
203
+ },
204
+ }
205
+
206
+ // P521 returns a [Curve] which implements NIST P-521 (FIPS 186-3, section D.2.5),
207
+ // also known as secp521r1.
208
+ //
209
+ // Multiple invocations of this function will return the same value, which can
210
+ // be used for equality checks and switch statements.
211
+ func P521() Curve { return p521 }
212
+
213
+ var p521 = &nistCurve{
214
+ name: "P-521",
215
+ generate: func(r io.Reader) (*ecdh.PrivateKey, error) {
216
+ return ecdh.GenerateKey(ecdh.P521(), r)
217
+ },
218
+ newPrivateKey: func(b []byte) (*ecdh.PrivateKey, error) {
219
+ return ecdh.NewPrivateKey(ecdh.P521(), b)
220
+ },
221
+ newPublicKey: func(publicKey []byte) (*ecdh.PublicKey, error) {
222
+ return ecdh.NewPublicKey(ecdh.P521(), publicKey)
223
+ },
224
+ sharedSecret: func(priv *ecdh.PrivateKey, pub *ecdh.PublicKey) (sharedSecret []byte, err error) {
225
+ return ecdh.ECDH(ecdh.P521(), priv, pub)
226
+ },
227
+ }
go/src/crypto/ecdh/x25519.go ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 ecdh
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/internal/fips140/edwards25519/field"
10
+ "crypto/internal/fips140only"
11
+ "crypto/internal/rand"
12
+ "errors"
13
+ "io"
14
+ )
15
+
16
+ var (
17
+ x25519PublicKeySize = 32
18
+ x25519PrivateKeySize = 32
19
+ x25519SharedSecretSize = 32
20
+ )
21
+
22
+ // X25519 returns a [Curve] which implements the X25519 function over Curve25519
23
+ // (RFC 7748, Section 5).
24
+ //
25
+ // Multiple invocations of this function will return the same value, so it can
26
+ // be used for equality checks and switch statements.
27
+ func X25519() Curve { return x25519 }
28
+
29
+ var x25519 = &x25519Curve{}
30
+
31
+ type x25519Curve struct{}
32
+
33
+ func (c *x25519Curve) String() string {
34
+ return "X25519"
35
+ }
36
+
37
+ func (c *x25519Curve) GenerateKey(r io.Reader) (*PrivateKey, error) {
38
+ if fips140only.Enforced() {
39
+ return nil, errors.New("crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode")
40
+ }
41
+ r = rand.CustomReader(r)
42
+ key := make([]byte, x25519PrivateKeySize)
43
+ if _, err := io.ReadFull(r, key); err != nil {
44
+ return nil, err
45
+ }
46
+ return c.NewPrivateKey(key)
47
+ }
48
+
49
+ func (c *x25519Curve) NewPrivateKey(key []byte) (*PrivateKey, error) {
50
+ if fips140only.Enforced() {
51
+ return nil, errors.New("crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode")
52
+ }
53
+ if len(key) != x25519PrivateKeySize {
54
+ return nil, errors.New("crypto/ecdh: invalid private key size")
55
+ }
56
+ publicKey := make([]byte, x25519PublicKeySize)
57
+ x25519Basepoint := [32]byte{9}
58
+ x25519ScalarMult(publicKey, key, x25519Basepoint[:])
59
+ // We don't check for the all-zero public key here because the scalar is
60
+ // never zero because of clamping, and the basepoint is not the identity in
61
+ // the prime-order subgroup(s).
62
+ return &PrivateKey{
63
+ curve: c,
64
+ privateKey: bytes.Clone(key),
65
+ publicKey: &PublicKey{curve: c, publicKey: publicKey},
66
+ }, nil
67
+ }
68
+
69
+ func (c *x25519Curve) NewPublicKey(key []byte) (*PublicKey, error) {
70
+ if fips140only.Enforced() {
71
+ return nil, errors.New("crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode")
72
+ }
73
+ if len(key) != x25519PublicKeySize {
74
+ return nil, errors.New("crypto/ecdh: invalid public key")
75
+ }
76
+ return &PublicKey{
77
+ curve: c,
78
+ publicKey: bytes.Clone(key),
79
+ }, nil
80
+ }
81
+
82
+ func (c *x25519Curve) ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error) {
83
+ out := make([]byte, x25519SharedSecretSize)
84
+ x25519ScalarMult(out, local.privateKey, remote.publicKey)
85
+ if isZero(out) {
86
+ return nil, errors.New("crypto/ecdh: bad X25519 remote ECDH input: low order point")
87
+ }
88
+ return out, nil
89
+ }
90
+
91
+ func x25519ScalarMult(dst, scalar, point []byte) {
92
+ var e [32]byte
93
+
94
+ copy(e[:], scalar[:])
95
+ e[0] &= 248
96
+ e[31] &= 127
97
+ e[31] |= 64
98
+
99
+ var x1, x2, z2, x3, z3, tmp0, tmp1 field.Element
100
+ x1.SetBytes(point[:])
101
+ x2.One()
102
+ x3.Set(&x1)
103
+ z3.One()
104
+
105
+ swap := 0
106
+ for pos := 254; pos >= 0; pos-- {
107
+ b := e[pos/8] >> uint(pos&7)
108
+ b &= 1
109
+ swap ^= int(b)
110
+ x2.Swap(&x3, swap)
111
+ z2.Swap(&z3, swap)
112
+ swap = int(b)
113
+
114
+ tmp0.Subtract(&x3, &z3)
115
+ tmp1.Subtract(&x2, &z2)
116
+ x2.Add(&x2, &z2)
117
+ z2.Add(&x3, &z3)
118
+ z3.Multiply(&tmp0, &x2)
119
+ z2.Multiply(&z2, &tmp1)
120
+ tmp0.Square(&tmp1)
121
+ tmp1.Square(&x2)
122
+ x3.Add(&z3, &z2)
123
+ z2.Subtract(&z3, &z2)
124
+ x2.Multiply(&tmp1, &tmp0)
125
+ tmp1.Subtract(&tmp1, &tmp0)
126
+ z2.Square(&z2)
127
+
128
+ z3.Mult32(&tmp1, 121666)
129
+ x3.Square(&x3)
130
+ tmp0.Add(&tmp0, &z3)
131
+ z3.Multiply(&x1, &z2)
132
+ z2.Multiply(&tmp1, &tmp0)
133
+ }
134
+
135
+ x2.Swap(&x3, swap)
136
+ z2.Swap(&z3, swap)
137
+
138
+ z2.Invert(&z2)
139
+ x2.Multiply(&x2, &z2)
140
+ copy(dst[:], x2.Bytes())
141
+ }
142
+
143
+ // isZero reports whether x is all zeroes in constant time.
144
+ func isZero(x []byte) bool {
145
+ var acc byte
146
+ for _, b := range x {
147
+ acc |= b
148
+ }
149
+ return acc == 0
150
+ }
go/src/crypto/ecdsa/boring.go ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 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
+ //go:build boringcrypto
6
+
7
+ package ecdsa
8
+
9
+ import (
10
+ "crypto/internal/boring"
11
+ "crypto/internal/boring/bbig"
12
+ "crypto/internal/boring/bcache"
13
+ "math/big"
14
+ )
15
+
16
+ // Cached conversions from Go PublicKey/PrivateKey to BoringCrypto.
17
+ //
18
+ // The first operation on a PublicKey or PrivateKey makes a parallel
19
+ // BoringCrypto key and saves it in pubCache or privCache.
20
+ //
21
+ // We could just assume that once used in a Sign or Verify operation,
22
+ // a particular key is never again modified, but that has not been a
23
+ // stated assumption before. Just in case there is any existing code that
24
+ // does modify the key between operations, we save the original values
25
+ // alongside the cached BoringCrypto key and check that the real key
26
+ // still matches before using the cached key. The theory is that the real
27
+ // operations are significantly more expensive than the comparison.
28
+
29
+ var pubCache bcache.Cache[PublicKey, boringPub]
30
+ var privCache bcache.Cache[PrivateKey, boringPriv]
31
+
32
+ func init() {
33
+ pubCache.Register()
34
+ privCache.Register()
35
+ }
36
+
37
+ type boringPub struct {
38
+ key *boring.PublicKeyECDSA
39
+ orig PublicKey
40
+ }
41
+
42
+ func boringPublicKey(pub *PublicKey) (*boring.PublicKeyECDSA, error) {
43
+ b := pubCache.Get(pub)
44
+ if b != nil && publicKeyEqual(&b.orig, pub) {
45
+ return b.key, nil
46
+ }
47
+
48
+ b = new(boringPub)
49
+ b.orig = copyPublicKey(pub)
50
+ key, err := boring.NewPublicKeyECDSA(b.orig.Curve.Params().Name, bbig.Enc(b.orig.X), bbig.Enc(b.orig.Y))
51
+ if err != nil {
52
+ return nil, err
53
+ }
54
+ b.key = key
55
+ pubCache.Put(pub, b)
56
+ return key, nil
57
+ }
58
+
59
+ type boringPriv struct {
60
+ key *boring.PrivateKeyECDSA
61
+ orig PrivateKey
62
+ }
63
+
64
+ func boringPrivateKey(priv *PrivateKey) (*boring.PrivateKeyECDSA, error) {
65
+ b := privCache.Get(priv)
66
+ if b != nil && privateKeyEqual(&b.orig, priv) {
67
+ return b.key, nil
68
+ }
69
+
70
+ b = new(boringPriv)
71
+ b.orig = copyPrivateKey(priv)
72
+ key, err := boring.NewPrivateKeyECDSA(b.orig.Curve.Params().Name, bbig.Enc(b.orig.X), bbig.Enc(b.orig.Y), bbig.Enc(b.orig.D))
73
+ if err != nil {
74
+ return nil, err
75
+ }
76
+ b.key = key
77
+ privCache.Put(priv, b)
78
+ return key, nil
79
+ }
80
+
81
+ func publicKeyEqual(k1, k2 *PublicKey) bool {
82
+ return k1.X != nil &&
83
+ k1.Curve.Params() == k2.Curve.Params() &&
84
+ k1.X.Cmp(k2.X) == 0 &&
85
+ k1.Y.Cmp(k2.Y) == 0
86
+ }
87
+
88
+ func privateKeyEqual(k1, k2 *PrivateKey) bool {
89
+ return publicKeyEqual(&k1.PublicKey, &k2.PublicKey) &&
90
+ k1.D.Cmp(k2.D) == 0
91
+ }
92
+
93
+ func copyPublicKey(k *PublicKey) PublicKey {
94
+ return PublicKey{
95
+ Curve: k.Curve,
96
+ X: new(big.Int).Set(k.X),
97
+ Y: new(big.Int).Set(k.Y),
98
+ }
99
+ }
100
+
101
+ func copyPrivateKey(k *PrivateKey) PrivateKey {
102
+ return PrivateKey{
103
+ PublicKey: copyPublicKey(&k.PublicKey),
104
+ D: new(big.Int).Set(k.D),
105
+ }
106
+ }
go/src/crypto/ecdsa/ecdsa.go ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
6
+ // defined in [FIPS 186-5].
7
+ //
8
+ // Signatures generated by this package are not deterministic, but entropy is
9
+ // mixed with the private key and the message, achieving the same level of
10
+ // security in case of randomness source failure.
11
+ //
12
+ // Operations involving private keys are implemented using constant-time
13
+ // algorithms, as long as an [elliptic.Curve] returned by [elliptic.P224],
14
+ // [elliptic.P256], [elliptic.P384], or [elliptic.P521] is used.
15
+ //
16
+ // [FIPS 186-5]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf
17
+ package ecdsa
18
+
19
+ import (
20
+ "crypto"
21
+ "crypto/ecdh"
22
+ "crypto/elliptic"
23
+ "crypto/internal/boring"
24
+ "crypto/internal/boring/bbig"
25
+ "crypto/internal/fips140/ecdsa"
26
+ "crypto/internal/fips140/nistec"
27
+ "crypto/internal/fips140cache"
28
+ "crypto/internal/fips140hash"
29
+ "crypto/internal/fips140only"
30
+ "crypto/internal/rand"
31
+ "crypto/sha512"
32
+ "crypto/subtle"
33
+ "errors"
34
+ "io"
35
+ "math/big"
36
+
37
+ "golang.org/x/crypto/cryptobyte"
38
+ "golang.org/x/crypto/cryptobyte/asn1"
39
+ )
40
+
41
+ // PublicKey represents an ECDSA public key.
42
+ type PublicKey struct {
43
+ elliptic.Curve
44
+
45
+ // X, Y are the coordinates of the public key point.
46
+ //
47
+ // Deprecated: modifying the raw coordinates can produce invalid keys, and may
48
+ // invalidate internal optimizations; moreover, [big.Int] methods are not
49
+ // suitable for operating on cryptographic values. To encode and decode
50
+ // PublicKey values, use [PublicKey.Bytes] and [ParseUncompressedPublicKey]
51
+ // or [crypto/x509.MarshalPKIXPublicKey] and [crypto/x509.ParsePKIXPublicKey].
52
+ // For ECDH, use [crypto/ecdh]. For lower-level elliptic curve operations,
53
+ // use a third-party module like filippo.io/nistec.
54
+ X, Y *big.Int
55
+ }
56
+
57
+ // Any methods implemented on PublicKey might need to also be implemented on
58
+ // PrivateKey, as the latter embeds the former and will expose its methods.
59
+
60
+ // ECDH returns k as a [ecdh.PublicKey]. It returns an error if the key is
61
+ // invalid according to the definition of [ecdh.Curve.NewPublicKey], or if the
62
+ // Curve is not supported by crypto/ecdh.
63
+ func (pub *PublicKey) ECDH() (*ecdh.PublicKey, error) {
64
+ c := curveToECDH(pub.Curve)
65
+ if c == nil {
66
+ return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
67
+ }
68
+ k, err := pub.Bytes()
69
+ if err != nil {
70
+ return nil, err
71
+ }
72
+ return c.NewPublicKey(k)
73
+ }
74
+
75
+ // Equal reports whether pub and x have the same value.
76
+ //
77
+ // Two keys are only considered to have the same value if they have the same Curve value.
78
+ // Note that for example [elliptic.P256] and elliptic.P256().Params() are different
79
+ // values, as the latter is a generic not constant time implementation.
80
+ func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
81
+ xx, ok := x.(*PublicKey)
82
+ if !ok {
83
+ return false
84
+ }
85
+ return bigIntEqual(pub.X, xx.X) && bigIntEqual(pub.Y, xx.Y) &&
86
+ // Standard library Curve implementations are singletons, so this check
87
+ // will work for those. Other Curves might be equivalent even if not
88
+ // singletons, but there is no definitive way to check for that, and
89
+ // better to err on the side of safety.
90
+ pub.Curve == xx.Curve
91
+ }
92
+
93
+ // ParseUncompressedPublicKey parses a public key encoded as an uncompressed
94
+ // point according to SEC 1, Version 2.0, Section 2.3.3 (also known as the X9.62
95
+ // uncompressed format). It returns an error if the point is not in uncompressed
96
+ // form, is not on the curve, or is the point at infinity.
97
+ //
98
+ // curve must be one of [elliptic.P224], [elliptic.P256], [elliptic.P384], or
99
+ // [elliptic.P521], or ParseUncompressedPublicKey returns an error.
100
+ //
101
+ // ParseUncompressedPublicKey accepts the same format as
102
+ // [ecdh.Curve.NewPublicKey] does for NIST curves, but returns a [PublicKey]
103
+ // instead of an [ecdh.PublicKey].
104
+ //
105
+ // Note that public keys are more commonly encoded in DER (or PEM) format, which
106
+ // can be parsed with [crypto/x509.ParsePKIXPublicKey] (and [encoding/pem]).
107
+ func ParseUncompressedPublicKey(curve elliptic.Curve, data []byte) (*PublicKey, error) {
108
+ if len(data) < 1 || data[0] != 4 {
109
+ return nil, errors.New("ecdsa: invalid uncompressed public key")
110
+ }
111
+ switch curve {
112
+ case elliptic.P224():
113
+ return parseUncompressedPublicKey(ecdsa.P224(), curve, data)
114
+ case elliptic.P256():
115
+ return parseUncompressedPublicKey(ecdsa.P256(), curve, data)
116
+ case elliptic.P384():
117
+ return parseUncompressedPublicKey(ecdsa.P384(), curve, data)
118
+ case elliptic.P521():
119
+ return parseUncompressedPublicKey(ecdsa.P521(), curve, data)
120
+ default:
121
+ return nil, errors.New("ecdsa: curve not supported by ParseUncompressedPublicKey")
122
+ }
123
+ }
124
+
125
+ func parseUncompressedPublicKey[P ecdsa.Point[P]](c *ecdsa.Curve[P], curve elliptic.Curve, data []byte) (*PublicKey, error) {
126
+ k, err := ecdsa.NewPublicKey(c, data)
127
+ if err != nil {
128
+ return nil, err
129
+ }
130
+ return publicKeyFromFIPS(curve, k)
131
+ }
132
+
133
+ // Bytes encodes the public key as an uncompressed point according to SEC 1,
134
+ // Version 2.0, Section 2.3.3 (also known as the X9.62 uncompressed format).
135
+ // It returns an error if the public key is invalid.
136
+ //
137
+ // PublicKey.Curve must be one of [elliptic.P224], [elliptic.P256],
138
+ // [elliptic.P384], or [elliptic.P521], or Bytes returns an error.
139
+ //
140
+ // Bytes returns the same format as [ecdh.PublicKey.Bytes] does for NIST curves.
141
+ //
142
+ // Note that public keys are more commonly encoded in DER (or PEM) format, which
143
+ // can be generated with [crypto/x509.MarshalPKIXPublicKey] (and [encoding/pem]).
144
+ func (pub *PublicKey) Bytes() ([]byte, error) {
145
+ switch pub.Curve {
146
+ case elliptic.P224():
147
+ return publicKeyBytes(ecdsa.P224(), pub)
148
+ case elliptic.P256():
149
+ return publicKeyBytes(ecdsa.P256(), pub)
150
+ case elliptic.P384():
151
+ return publicKeyBytes(ecdsa.P384(), pub)
152
+ case elliptic.P521():
153
+ return publicKeyBytes(ecdsa.P521(), pub)
154
+ default:
155
+ return nil, errors.New("ecdsa: curve not supported by PublicKey.Bytes")
156
+ }
157
+ }
158
+
159
+ func publicKeyBytes[P ecdsa.Point[P]](c *ecdsa.Curve[P], pub *PublicKey) ([]byte, error) {
160
+ k, err := publicKeyToFIPS(c, pub)
161
+ if err != nil {
162
+ return nil, err
163
+ }
164
+ return k.Bytes(), nil
165
+ }
166
+
167
+ // PrivateKey represents an ECDSA private key.
168
+ type PrivateKey struct {
169
+ PublicKey
170
+
171
+ // D is the private scalar value.
172
+ //
173
+ // Deprecated: modifying the raw value can produce invalid keys, and may
174
+ // invalidate internal optimizations; moreover, [big.Int] methods are not
175
+ // suitable for operating on cryptographic values. To encode and decode
176
+ // PrivateKey values, use [PrivateKey.Bytes] and [ParseRawPrivateKey] or
177
+ // [crypto/x509.MarshalPKCS8PrivateKey] and [crypto/x509.ParsePKCS8PrivateKey].
178
+ // For ECDH, use [crypto/ecdh].
179
+ D *big.Int
180
+ }
181
+
182
+ // ECDH returns k as a [ecdh.PrivateKey]. It returns an error if the key is
183
+ // invalid according to the definition of [ecdh.Curve.NewPrivateKey], or if the
184
+ // Curve is not supported by [crypto/ecdh].
185
+ func (priv *PrivateKey) ECDH() (*ecdh.PrivateKey, error) {
186
+ c := curveToECDH(priv.Curve)
187
+ if c == nil {
188
+ return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
189
+ }
190
+ k, err := priv.Bytes()
191
+ if err != nil {
192
+ return nil, err
193
+ }
194
+ return c.NewPrivateKey(k)
195
+ }
196
+
197
+ func curveToECDH(c elliptic.Curve) ecdh.Curve {
198
+ switch c {
199
+ case elliptic.P256():
200
+ return ecdh.P256()
201
+ case elliptic.P384():
202
+ return ecdh.P384()
203
+ case elliptic.P521():
204
+ return ecdh.P521()
205
+ default:
206
+ return nil
207
+ }
208
+ }
209
+
210
+ // Public returns the public key corresponding to priv.
211
+ func (priv *PrivateKey) Public() crypto.PublicKey {
212
+ return &priv.PublicKey
213
+ }
214
+
215
+ // Equal reports whether priv and x have the same value.
216
+ //
217
+ // See [PublicKey.Equal] for details on how Curve is compared.
218
+ func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
219
+ xx, ok := x.(*PrivateKey)
220
+ if !ok {
221
+ return false
222
+ }
223
+ return priv.PublicKey.Equal(&xx.PublicKey) && bigIntEqual(priv.D, xx.D)
224
+ }
225
+
226
+ // bigIntEqual reports whether a and b are equal leaking only their bit length
227
+ // through timing side-channels.
228
+ func bigIntEqual(a, b *big.Int) bool {
229
+ return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
230
+ }
231
+
232
+ // ParseRawPrivateKey parses a private key encoded as a fixed-length big-endian
233
+ // integer, according to SEC 1, Version 2.0, Section 2.3.6 (sometimes referred
234
+ // to as the raw format). It returns an error if the value is not reduced modulo
235
+ // the curve's order, or if it's zero.
236
+ //
237
+ // curve must be one of [elliptic.P224], [elliptic.P256], [elliptic.P384], or
238
+ // [elliptic.P521], or ParseRawPrivateKey returns an error.
239
+ //
240
+ // ParseRawPrivateKey accepts the same format as [ecdh.Curve.NewPrivateKey] does
241
+ // for NIST curves, but returns a [PrivateKey] instead of an [ecdh.PrivateKey].
242
+ //
243
+ // Note that private keys are more commonly encoded in ASN.1 or PKCS#8 format,
244
+ // which can be parsed with [crypto/x509.ParseECPrivateKey] or
245
+ // [crypto/x509.ParsePKCS8PrivateKey] (and [encoding/pem]).
246
+ func ParseRawPrivateKey(curve elliptic.Curve, data []byte) (*PrivateKey, error) {
247
+ switch curve {
248
+ case elliptic.P224():
249
+ return parseRawPrivateKey(ecdsa.P224(), nistec.NewP224Point, curve, data)
250
+ case elliptic.P256():
251
+ return parseRawPrivateKey(ecdsa.P256(), nistec.NewP256Point, curve, data)
252
+ case elliptic.P384():
253
+ return parseRawPrivateKey(ecdsa.P384(), nistec.NewP384Point, curve, data)
254
+ case elliptic.P521():
255
+ return parseRawPrivateKey(ecdsa.P521(), nistec.NewP521Point, curve, data)
256
+ default:
257
+ return nil, errors.New("ecdsa: curve not supported by ParseRawPrivateKey")
258
+ }
259
+ }
260
+
261
+ func parseRawPrivateKey[P ecdsa.Point[P]](c *ecdsa.Curve[P], newPoint func() P, curve elliptic.Curve, data []byte) (*PrivateKey, error) {
262
+ q, err := newPoint().ScalarBaseMult(data)
263
+ if err != nil {
264
+ return nil, err
265
+ }
266
+ k, err := ecdsa.NewPrivateKey(c, data, q.Bytes())
267
+ if err != nil {
268
+ return nil, err
269
+ }
270
+ return privateKeyFromFIPS(curve, k)
271
+ }
272
+
273
+ // Bytes encodes the private key as a fixed-length big-endian integer according
274
+ // to SEC 1, Version 2.0, Section 2.3.6 (sometimes referred to as the raw
275
+ // format). It returns an error if the private key is invalid.
276
+ //
277
+ // PrivateKey.Curve must be one of [elliptic.P224], [elliptic.P256],
278
+ // [elliptic.P384], or [elliptic.P521], or Bytes returns an error.
279
+ //
280
+ // Bytes returns the same format as [ecdh.PrivateKey.Bytes] does for NIST curves.
281
+ //
282
+ // Note that private keys are more commonly encoded in ASN.1 or PKCS#8 format,
283
+ // which can be generated with [crypto/x509.MarshalECPrivateKey] or
284
+ // [crypto/x509.MarshalPKCS8PrivateKey] (and [encoding/pem]).
285
+ func (priv *PrivateKey) Bytes() ([]byte, error) {
286
+ switch priv.Curve {
287
+ case elliptic.P224():
288
+ return privateKeyBytes(ecdsa.P224(), priv)
289
+ case elliptic.P256():
290
+ return privateKeyBytes(ecdsa.P256(), priv)
291
+ case elliptic.P384():
292
+ return privateKeyBytes(ecdsa.P384(), priv)
293
+ case elliptic.P521():
294
+ return privateKeyBytes(ecdsa.P521(), priv)
295
+ default:
296
+ return nil, errors.New("ecdsa: curve not supported by PrivateKey.Bytes")
297
+ }
298
+ }
299
+
300
+ func privateKeyBytes[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey) ([]byte, error) {
301
+ k, err := privateKeyToFIPS(c, priv)
302
+ if err != nil {
303
+ return nil, err
304
+ }
305
+ return k.Bytes(), nil
306
+ }
307
+
308
+ // Sign signs a hash (which should be the result of hashing a larger message
309
+ // with opts.HashFunc()) using the private key, priv. If the hash is longer than
310
+ // the bit-length of the private key's curve order, the hash will be truncated
311
+ // to that length. It returns the ASN.1 encoded signature, like [SignASN1].
312
+ //
313
+ // If random is not nil, the signature is randomized. Most applications should use
314
+ // [crypto/rand.Reader] as random, but unless GODEBUG=cryptocustomrand=1 is set, a
315
+ // secure source of random bytes is always used, and the actual Reader is ignored.
316
+ // The GODEBUG setting will be removed in a future Go release. Instead, use
317
+ // [testing/cryptotest.SetGlobalRandom].
318
+ //
319
+ // If random is nil, Sign will produce a deterministic signature according to RFC
320
+ // 6979. When producing a deterministic signature, opts.HashFunc() must be the
321
+ // function used to produce digest and priv.Curve must be one of
322
+ // [elliptic.P224], [elliptic.P256], [elliptic.P384], or [elliptic.P521].
323
+ func (priv *PrivateKey) Sign(random io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
324
+ if random == nil {
325
+ return signRFC6979(priv, digest, opts)
326
+ }
327
+ random = rand.CustomReader(random)
328
+ return SignASN1(random, priv, digest)
329
+ }
330
+
331
+ // GenerateKey generates a new ECDSA private key for the specified curve.
332
+ //
333
+ // Since Go 1.26, a secure source of random bytes is always used, and the Reader is
334
+ // ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed
335
+ // in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].
336
+ func GenerateKey(c elliptic.Curve, r io.Reader) (*PrivateKey, error) {
337
+ if boring.Enabled && rand.IsDefaultReader(r) {
338
+ x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
339
+ if err != nil {
340
+ return nil, err
341
+ }
342
+ return &PrivateKey{PublicKey: PublicKey{Curve: c, X: bbig.Dec(x), Y: bbig.Dec(y)}, D: bbig.Dec(d)}, nil
343
+ }
344
+ boring.UnreachableExceptTests()
345
+
346
+ r = rand.CustomReader(r)
347
+
348
+ switch c.Params() {
349
+ case elliptic.P224().Params():
350
+ return generateFIPS(c, ecdsa.P224(), r)
351
+ case elliptic.P256().Params():
352
+ return generateFIPS(c, ecdsa.P256(), r)
353
+ case elliptic.P384().Params():
354
+ return generateFIPS(c, ecdsa.P384(), r)
355
+ case elliptic.P521().Params():
356
+ return generateFIPS(c, ecdsa.P521(), r)
357
+ default:
358
+ return generateLegacy(c, r)
359
+ }
360
+ }
361
+
362
+ func generateFIPS[P ecdsa.Point[P]](curve elliptic.Curve, c *ecdsa.Curve[P], rand io.Reader) (*PrivateKey, error) {
363
+ if fips140only.Enforced() && !fips140only.ApprovedRandomReader(rand) {
364
+ return nil, errors.New("crypto/ecdsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
365
+ }
366
+ privateKey, err := ecdsa.GenerateKey(c, rand)
367
+ if err != nil {
368
+ return nil, err
369
+ }
370
+ return privateKeyFromFIPS(curve, privateKey)
371
+ }
372
+
373
+ // SignASN1 signs a hash (which should be the result of hashing a larger message)
374
+ // using the private key, priv. If the hash is longer than the bit-length of the
375
+ // private key's curve order, the hash will be truncated to that length. It
376
+ // returns the ASN.1 encoded signature.
377
+ //
378
+ // The signature is randomized. Since Go 1.26, a secure source of random bytes
379
+ // is always used, and the Reader is ignored unless GODEBUG=cryptocustomrand=1
380
+ // is set. This setting will be removed in a future Go release. Instead, use
381
+ // [testing/cryptotest.SetGlobalRandom].
382
+ func SignASN1(r io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
383
+ if boring.Enabled && rand.IsDefaultReader(r) {
384
+ b, err := boringPrivateKey(priv)
385
+ if err != nil {
386
+ return nil, err
387
+ }
388
+ return boring.SignMarshalECDSA(b, hash)
389
+ }
390
+ boring.UnreachableExceptTests()
391
+
392
+ r = rand.CustomReader(r)
393
+
394
+ switch priv.Curve.Params() {
395
+ case elliptic.P224().Params():
396
+ return signFIPS(ecdsa.P224(), priv, r, hash)
397
+ case elliptic.P256().Params():
398
+ return signFIPS(ecdsa.P256(), priv, r, hash)
399
+ case elliptic.P384().Params():
400
+ return signFIPS(ecdsa.P384(), priv, r, hash)
401
+ case elliptic.P521().Params():
402
+ return signFIPS(ecdsa.P521(), priv, r, hash)
403
+ default:
404
+ return signLegacy(priv, r, hash)
405
+ }
406
+ }
407
+
408
+ func signFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey, rand io.Reader, hash []byte) ([]byte, error) {
409
+ if fips140only.Enforced() && !fips140only.ApprovedRandomReader(rand) {
410
+ return nil, errors.New("crypto/ecdsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
411
+ }
412
+ k, err := privateKeyToFIPS(c, priv)
413
+ if err != nil {
414
+ return nil, err
415
+ }
416
+ // Always using SHA-512 instead of the hash that computed hash is
417
+ // technically a violation of draft-irtf-cfrg-det-sigs-with-noise-04 but in
418
+ // our API we don't get to know what it was, and this has no security impact.
419
+ sig, err := ecdsa.Sign(c, sha512.New, k, rand, hash)
420
+ if err != nil {
421
+ return nil, err
422
+ }
423
+ return encodeSignature(sig.R, sig.S)
424
+ }
425
+
426
+ func signRFC6979(priv *PrivateKey, hash []byte, opts crypto.SignerOpts) ([]byte, error) {
427
+ if opts == nil {
428
+ return nil, errors.New("ecdsa: Sign called with nil opts")
429
+ }
430
+ h := opts.HashFunc()
431
+ if h.Size() != len(hash) {
432
+ return nil, errors.New("ecdsa: hash length does not match hash function")
433
+ }
434
+ switch priv.Curve.Params() {
435
+ case elliptic.P224().Params():
436
+ return signFIPSDeterministic(ecdsa.P224(), h, priv, hash)
437
+ case elliptic.P256().Params():
438
+ return signFIPSDeterministic(ecdsa.P256(), h, priv, hash)
439
+ case elliptic.P384().Params():
440
+ return signFIPSDeterministic(ecdsa.P384(), h, priv, hash)
441
+ case elliptic.P521().Params():
442
+ return signFIPSDeterministic(ecdsa.P521(), h, priv, hash)
443
+ default:
444
+ return nil, errors.New("ecdsa: curve not supported by deterministic signatures")
445
+ }
446
+ }
447
+
448
+ func signFIPSDeterministic[P ecdsa.Point[P]](c *ecdsa.Curve[P], hashFunc crypto.Hash, priv *PrivateKey, hash []byte) ([]byte, error) {
449
+ k, err := privateKeyToFIPS(c, priv)
450
+ if err != nil {
451
+ return nil, err
452
+ }
453
+ h := fips140hash.UnwrapNew(hashFunc.New)
454
+ if fips140only.Enforced() && !fips140only.ApprovedHash(h()) {
455
+ return nil, errors.New("crypto/ecdsa: use of hash functions other than SHA-2 or SHA-3 is not allowed in FIPS 140-only mode")
456
+ }
457
+ sig, err := ecdsa.SignDeterministic(c, h, k, hash)
458
+ if err != nil {
459
+ return nil, err
460
+ }
461
+ return encodeSignature(sig.R, sig.S)
462
+ }
463
+
464
+ func encodeSignature(r, s []byte) ([]byte, error) {
465
+ var b cryptobyte.Builder
466
+ b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
467
+ addASN1IntBytes(b, r)
468
+ addASN1IntBytes(b, s)
469
+ })
470
+ return b.Bytes()
471
+ }
472
+
473
+ // addASN1IntBytes encodes in ASN.1 a positive integer represented as
474
+ // a big-endian byte slice with zero or more leading zeroes.
475
+ func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
476
+ for len(bytes) > 0 && bytes[0] == 0 {
477
+ bytes = bytes[1:]
478
+ }
479
+ if len(bytes) == 0 {
480
+ b.SetError(errors.New("invalid integer"))
481
+ return
482
+ }
483
+ b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
484
+ if bytes[0]&0x80 != 0 {
485
+ c.AddUint8(0)
486
+ }
487
+ c.AddBytes(bytes)
488
+ })
489
+ }
490
+
491
+ // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
492
+ // public key, pub. Its return value records whether the signature is valid.
493
+ //
494
+ // The inputs are not considered confidential, and may leak through timing side
495
+ // channels, or if an attacker has control of part of the inputs.
496
+ func VerifyASN1(pub *PublicKey, hash, sig []byte) bool {
497
+ if boring.Enabled {
498
+ key, err := boringPublicKey(pub)
499
+ if err != nil {
500
+ return false
501
+ }
502
+ return boring.VerifyECDSA(key, hash, sig)
503
+ }
504
+ boring.UnreachableExceptTests()
505
+
506
+ switch pub.Curve.Params() {
507
+ case elliptic.P224().Params():
508
+ return verifyFIPS(ecdsa.P224(), pub, hash, sig)
509
+ case elliptic.P256().Params():
510
+ return verifyFIPS(ecdsa.P256(), pub, hash, sig)
511
+ case elliptic.P384().Params():
512
+ return verifyFIPS(ecdsa.P384(), pub, hash, sig)
513
+ case elliptic.P521().Params():
514
+ return verifyFIPS(ecdsa.P521(), pub, hash, sig)
515
+ default:
516
+ return verifyLegacy(pub, hash, sig)
517
+ }
518
+ }
519
+
520
+ func verifyFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], pub *PublicKey, hash, sig []byte) bool {
521
+ r, s, err := parseSignature(sig)
522
+ if err != nil {
523
+ return false
524
+ }
525
+ k, err := publicKeyToFIPS(c, pub)
526
+ if err != nil {
527
+ return false
528
+ }
529
+ if err := ecdsa.Verify(c, k, hash, &ecdsa.Signature{R: r, S: s}); err != nil {
530
+ return false
531
+ }
532
+ return true
533
+ }
534
+
535
+ func parseSignature(sig []byte) (r, s []byte, err error) {
536
+ var inner cryptobyte.String
537
+ input := cryptobyte.String(sig)
538
+ if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
539
+ !input.Empty() ||
540
+ !inner.ReadASN1Integer(&r) ||
541
+ !inner.ReadASN1Integer(&s) ||
542
+ !inner.Empty() {
543
+ return nil, nil, errors.New("invalid ASN.1")
544
+ }
545
+ return r, s, nil
546
+ }
547
+
548
+ func publicKeyFromFIPS(curve elliptic.Curve, pub *ecdsa.PublicKey) (*PublicKey, error) {
549
+ x, y, err := pointToAffine(curve, pub.Bytes())
550
+ if err != nil {
551
+ return nil, err
552
+ }
553
+ return &PublicKey{Curve: curve, X: x, Y: y}, nil
554
+ }
555
+
556
+ func privateKeyFromFIPS(curve elliptic.Curve, priv *ecdsa.PrivateKey) (*PrivateKey, error) {
557
+ pub, err := publicKeyFromFIPS(curve, priv.PublicKey())
558
+ if err != nil {
559
+ return nil, err
560
+ }
561
+ return &PrivateKey{PublicKey: *pub, D: new(big.Int).SetBytes(priv.Bytes())}, nil
562
+ }
563
+
564
+ func publicKeyToFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], pub *PublicKey) (*ecdsa.PublicKey, error) {
565
+ Q, err := pointFromAffine(pub.Curve, pub.X, pub.Y)
566
+ if err != nil {
567
+ return nil, err
568
+ }
569
+ return ecdsa.NewPublicKey(c, Q)
570
+ }
571
+
572
+ var privateKeyCache fips140cache.Cache[PrivateKey, ecdsa.PrivateKey]
573
+
574
+ func privateKeyToFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey) (*ecdsa.PrivateKey, error) {
575
+ Q, err := pointFromAffine(priv.Curve, priv.X, priv.Y)
576
+ if err != nil {
577
+ return nil, err
578
+ }
579
+
580
+ // Reject values that would not get correctly encoded.
581
+ if priv.D.BitLen() > priv.Curve.Params().N.BitLen() {
582
+ return nil, errors.New("ecdsa: private key scalar too large")
583
+ }
584
+ if priv.D.Sign() <= 0 {
585
+ return nil, errors.New("ecdsa: private key scalar is zero or negative")
586
+ }
587
+
588
+ size := (priv.Curve.Params().N.BitLen() + 7) / 8
589
+ const maxScalarSize = 66 // enough for a P-521 private key
590
+ if size > maxScalarSize {
591
+ return nil, errors.New("ecdsa: internal error: curve size too large")
592
+ }
593
+ D := priv.D.FillBytes(make([]byte, size, maxScalarSize))
594
+
595
+ return privateKeyCache.Get(priv, func() (*ecdsa.PrivateKey, error) {
596
+ return ecdsa.NewPrivateKey(c, D, Q)
597
+ }, func(k *ecdsa.PrivateKey) bool {
598
+ return subtle.ConstantTimeCompare(k.PublicKey().Bytes(), Q) == 1 &&
599
+ subtle.ConstantTimeCompare(k.Bytes(), D) == 1
600
+ })
601
+ }
602
+
603
+ // pointFromAffine is used to convert the PublicKey to a nistec SetBytes input.
604
+ func pointFromAffine(curve elliptic.Curve, x, y *big.Int) ([]byte, error) {
605
+ bitSize := curve.Params().BitSize
606
+ // Reject values that would not get correctly encoded.
607
+ if x.Sign() < 0 || y.Sign() < 0 {
608
+ return nil, errors.New("negative coordinate")
609
+ }
610
+ if x.BitLen() > bitSize || y.BitLen() > bitSize {
611
+ return nil, errors.New("overflowing coordinate")
612
+ }
613
+ // Encode the coordinates and let [ecdsa.NewPublicKey] reject invalid points.
614
+ byteLen := (bitSize + 7) / 8
615
+ buf := make([]byte, 1+2*byteLen)
616
+ buf[0] = 4 // uncompressed point
617
+ x.FillBytes(buf[1 : 1+byteLen])
618
+ y.FillBytes(buf[1+byteLen : 1+2*byteLen])
619
+ return buf, nil
620
+ }
621
+
622
+ // pointToAffine is used to convert a nistec Bytes encoding to a PublicKey.
623
+ func pointToAffine(curve elliptic.Curve, p []byte) (x, y *big.Int, err error) {
624
+ if len(p) == 1 && p[0] == 0 {
625
+ // This is the encoding of the point at infinity.
626
+ return nil, nil, errors.New("ecdsa: public key point is the infinity")
627
+ }
628
+ byteLen := (curve.Params().BitSize + 7) / 8
629
+ x = new(big.Int).SetBytes(p[1 : 1+byteLen])
630
+ y = new(big.Int).SetBytes(p[1+byteLen:])
631
+ return x, y, nil
632
+ }
go/src/crypto/ecdsa/ecdsa_legacy.go ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 ecdsa
6
+
7
+ import (
8
+ "crypto/elliptic"
9
+ "crypto/internal/fips140only"
10
+ "errors"
11
+ "io"
12
+ "math/big"
13
+ "math/rand/v2"
14
+
15
+ "golang.org/x/crypto/cryptobyte"
16
+ "golang.org/x/crypto/cryptobyte/asn1"
17
+ )
18
+
19
+ // This file contains a math/big implementation of ECDSA that is only used for
20
+ // deprecated custom curves.
21
+
22
+ func generateLegacy(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
23
+ if fips140only.Enforced() {
24
+ return nil, errors.New("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
25
+ }
26
+
27
+ k, err := randFieldElement(c, rand)
28
+ if err != nil {
29
+ return nil, err
30
+ }
31
+
32
+ priv := new(PrivateKey)
33
+ priv.PublicKey.Curve = c
34
+ priv.D = k
35
+ priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
36
+ return priv, nil
37
+ }
38
+
39
+ // hashToInt converts a hash value to an integer. Per FIPS 186-4, Section 6.4,
40
+ // we use the left-most bits of the hash to match the bit-length of the order of
41
+ // the curve. This also performs Step 5 of SEC 1, Version 2.0, Section 4.1.3.
42
+ func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
43
+ orderBits := c.Params().N.BitLen()
44
+ orderBytes := (orderBits + 7) / 8
45
+ if len(hash) > orderBytes {
46
+ hash = hash[:orderBytes]
47
+ }
48
+
49
+ ret := new(big.Int).SetBytes(hash)
50
+ excess := len(hash)*8 - orderBits
51
+ if excess > 0 {
52
+ ret.Rsh(ret, uint(excess))
53
+ }
54
+ return ret
55
+ }
56
+
57
+ var errZeroParam = errors.New("zero parameter")
58
+
59
+ // Sign signs a hash (which should be the result of hashing a larger message)
60
+ // using the private key, priv. If the hash is longer than the bit-length of the
61
+ // private key's curve order, the hash will be truncated to that length. It
62
+ // returns the signature as a pair of integers. Most applications should use
63
+ // [SignASN1] instead of dealing directly with r, s.
64
+ //
65
+ // The signature is randomized. Since Go 1.26, a secure source of random bytes
66
+ // is always used, and the Reader is ignored unless GODEBUG=cryptocustomrand=1
67
+ // is set. This setting will be removed in a future Go release. Instead, use
68
+ // [testing/cryptotest.SetGlobalRandom].
69
+ func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
70
+ sig, err := SignASN1(rand, priv, hash)
71
+ if err != nil {
72
+ return nil, nil, err
73
+ }
74
+
75
+ r, s = new(big.Int), new(big.Int)
76
+ var inner cryptobyte.String
77
+ input := cryptobyte.String(sig)
78
+ if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
79
+ !input.Empty() ||
80
+ !inner.ReadASN1Integer(r) ||
81
+ !inner.ReadASN1Integer(s) ||
82
+ !inner.Empty() {
83
+ return nil, nil, errors.New("invalid ASN.1 from SignASN1")
84
+ }
85
+ return r, s, nil
86
+ }
87
+
88
+ func signLegacy(priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) {
89
+ if fips140only.Enforced() {
90
+ return nil, errors.New("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
91
+ }
92
+
93
+ c := priv.Curve
94
+
95
+ // A cheap version of hedged signatures, for the deprecated path.
96
+ var seed [32]byte
97
+ if _, err := io.ReadFull(csprng, seed[:]); err != nil {
98
+ return nil, err
99
+ }
100
+ for i, b := range priv.D.Bytes() {
101
+ seed[i%32] ^= b
102
+ }
103
+ for i, b := range hash {
104
+ seed[i%32] ^= b
105
+ }
106
+ csprng = rand.NewChaCha8(seed)
107
+
108
+ // SEC 1, Version 2.0, Section 4.1.3
109
+ N := c.Params().N
110
+ if N.Sign() == 0 {
111
+ return nil, errZeroParam
112
+ }
113
+ var k, kInv, r, s *big.Int
114
+ for {
115
+ for {
116
+ k, err = randFieldElement(c, csprng)
117
+ if err != nil {
118
+ return nil, err
119
+ }
120
+
121
+ kInv = new(big.Int).ModInverse(k, N)
122
+
123
+ r, _ = c.ScalarBaseMult(k.Bytes())
124
+ r.Mod(r, N)
125
+ if r.Sign() != 0 {
126
+ break
127
+ }
128
+ }
129
+
130
+ e := hashToInt(hash, c)
131
+ s = new(big.Int).Mul(priv.D, r)
132
+ s.Add(s, e)
133
+ s.Mul(s, kInv)
134
+ s.Mod(s, N) // N != 0
135
+ if s.Sign() != 0 {
136
+ break
137
+ }
138
+ }
139
+
140
+ return encodeSignature(r.Bytes(), s.Bytes())
141
+ }
142
+
143
+ // Verify verifies the signature in r, s of hash using the public key, pub. Its
144
+ // return value records whether the signature is valid. Most applications should
145
+ // use VerifyASN1 instead of dealing directly with r, s.
146
+ //
147
+ // The inputs are not considered confidential, and may leak through timing side
148
+ // channels, or if an attacker has control of part of the inputs.
149
+ func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
150
+ if r.Sign() <= 0 || s.Sign() <= 0 {
151
+ return false
152
+ }
153
+ sig, err := encodeSignature(r.Bytes(), s.Bytes())
154
+ if err != nil {
155
+ return false
156
+ }
157
+ return VerifyASN1(pub, hash, sig)
158
+ }
159
+
160
+ func verifyLegacy(pub *PublicKey, hash []byte, sig []byte) bool {
161
+ if fips140only.Enforced() {
162
+ panic("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
163
+ }
164
+
165
+ rBytes, sBytes, err := parseSignature(sig)
166
+ if err != nil {
167
+ return false
168
+ }
169
+ r, s := new(big.Int).SetBytes(rBytes), new(big.Int).SetBytes(sBytes)
170
+
171
+ c := pub.Curve
172
+ N := c.Params().N
173
+
174
+ if r.Sign() <= 0 || s.Sign() <= 0 {
175
+ return false
176
+ }
177
+ if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
178
+ return false
179
+ }
180
+
181
+ // SEC 1, Version 2.0, Section 4.1.4
182
+ e := hashToInt(hash, c)
183
+ w := new(big.Int).ModInverse(s, N)
184
+
185
+ u1 := e.Mul(e, w)
186
+ u1.Mod(u1, N)
187
+ u2 := w.Mul(r, w)
188
+ u2.Mod(u2, N)
189
+
190
+ x1, y1 := c.ScalarBaseMult(u1.Bytes())
191
+ x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
192
+ x, y := c.Add(x1, y1, x2, y2)
193
+
194
+ if x.Sign() == 0 && y.Sign() == 0 {
195
+ return false
196
+ }
197
+ x.Mod(x, N)
198
+ return x.Cmp(r) == 0
199
+ }
200
+
201
+ var one = new(big.Int).SetInt64(1)
202
+
203
+ // randFieldElement returns a random element of the order of the given
204
+ // curve using the procedure given in FIPS 186-4, Appendix B.5.2.
205
+ func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
206
+ for {
207
+ N := c.Params().N
208
+ b := make([]byte, (N.BitLen()+7)/8)
209
+ if _, err = io.ReadFull(rand, b); err != nil {
210
+ return
211
+ }
212
+ if excess := len(b)*8 - N.BitLen(); excess > 0 {
213
+ b[0] >>= excess
214
+ }
215
+ k = new(big.Int).SetBytes(b)
216
+ if k.Sign() != 0 && k.Cmp(N) < 0 {
217
+ return
218
+ }
219
+ }
220
+ }
go/src/crypto/ecdsa/ecdsa_test.go ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 ecdsa
6
+
7
+ import (
8
+ "bufio"
9
+ "bytes"
10
+ "compress/bzip2"
11
+ "crypto"
12
+ "crypto/elliptic"
13
+ "crypto/internal/cryptotest"
14
+ "crypto/rand"
15
+ "crypto/sha1"
16
+ "crypto/sha256"
17
+ "crypto/sha512"
18
+ "encoding/hex"
19
+ "hash"
20
+ "io"
21
+ "math/big"
22
+ "os"
23
+ "strings"
24
+ "testing"
25
+ )
26
+
27
+ func testAllCurves(t *testing.T, f func(*testing.T, elliptic.Curve)) {
28
+ tests := []struct {
29
+ name string
30
+ curve elliptic.Curve
31
+ }{
32
+ {"P256", elliptic.P256()},
33
+ {"P224", elliptic.P224()},
34
+ {"P384", elliptic.P384()},
35
+ {"P521", elliptic.P521()},
36
+ {"P256/Generic", genericParamsForCurve(elliptic.P256())},
37
+ }
38
+ if testing.Short() {
39
+ tests = tests[:1]
40
+ }
41
+ for _, test := range tests {
42
+ curve := test.curve
43
+ cryptotest.TestAllImplementations(t, "ecdsa", func(t *testing.T) {
44
+ t.Run(test.name, func(t *testing.T) {
45
+ t.Parallel()
46
+ f(t, curve)
47
+ })
48
+ })
49
+ }
50
+ }
51
+
52
+ // genericParamsForCurve returns the dereferenced CurveParams for
53
+ // the specified curve. This is used to avoid the logic for
54
+ // upgrading a curve to its specific implementation, forcing
55
+ // usage of the generic implementation.
56
+ func genericParamsForCurve(c elliptic.Curve) *elliptic.CurveParams {
57
+ d := *(c.Params())
58
+ return &d
59
+ }
60
+
61
+ func TestKeyGeneration(t *testing.T) {
62
+ testAllCurves(t, testKeyGeneration)
63
+ }
64
+
65
+ func testKeyGeneration(t *testing.T, c elliptic.Curve) {
66
+ priv, err := GenerateKey(c, rand.Reader)
67
+ if err != nil {
68
+ t.Fatal(err)
69
+ }
70
+ if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) {
71
+ t.Errorf("public key invalid: %s", err)
72
+ }
73
+ }
74
+
75
+ func TestSignAndVerify(t *testing.T) {
76
+ testAllCurves(t, testSignAndVerify)
77
+ }
78
+
79
+ func testSignAndVerify(t *testing.T, c elliptic.Curve) {
80
+ priv, _ := GenerateKey(c, rand.Reader)
81
+
82
+ hashed := []byte("testing")
83
+ r, s, err := Sign(rand.Reader, priv, hashed)
84
+ if err != nil {
85
+ t.Errorf("error signing: %s", err)
86
+ return
87
+ }
88
+
89
+ if !Verify(&priv.PublicKey, hashed, r, s) {
90
+ t.Errorf("Verify failed")
91
+ }
92
+
93
+ hashed[0] ^= 0xff
94
+ if Verify(&priv.PublicKey, hashed, r, s) {
95
+ t.Errorf("Verify always works!")
96
+ }
97
+ }
98
+
99
+ func TestSignAndVerifyASN1(t *testing.T) {
100
+ testAllCurves(t, testSignAndVerifyASN1)
101
+ }
102
+
103
+ func testSignAndVerifyASN1(t *testing.T, c elliptic.Curve) {
104
+ priv, _ := GenerateKey(c, rand.Reader)
105
+
106
+ hashed := []byte("testing")
107
+ sig, err := SignASN1(rand.Reader, priv, hashed)
108
+ if err != nil {
109
+ t.Errorf("error signing: %s", err)
110
+ return
111
+ }
112
+
113
+ if !VerifyASN1(&priv.PublicKey, hashed, sig) {
114
+ t.Errorf("VerifyASN1 failed")
115
+ }
116
+
117
+ hashed[0] ^= 0xff
118
+ if VerifyASN1(&priv.PublicKey, hashed, sig) {
119
+ t.Errorf("VerifyASN1 always works!")
120
+ }
121
+ }
122
+
123
+ func TestNonceSafety(t *testing.T) {
124
+ testAllCurves(t, testNonceSafety)
125
+ }
126
+
127
+ func testNonceSafety(t *testing.T, c elliptic.Curve) {
128
+ priv, _ := GenerateKey(c, rand.Reader)
129
+
130
+ hashed := []byte("testing")
131
+ r0, s0, err := Sign(zeroReader, priv, hashed)
132
+ if err != nil {
133
+ t.Errorf("error signing: %s", err)
134
+ return
135
+ }
136
+
137
+ hashed = []byte("testing...")
138
+ r1, s1, err := Sign(zeroReader, priv, hashed)
139
+ if err != nil {
140
+ t.Errorf("error signing: %s", err)
141
+ return
142
+ }
143
+
144
+ if s0.Cmp(s1) == 0 {
145
+ // This should never happen.
146
+ t.Errorf("the signatures on two different messages were the same")
147
+ }
148
+
149
+ if r0.Cmp(r1) == 0 {
150
+ t.Errorf("the nonce used for two different messages was the same")
151
+ }
152
+ }
153
+
154
+ type readerFunc func([]byte) (int, error)
155
+
156
+ func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
157
+
158
+ var zeroReader = readerFunc(func(b []byte) (int, error) {
159
+ clear(b)
160
+ return len(b), nil
161
+ })
162
+
163
+ func TestINDCCA(t *testing.T) {
164
+ testAllCurves(t, testINDCCA)
165
+ }
166
+
167
+ func testINDCCA(t *testing.T, c elliptic.Curve) {
168
+ priv, _ := GenerateKey(c, rand.Reader)
169
+
170
+ hashed := []byte("testing")
171
+ r0, s0, err := Sign(rand.Reader, priv, hashed)
172
+ if err != nil {
173
+ t.Errorf("error signing: %s", err)
174
+ return
175
+ }
176
+
177
+ r1, s1, err := Sign(rand.Reader, priv, hashed)
178
+ if err != nil {
179
+ t.Errorf("error signing: %s", err)
180
+ return
181
+ }
182
+
183
+ if s0.Cmp(s1) == 0 {
184
+ t.Errorf("two signatures of the same message produced the same result")
185
+ }
186
+
187
+ if r0.Cmp(r1) == 0 {
188
+ t.Errorf("two signatures of the same message produced the same nonce")
189
+ }
190
+ }
191
+
192
+ func fromHex(s string) *big.Int {
193
+ r, ok := new(big.Int).SetString(s, 16)
194
+ if !ok {
195
+ panic("bad hex")
196
+ }
197
+ return r
198
+ }
199
+
200
+ func TestVectors(t *testing.T) {
201
+ cryptotest.TestAllImplementations(t, "ecdsa", testVectors)
202
+ }
203
+
204
+ func testVectors(t *testing.T) {
205
+ // This test runs the full set of NIST test vectors from
206
+ // https://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3ecdsatestvectors.zip
207
+ //
208
+ // The SigVer.rsp file has been edited to remove test vectors for
209
+ // unsupported algorithms and has been compressed.
210
+
211
+ if testing.Short() {
212
+ return
213
+ }
214
+
215
+ f, err := os.Open("testdata/SigVer.rsp.bz2")
216
+ if err != nil {
217
+ t.Fatal(err)
218
+ }
219
+
220
+ buf := bufio.NewReader(bzip2.NewReader(f))
221
+
222
+ lineNo := 1
223
+ var h hash.Hash
224
+ var msg []byte
225
+ var hashed []byte
226
+ var r, s *big.Int
227
+ pub := new(PublicKey)
228
+
229
+ for {
230
+ line, err := buf.ReadString('\n')
231
+ if len(line) == 0 {
232
+ if err == io.EOF {
233
+ break
234
+ }
235
+ t.Fatalf("error reading from input: %s", err)
236
+ }
237
+ lineNo++
238
+ // Need to remove \r\n from the end of the line.
239
+ if !strings.HasSuffix(line, "\r\n") {
240
+ t.Fatalf("bad line ending (expected \\r\\n) on line %d", lineNo)
241
+ }
242
+ line = line[:len(line)-2]
243
+
244
+ if len(line) == 0 || line[0] == '#' {
245
+ continue
246
+ }
247
+
248
+ if line[0] == '[' {
249
+ line = line[1 : len(line)-1]
250
+ curve, hash, _ := strings.Cut(line, ",")
251
+
252
+ switch curve {
253
+ case "P-224":
254
+ pub.Curve = elliptic.P224()
255
+ case "P-256":
256
+ pub.Curve = elliptic.P256()
257
+ case "P-384":
258
+ pub.Curve = elliptic.P384()
259
+ case "P-521":
260
+ pub.Curve = elliptic.P521()
261
+ default:
262
+ pub.Curve = nil
263
+ }
264
+
265
+ switch hash {
266
+ case "SHA-1":
267
+ h = sha1.New()
268
+ case "SHA-224":
269
+ h = sha256.New224()
270
+ case "SHA-256":
271
+ h = sha256.New()
272
+ case "SHA-384":
273
+ h = sha512.New384()
274
+ case "SHA-512":
275
+ h = sha512.New()
276
+ default:
277
+ h = nil
278
+ }
279
+
280
+ continue
281
+ }
282
+
283
+ if h == nil || pub.Curve == nil {
284
+ continue
285
+ }
286
+
287
+ switch {
288
+ case strings.HasPrefix(line, "Msg = "):
289
+ if msg, err = hex.DecodeString(line[6:]); err != nil {
290
+ t.Fatalf("failed to decode message on line %d: %s", lineNo, err)
291
+ }
292
+ case strings.HasPrefix(line, "Qx = "):
293
+ pub.X = fromHex(line[5:])
294
+ case strings.HasPrefix(line, "Qy = "):
295
+ pub.Y = fromHex(line[5:])
296
+ case strings.HasPrefix(line, "R = "):
297
+ r = fromHex(line[4:])
298
+ case strings.HasPrefix(line, "S = "):
299
+ s = fromHex(line[4:])
300
+ case strings.HasPrefix(line, "Result = "):
301
+ expected := line[9] == 'P'
302
+ h.Reset()
303
+ h.Write(msg)
304
+ hashed := h.Sum(hashed[:0])
305
+ if Verify(pub, hashed, r, s) != expected {
306
+ t.Fatalf("incorrect result on line %d", lineNo)
307
+ }
308
+ default:
309
+ t.Fatalf("unknown variable on line %d: %s", lineNo, line)
310
+ }
311
+ }
312
+ }
313
+
314
+ func TestNegativeInputs(t *testing.T) {
315
+ testAllCurves(t, testNegativeInputs)
316
+ }
317
+
318
+ func testNegativeInputs(t *testing.T, curve elliptic.Curve) {
319
+ key, err := GenerateKey(curve, rand.Reader)
320
+ if err != nil {
321
+ t.Errorf("failed to generate key")
322
+ }
323
+
324
+ var hash [32]byte
325
+ r := new(big.Int).SetInt64(1)
326
+ r.Lsh(r, 550 /* larger than any supported curve */)
327
+ r.Neg(r)
328
+
329
+ if Verify(&key.PublicKey, hash[:], r, r) {
330
+ t.Errorf("bogus signature accepted")
331
+ }
332
+ }
333
+
334
+ func TestZeroHashSignature(t *testing.T) {
335
+ testAllCurves(t, testZeroHashSignature)
336
+ }
337
+
338
+ func testZeroHashSignature(t *testing.T, curve elliptic.Curve) {
339
+ zeroHash := make([]byte, 64)
340
+
341
+ privKey, err := GenerateKey(curve, rand.Reader)
342
+ if err != nil {
343
+ panic(err)
344
+ }
345
+
346
+ // Sign a hash consisting of all zeros.
347
+ r, s, err := Sign(rand.Reader, privKey, zeroHash)
348
+ if err != nil {
349
+ panic(err)
350
+ }
351
+
352
+ // Confirm that it can be verified.
353
+ if !Verify(&privKey.PublicKey, zeroHash, r, s) {
354
+ t.Errorf("zero hash signature verify failed for %T", curve)
355
+ }
356
+ }
357
+
358
+ func TestZeroSignature(t *testing.T) {
359
+ testAllCurves(t, testZeroSignature)
360
+ }
361
+
362
+ func testZeroSignature(t *testing.T, curve elliptic.Curve) {
363
+ privKey, err := GenerateKey(curve, rand.Reader)
364
+ if err != nil {
365
+ panic(err)
366
+ }
367
+
368
+ if Verify(&privKey.PublicKey, make([]byte, 64), big.NewInt(0), big.NewInt(0)) {
369
+ t.Errorf("Verify with r,s=0 succeeded: %T", curve)
370
+ }
371
+ }
372
+
373
+ func TestNegativeSignature(t *testing.T) {
374
+ testAllCurves(t, testNegativeSignature)
375
+ }
376
+
377
+ func testNegativeSignature(t *testing.T, curve elliptic.Curve) {
378
+ zeroHash := make([]byte, 64)
379
+
380
+ privKey, err := GenerateKey(curve, rand.Reader)
381
+ if err != nil {
382
+ panic(err)
383
+ }
384
+ r, s, err := Sign(rand.Reader, privKey, zeroHash)
385
+ if err != nil {
386
+ panic(err)
387
+ }
388
+
389
+ r = r.Neg(r)
390
+ if Verify(&privKey.PublicKey, zeroHash, r, s) {
391
+ t.Errorf("Verify with r=-r succeeded: %T", curve)
392
+ }
393
+ }
394
+
395
+ func TestRPlusNSignature(t *testing.T) {
396
+ testAllCurves(t, testRPlusNSignature)
397
+ }
398
+
399
+ func testRPlusNSignature(t *testing.T, curve elliptic.Curve) {
400
+ zeroHash := make([]byte, 64)
401
+
402
+ privKey, err := GenerateKey(curve, rand.Reader)
403
+ if err != nil {
404
+ panic(err)
405
+ }
406
+ r, s, err := Sign(rand.Reader, privKey, zeroHash)
407
+ if err != nil {
408
+ panic(err)
409
+ }
410
+
411
+ r = r.Add(r, curve.Params().N)
412
+ if Verify(&privKey.PublicKey, zeroHash, r, s) {
413
+ t.Errorf("Verify with r=r+n succeeded: %T", curve)
414
+ }
415
+ }
416
+
417
+ func TestRMinusNSignature(t *testing.T) {
418
+ testAllCurves(t, testRMinusNSignature)
419
+ }
420
+
421
+ func testRMinusNSignature(t *testing.T, curve elliptic.Curve) {
422
+ zeroHash := make([]byte, 64)
423
+
424
+ privKey, err := GenerateKey(curve, rand.Reader)
425
+ if err != nil {
426
+ panic(err)
427
+ }
428
+ r, s, err := Sign(rand.Reader, privKey, zeroHash)
429
+ if err != nil {
430
+ panic(err)
431
+ }
432
+
433
+ r = r.Sub(r, curve.Params().N)
434
+ if Verify(&privKey.PublicKey, zeroHash, r, s) {
435
+ t.Errorf("Verify with r=r-n succeeded: %T", curve)
436
+ }
437
+ }
438
+
439
+ func TestRFC6979(t *testing.T) {
440
+ t.Run("P-224", func(t *testing.T) {
441
+ testRFC6979(t, elliptic.P224(),
442
+ "F220266E1105BFE3083E03EC7A3A654651F45E37167E88600BF257C1",
443
+ "00CF08DA5AD719E42707FA431292DEA11244D64FC51610D94B130D6C",
444
+ "EEAB6F3DEBE455E3DBF85416F7030CBD94F34F2D6F232C69F3C1385A",
445
+ "sample",
446
+ "61AA3DA010E8E8406C656BC477A7A7189895E7E840CDFE8FF42307BA",
447
+ "BC814050DAB5D23770879494F9E0A680DC1AF7161991BDE692B10101")
448
+ testRFC6979(t, elliptic.P224(),
449
+ "F220266E1105BFE3083E03EC7A3A654651F45E37167E88600BF257C1",
450
+ "00CF08DA5AD719E42707FA431292DEA11244D64FC51610D94B130D6C",
451
+ "EEAB6F3DEBE455E3DBF85416F7030CBD94F34F2D6F232C69F3C1385A",
452
+ "test",
453
+ "AD04DDE87B84747A243A631EA47A1BA6D1FAA059149AD2440DE6FBA6",
454
+ "178D49B1AE90E3D8B629BE3DB5683915F4E8C99FDF6E666CF37ADCFD")
455
+ })
456
+ t.Run("P-256", func(t *testing.T) {
457
+ // This vector was bruteforced to find a message that causes the
458
+ // generation of k to loop. It was checked against
459
+ // github.com/codahale/rfc6979 (https://go.dev/play/p/FK5-fmKf7eK),
460
+ // OpenSSL 3.2.0 (https://github.com/openssl/openssl/pull/23130),
461
+ // and python-ecdsa:
462
+ //
463
+ // ecdsa.keys.SigningKey.from_secret_exponent(
464
+ // 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721,
465
+ // ecdsa.curves.curve_by_name("NIST256p"), hashlib.sha256).sign_deterministic(
466
+ // b"wv[vnX", hashlib.sha256, lambda r, s, order: print(hex(r), hex(s)))
467
+ //
468
+ testRFC6979(t, elliptic.P256(),
469
+ "C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721",
470
+ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6",
471
+ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299",
472
+ "wv[vnX",
473
+ "EFD9073B652E76DA1B5A019C0E4A2E3FA529B035A6ABB91EF67F0ED7A1F21234",
474
+ "3DB4706C9D9F4A4FE13BB5E08EF0FAB53A57DBAB2061C83A35FA411C68D2BA33")
475
+
476
+ // The remaining vectors are from RFC 6979.
477
+ testRFC6979(t, elliptic.P256(),
478
+ "C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721",
479
+ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6",
480
+ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299",
481
+ "sample",
482
+ "EFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716",
483
+ "F7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8")
484
+ testRFC6979(t, elliptic.P256(),
485
+ "C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721",
486
+ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6",
487
+ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299",
488
+ "test",
489
+ "F1ABB023518351CD71D881567B1EA663ED3EFCF6C5132B354F28D3B0B7D38367",
490
+ "019F4113742A2B14BD25926B49C649155F267E60D3814B4C0CC84250E46F0083")
491
+ })
492
+ t.Run("P-384", func(t *testing.T) {
493
+ testRFC6979(t, elliptic.P384(),
494
+ "6B9D3DAD2E1B8C1C05B19875B6659F4DE23C3B667BF297BA9AA47740787137D896D5724E4C70A825F872C9EA60D2EDF5",
495
+ "EC3A4E415B4E19A4568618029F427FA5DA9A8BC4AE92E02E06AAE5286B300C64DEF8F0EA9055866064A254515480BC13",
496
+ "8015D9B72D7D57244EA8EF9AC0C621896708A59367F9DFB9F54CA84B3F1C9DB1288B231C3AE0D4FE7344FD2533264720",
497
+ "sample",
498
+ "21B13D1E013C7FA1392D03C5F99AF8B30C570C6F98D4EA8E354B63A21D3DAA33BDE1E888E63355D92FA2B3C36D8FB2CD",
499
+ "F3AA443FB107745BF4BD77CB3891674632068A10CA67E3D45DB2266FA7D1FEEBEFDC63ECCD1AC42EC0CB8668A4FA0AB0")
500
+ testRFC6979(t, elliptic.P384(),
501
+ "6B9D3DAD2E1B8C1C05B19875B6659F4DE23C3B667BF297BA9AA47740787137D896D5724E4C70A825F872C9EA60D2EDF5",
502
+ "EC3A4E415B4E19A4568618029F427FA5DA9A8BC4AE92E02E06AAE5286B300C64DEF8F0EA9055866064A254515480BC13",
503
+ "8015D9B72D7D57244EA8EF9AC0C621896708A59367F9DFB9F54CA84B3F1C9DB1288B231C3AE0D4FE7344FD2533264720",
504
+ "test",
505
+ "6D6DEFAC9AB64DABAFE36C6BF510352A4CC27001263638E5B16D9BB51D451559F918EEDAF2293BE5B475CC8F0188636B",
506
+ "2D46F3BECBCC523D5F1A1256BF0C9B024D879BA9E838144C8BA6BAEB4B53B47D51AB373F9845C0514EEFB14024787265")
507
+ })
508
+ t.Run("P-521", func(t *testing.T) {
509
+ testRFC6979(t, elliptic.P521(),
510
+ "0FAD06DAA62BA3B25D2FB40133DA757205DE67F5BB0018FEE8C86E1B68C7E75CAA896EB32F1F47C70855836A6D16FCC1466F6D8FBEC67DB89EC0C08B0E996B83538",
511
+ "1894550D0785932E00EAA23B694F213F8C3121F86DC97A04E5A7167DB4E5BCD371123D46E45DB6B5D5370A7F20FB633155D38FFA16D2BD761DCAC474B9A2F5023A4",
512
+ "0493101C962CD4D2FDDF782285E64584139C2F91B47F87FF82354D6630F746A28A0DB25741B5B34A828008B22ACC23F924FAAFBD4D33F81EA66956DFEAA2BFDFCF5",
513
+ "sample",
514
+ "1511BB4D675114FE266FC4372B87682BAECC01D3CC62CF2303C92B3526012659D16876E25C7C1E57648F23B73564D67F61C6F14D527D54972810421E7D87589E1A7",
515
+ "04A171143A83163D6DF460AAF61522695F207A58B95C0644D87E52AA1A347916E4F7A72930B1BC06DBE22CE3F58264AFD23704CBB63B29B931F7DE6C9D949A7ECFC")
516
+ testRFC6979(t, elliptic.P521(),
517
+ "0FAD06DAA62BA3B25D2FB40133DA757205DE67F5BB0018FEE8C86E1B68C7E75CAA896EB32F1F47C70855836A6D16FCC1466F6D8FBEC67DB89EC0C08B0E996B83538",
518
+ "1894550D0785932E00EAA23B694F213F8C3121F86DC97A04E5A7167DB4E5BCD371123D46E45DB6B5D5370A7F20FB633155D38FFA16D2BD761DCAC474B9A2F5023A4",
519
+ "0493101C962CD4D2FDDF782285E64584139C2F91B47F87FF82354D6630F746A28A0DB25741B5B34A828008B22ACC23F924FAAFBD4D33F81EA66956DFEAA2BFDFCF5",
520
+ "test",
521
+ "00E871C4A14F993C6C7369501900C4BC1E9C7B0B4BA44E04868B30B41D8071042EB28C4C250411D0CE08CD197E4188EA4876F279F90B3D8D74A3C76E6F1E4656AA8",
522
+ "0CD52DBAA33B063C3A6CD8058A1FB0A46A4754B034FCC644766CA14DA8CA5CA9FDE00E88C1AD60CCBA759025299079D7A427EC3CC5B619BFBC828E7769BCD694E86")
523
+ })
524
+ }
525
+
526
+ func testRFC6979(t *testing.T, curve elliptic.Curve, D, X, Y, msg, r, s string) {
527
+ priv := &PrivateKey{
528
+ D: fromHex(D),
529
+ PublicKey: PublicKey{
530
+ Curve: curve,
531
+ X: fromHex(X),
532
+ Y: fromHex(Y),
533
+ },
534
+ }
535
+ h := sha256.Sum256([]byte(msg))
536
+ sig, err := priv.Sign(nil, h[:], crypto.SHA256)
537
+ if err != nil {
538
+ t.Fatal(err)
539
+ }
540
+ expected, err := encodeSignature(fromHex(r).Bytes(), fromHex(s).Bytes())
541
+ if err != nil {
542
+ t.Fatal(err)
543
+ }
544
+ if !bytes.Equal(sig, expected) {
545
+ t.Errorf("signature mismatch:\n got: %x\nwant: %x", sig, expected)
546
+ }
547
+ }
548
+
549
+ func TestParseAndBytesRoundTrip(t *testing.T) {
550
+ testAllCurves(t, testParseAndBytesRoundTrip)
551
+ }
552
+
553
+ func testParseAndBytesRoundTrip(t *testing.T, curve elliptic.Curve) {
554
+ if strings.HasSuffix(t.Name(), "/Generic") {
555
+ t.Skip("these methods don't support generic curves")
556
+ }
557
+ priv, _ := GenerateKey(curve, rand.Reader)
558
+
559
+ b, err := priv.PublicKey.Bytes()
560
+ if err != nil {
561
+ t.Fatalf("failed to serialize private key's public key: %v", err)
562
+ }
563
+ if b[0] != 4 {
564
+ t.Fatalf("public key bytes doesn't start with 0x04 (uncompressed format)")
565
+ }
566
+ p, err := ParseUncompressedPublicKey(curve, b)
567
+ if err != nil {
568
+ t.Fatalf("failed to parse private key's public key: %v", err)
569
+ }
570
+ if !priv.PublicKey.Equal(p) {
571
+ t.Errorf("parsed private key's public key doesn't match original")
572
+ }
573
+
574
+ bk, err := priv.Bytes()
575
+ if err != nil {
576
+ t.Fatalf("failed to serialize private key: %v", err)
577
+ }
578
+ k, err := ParseRawPrivateKey(curve, bk)
579
+ if err != nil {
580
+ t.Fatalf("failed to parse private key: %v", err)
581
+ }
582
+ if !priv.Equal(k) {
583
+ t.Errorf("parsed private key doesn't match original")
584
+ }
585
+
586
+ if curve != elliptic.P224() {
587
+ privECDH, err := priv.ECDH()
588
+ if err != nil {
589
+ t.Fatalf("failed to convert private key to ECDH: %v", err)
590
+ }
591
+
592
+ pp, err := privECDH.Curve().NewPublicKey(b)
593
+ if err != nil {
594
+ t.Fatalf("failed to parse with ECDH: %v", err)
595
+ }
596
+ if !privECDH.PublicKey().Equal(pp) {
597
+ t.Errorf("parsed ECDH public key doesn't match original")
598
+ }
599
+ if !bytes.Equal(b, pp.Bytes()) {
600
+ t.Errorf("encoded ECDH public key doesn't match Bytes")
601
+ }
602
+
603
+ kk, err := privECDH.Curve().NewPrivateKey(bk)
604
+ if err != nil {
605
+ t.Fatalf("failed to parse with ECDH: %v", err)
606
+ }
607
+ if !privECDH.Equal(kk) {
608
+ t.Errorf("parsed ECDH private key doesn't match original")
609
+ }
610
+ if !bytes.Equal(bk, kk.Bytes()) {
611
+ t.Errorf("encoded ECDH private key doesn't match Bytes")
612
+ }
613
+ }
614
+ }
615
+
616
+ func TestInvalidPublicKeys(t *testing.T) {
617
+ testAllCurves(t, testInvalidPublicKeys)
618
+ }
619
+
620
+ func testInvalidPublicKeys(t *testing.T, curve elliptic.Curve) {
621
+ t.Run("Infinity", func(t *testing.T) {
622
+ k := &PublicKey{Curve: curve, X: big.NewInt(0), Y: big.NewInt(0)}
623
+ if _, err := k.Bytes(); err == nil {
624
+ t.Errorf("PublicKey.Bytes accepted infinity")
625
+ }
626
+
627
+ b := []byte{0}
628
+ if _, err := ParseUncompressedPublicKey(curve, b); err == nil {
629
+ t.Errorf("ParseUncompressedPublicKey accepted infinity")
630
+ }
631
+ b = make([]byte, 1+2*(curve.Params().BitSize+7)/8)
632
+ b[0] = 4
633
+ if _, err := ParseUncompressedPublicKey(curve, b); err == nil {
634
+ t.Errorf("ParseUncompressedPublicKey accepted infinity")
635
+ }
636
+ })
637
+ t.Run("NotOnCurve", func(t *testing.T) {
638
+ k, _ := GenerateKey(curve, rand.Reader)
639
+ k.X = k.X.Add(k.X, big.NewInt(1))
640
+ if _, err := k.Bytes(); err == nil {
641
+ t.Errorf("PublicKey.Bytes accepted not on curve")
642
+ }
643
+
644
+ b := make([]byte, 1+2*(curve.Params().BitSize+7)/8)
645
+ b[0] = 4
646
+ k.X.FillBytes(b[1 : 1+len(b)/2])
647
+ k.Y.FillBytes(b[1+len(b)/2:])
648
+ if _, err := ParseUncompressedPublicKey(curve, b); err == nil {
649
+ t.Errorf("ParseUncompressedPublicKey accepted not on curve")
650
+ }
651
+ })
652
+ t.Run("Compressed", func(t *testing.T) {
653
+ k, _ := GenerateKey(curve, rand.Reader)
654
+ b := elliptic.MarshalCompressed(curve, k.X, k.Y)
655
+ if _, err := ParseUncompressedPublicKey(curve, b); err == nil {
656
+ t.Errorf("ParseUncompressedPublicKey accepted compressed key")
657
+ }
658
+ })
659
+ }
660
+
661
+ func TestInvalidPrivateKeys(t *testing.T) {
662
+ testAllCurves(t, testInvalidPrivateKeys)
663
+ }
664
+
665
+ func testInvalidPrivateKeys(t *testing.T, curve elliptic.Curve) {
666
+ t.Run("Zero", func(t *testing.T) {
667
+ k := &PrivateKey{PublicKey{curve, big.NewInt(0), big.NewInt(0)}, big.NewInt(0)}
668
+ if _, err := k.Bytes(); err == nil {
669
+ t.Errorf("PrivateKey.Bytes accepted zero key")
670
+ }
671
+
672
+ b := make([]byte, (curve.Params().BitSize+7)/8)
673
+ if _, err := ParseRawPrivateKey(curve, b); err == nil {
674
+ t.Errorf("ParseRawPrivateKey accepted zero key")
675
+ }
676
+ })
677
+ t.Run("Overflow", func(t *testing.T) {
678
+ d := new(big.Int).Add(curve.Params().N, big.NewInt(5))
679
+ x, y := curve.ScalarBaseMult(d.Bytes())
680
+ k := &PrivateKey{PublicKey{curve, x, y}, d}
681
+ if _, err := k.Bytes(); err == nil {
682
+ t.Errorf("PrivateKey.Bytes accepted overflow key")
683
+ }
684
+
685
+ b := make([]byte, (curve.Params().BitSize+7)/8)
686
+ k.D.FillBytes(b)
687
+ if _, err := ParseRawPrivateKey(curve, b); err == nil {
688
+ t.Errorf("ParseRawPrivateKey accepted overflow key")
689
+ }
690
+ })
691
+ t.Run("Length", func(t *testing.T) {
692
+ b := []byte{1, 2, 3}
693
+ if _, err := ParseRawPrivateKey(curve, b); err == nil {
694
+ t.Errorf("ParseRawPrivateKey accepted short key")
695
+ }
696
+
697
+ b = make([]byte, (curve.Params().BitSize+7)/8)
698
+ b = append(b, []byte{1, 2, 3}...)
699
+ if _, err := ParseRawPrivateKey(curve, b); err == nil {
700
+ t.Errorf("ParseRawPrivateKey accepted long key")
701
+ }
702
+ })
703
+ }
704
+
705
+ func benchmarkAllCurves(b *testing.B, f func(*testing.B, elliptic.Curve)) {
706
+ tests := []struct {
707
+ name string
708
+ curve elliptic.Curve
709
+ }{
710
+ {"P256", elliptic.P256()},
711
+ {"P384", elliptic.P384()},
712
+ {"P521", elliptic.P521()},
713
+ }
714
+ for _, test := range tests {
715
+ curve := test.curve
716
+ b.Run(test.name, func(b *testing.B) {
717
+ f(b, curve)
718
+ })
719
+ }
720
+ }
721
+
722
+ func BenchmarkSign(b *testing.B) {
723
+ benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) {
724
+ r := bufio.NewReaderSize(rand.Reader, 1<<15)
725
+ priv, err := GenerateKey(curve, r)
726
+ if err != nil {
727
+ b.Fatal(err)
728
+ }
729
+ hashed := []byte("testing")
730
+
731
+ b.ReportAllocs()
732
+ b.ResetTimer()
733
+ for i := 0; i < b.N; i++ {
734
+ sig, err := SignASN1(r, priv, hashed)
735
+ if err != nil {
736
+ b.Fatal(err)
737
+ }
738
+ // Prevent the compiler from optimizing out the operation.
739
+ hashed[0] = sig[0]
740
+ }
741
+ })
742
+ }
743
+
744
+ func BenchmarkVerify(b *testing.B) {
745
+ benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) {
746
+ r := bufio.NewReaderSize(rand.Reader, 1<<15)
747
+ priv, err := GenerateKey(curve, r)
748
+ if err != nil {
749
+ b.Fatal(err)
750
+ }
751
+ hashed := []byte("testing")
752
+ sig, err := SignASN1(r, priv, hashed)
753
+ if err != nil {
754
+ b.Fatal(err)
755
+ }
756
+
757
+ b.ReportAllocs()
758
+ b.ResetTimer()
759
+ for i := 0; i < b.N; i++ {
760
+ if !VerifyASN1(&priv.PublicKey, hashed, sig) {
761
+ b.Fatal("verify failed")
762
+ }
763
+ }
764
+ })
765
+ }
766
+
767
+ func BenchmarkGenerateKey(b *testing.B) {
768
+ benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) {
769
+ r := bufio.NewReaderSize(rand.Reader, 1<<15)
770
+ b.ReportAllocs()
771
+ b.ResetTimer()
772
+ for i := 0; i < b.N; i++ {
773
+ if _, err := GenerateKey(curve, r); err != nil {
774
+ b.Fatal(err)
775
+ }
776
+ }
777
+ })
778
+ }
go/src/crypto/ecdsa/equal_test.go ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 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 ecdsa_test
6
+
7
+ import (
8
+ "crypto"
9
+ "crypto/ecdsa"
10
+ "crypto/elliptic"
11
+ "crypto/rand"
12
+ "crypto/x509"
13
+ "testing"
14
+ )
15
+
16
+ func testEqual(t *testing.T, c elliptic.Curve) {
17
+ private, _ := ecdsa.GenerateKey(c, rand.Reader)
18
+ public := &private.PublicKey
19
+
20
+ if !public.Equal(public) {
21
+ t.Errorf("public key is not equal to itself: %v", public)
22
+ }
23
+ if !public.Equal(crypto.Signer(private).Public().(*ecdsa.PublicKey)) {
24
+ t.Errorf("private.Public() is not Equal to public: %q", public)
25
+ }
26
+ if !private.Equal(private) {
27
+ t.Errorf("private key is not equal to itself: %v", private)
28
+ }
29
+
30
+ enc, err := x509.MarshalPKCS8PrivateKey(private)
31
+ if err != nil {
32
+ t.Fatal(err)
33
+ }
34
+ decoded, err := x509.ParsePKCS8PrivateKey(enc)
35
+ if err != nil {
36
+ t.Fatal(err)
37
+ }
38
+ if !public.Equal(decoded.(crypto.Signer).Public()) {
39
+ t.Errorf("public key is not equal to itself after decoding: %v", public)
40
+ }
41
+ if !private.Equal(decoded) {
42
+ t.Errorf("private key is not equal to itself after decoding: %v", private)
43
+ }
44
+
45
+ other, _ := ecdsa.GenerateKey(c, rand.Reader)
46
+ if public.Equal(other.Public()) {
47
+ t.Errorf("different public keys are Equal")
48
+ }
49
+ if private.Equal(other) {
50
+ t.Errorf("different private keys are Equal")
51
+ }
52
+
53
+ // Ensure that keys with the same coordinates but on different curves
54
+ // aren't considered Equal.
55
+ differentCurve := &ecdsa.PublicKey{}
56
+ *differentCurve = *public // make a copy of the public key
57
+ if differentCurve.Curve == elliptic.P256() {
58
+ differentCurve.Curve = elliptic.P224()
59
+ } else {
60
+ differentCurve.Curve = elliptic.P256()
61
+ }
62
+ if public.Equal(differentCurve) {
63
+ t.Errorf("public keys with different curves are Equal")
64
+ }
65
+ }
66
+
67
+ func TestEqual(t *testing.T) {
68
+ t.Run("P224", func(t *testing.T) { testEqual(t, elliptic.P224()) })
69
+ if testing.Short() {
70
+ return
71
+ }
72
+ t.Run("P256", func(t *testing.T) { testEqual(t, elliptic.P256()) })
73
+ t.Run("P384", func(t *testing.T) { testEqual(t, elliptic.P384()) })
74
+ t.Run("P521", func(t *testing.T) { testEqual(t, elliptic.P521()) })
75
+ }
go/src/crypto/ecdsa/example_test.go ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 ecdsa_test
6
+
7
+ import (
8
+ "crypto/ecdsa"
9
+ "crypto/elliptic"
10
+ "crypto/rand"
11
+ "crypto/sha256"
12
+ "fmt"
13
+ )
14
+
15
+ func Example() {
16
+ privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
17
+ if err != nil {
18
+ panic(err)
19
+ }
20
+
21
+ msg := "hello, world"
22
+ hash := sha256.Sum256([]byte(msg))
23
+
24
+ sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:])
25
+ if err != nil {
26
+ panic(err)
27
+ }
28
+ fmt.Printf("signature: %x\n", sig)
29
+
30
+ valid := ecdsa.VerifyASN1(&privateKey.PublicKey, hash[:], sig)
31
+ fmt.Println("signature verified:", valid)
32
+ }
go/src/crypto/ecdsa/notboring.go ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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
+ //go:build !boringcrypto
6
+
7
+ package ecdsa
8
+
9
+ import "crypto/internal/boring"
10
+
11
+ func boringPublicKey(*PublicKey) (*boring.PublicKeyECDSA, error) {
12
+ panic("boringcrypto: not available")
13
+ }
14
+ func boringPrivateKey(*PrivateKey) (*boring.PrivateKeyECDSA, error) {
15
+ panic("boringcrypto: not available")
16
+ }
go/src/crypto/ed25519/ed25519.go ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 ed25519 implements the Ed25519 signature algorithm. See
6
+ // https://ed25519.cr.yp.to/.
7
+ //
8
+ // These functions are also compatible with the “Ed25519” function defined in
9
+ // RFC 8032. However, unlike RFC 8032's formulation, this package's private key
10
+ // representation includes a public key suffix to make multiple signing
11
+ // operations with the same key more efficient. This package refers to the RFC
12
+ // 8032 private key as the “seed”.
13
+ //
14
+ // Operations involving private keys are implemented using constant-time
15
+ // algorithms.
16
+ package ed25519
17
+
18
+ import (
19
+ "crypto"
20
+ "crypto/internal/fips140/ed25519"
21
+ "crypto/internal/fips140cache"
22
+ "crypto/internal/fips140only"
23
+ "crypto/internal/rand"
24
+ cryptorand "crypto/rand"
25
+ "crypto/subtle"
26
+ "errors"
27
+ "internal/godebug"
28
+ "io"
29
+ "strconv"
30
+ )
31
+
32
+ const (
33
+ // PublicKeySize is the size, in bytes, of public keys as used in this package.
34
+ PublicKeySize = 32
35
+ // PrivateKeySize is the size, in bytes, of private keys as used in this package.
36
+ PrivateKeySize = 64
37
+ // SignatureSize is the size, in bytes, of signatures generated and verified by this package.
38
+ SignatureSize = 64
39
+ // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
40
+ SeedSize = 32
41
+ )
42
+
43
+ // PublicKey is the type of Ed25519 public keys.
44
+ type PublicKey []byte
45
+
46
+ // Any methods implemented on PublicKey might need to also be implemented on
47
+ // PrivateKey, as the latter embeds the former and will expose its methods.
48
+
49
+ // Equal reports whether pub and x have the same value.
50
+ func (pub PublicKey) Equal(x crypto.PublicKey) bool {
51
+ xx, ok := x.(PublicKey)
52
+ if !ok {
53
+ return false
54
+ }
55
+ return subtle.ConstantTimeCompare(pub, xx) == 1
56
+ }
57
+
58
+ // PrivateKey is the type of Ed25519 private keys. It implements [crypto.Signer].
59
+ type PrivateKey []byte
60
+
61
+ // Public returns the [PublicKey] corresponding to priv.
62
+ func (priv PrivateKey) Public() crypto.PublicKey {
63
+ publicKey := make([]byte, PublicKeySize)
64
+ copy(publicKey, priv[32:])
65
+ return PublicKey(publicKey)
66
+ }
67
+
68
+ // Equal reports whether priv and x have the same value.
69
+ func (priv PrivateKey) Equal(x crypto.PrivateKey) bool {
70
+ xx, ok := x.(PrivateKey)
71
+ if !ok {
72
+ return false
73
+ }
74
+ return subtle.ConstantTimeCompare(priv, xx) == 1
75
+ }
76
+
77
+ // Seed returns the private key seed corresponding to priv. It is provided for
78
+ // interoperability with RFC 8032. RFC 8032's private keys correspond to seeds
79
+ // in this package.
80
+ func (priv PrivateKey) Seed() []byte {
81
+ return append(make([]byte, 0, SeedSize), priv[:SeedSize]...)
82
+ }
83
+
84
+ // privateKeyCache uses a pointer to the first byte of underlying storage as a
85
+ // key, because [PrivateKey] is a slice header passed around by value.
86
+ var privateKeyCache fips140cache.Cache[byte, ed25519.PrivateKey]
87
+
88
+ // Sign signs the given message with priv. rand is ignored and can be nil.
89
+ //
90
+ // If opts.HashFunc() is [crypto.SHA512], the pre-hashed variant Ed25519ph is used
91
+ // and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must
92
+ // be [crypto.Hash](0) and the message must not be hashed, as Ed25519 performs two
93
+ // passes over messages to be signed.
94
+ //
95
+ // A value of type [Options] can be used as opts, or crypto.Hash(0) or
96
+ // crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.
97
+ func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
98
+ k, err := privateKeyCache.Get(&priv[0], func() (*ed25519.PrivateKey, error) {
99
+ return ed25519.NewPrivateKey(priv)
100
+ }, func(k *ed25519.PrivateKey) bool {
101
+ return subtle.ConstantTimeCompare(priv, k.Bytes()) == 1
102
+ })
103
+ if err != nil {
104
+ return nil, err
105
+ }
106
+ hash := opts.HashFunc()
107
+ context := ""
108
+ if opts, ok := opts.(*Options); ok {
109
+ context = opts.Context
110
+ }
111
+ switch {
112
+ case hash == crypto.SHA512: // Ed25519ph
113
+ return ed25519.SignPH(k, message, context)
114
+ case hash == crypto.Hash(0) && context != "": // Ed25519ctx
115
+ if fips140only.Enforced() {
116
+ return nil, errors.New("crypto/ed25519: use of Ed25519ctx is not allowed in FIPS 140-only mode")
117
+ }
118
+ return ed25519.SignCtx(k, message, context)
119
+ case hash == crypto.Hash(0): // Ed25519
120
+ return ed25519.Sign(k, message), nil
121
+ default:
122
+ return nil, errors.New("ed25519: expected opts.HashFunc() zero (unhashed message, for standard Ed25519) or SHA-512 (for Ed25519ph)")
123
+ }
124
+ }
125
+
126
+ // Options can be used with [PrivateKey.Sign] or [VerifyWithOptions]
127
+ // to select Ed25519 variants.
128
+ type Options struct {
129
+ // Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
130
+ Hash crypto.Hash
131
+
132
+ // Context, if not empty, selects Ed25519ctx or provides the context string
133
+ // for Ed25519ph. It can be at most 255 bytes in length.
134
+ Context string
135
+ }
136
+
137
+ // HashFunc returns o.Hash.
138
+ func (o *Options) HashFunc() crypto.Hash { return o.Hash }
139
+
140
+ var cryptocustomrand = godebug.New("cryptocustomrand")
141
+
142
+ // GenerateKey generates a public/private key pair using entropy from random.
143
+ //
144
+ // If random is nil, a secure random source is used. (Before Go 1.26, a custom
145
+ // [crypto/rand.Reader] was used if set by the application. That behavior can be
146
+ // restored with GODEBUG=cryptocustomrand=1. This setting will be removed in a
147
+ // future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].)
148
+ //
149
+ // The output of this function is deterministic, and equivalent to reading
150
+ // [SeedSize] bytes from random, and passing them to [NewKeyFromSeed].
151
+ func GenerateKey(random io.Reader) (PublicKey, PrivateKey, error) {
152
+ if random == nil {
153
+ if cryptocustomrand.Value() == "1" {
154
+ random = cryptorand.Reader
155
+ if !rand.IsDefaultReader(random) {
156
+ cryptocustomrand.IncNonDefault()
157
+ }
158
+ } else {
159
+ random = rand.Reader
160
+ }
161
+ }
162
+
163
+ seed := make([]byte, SeedSize)
164
+ if _, err := io.ReadFull(random, seed); err != nil {
165
+ return nil, nil, err
166
+ }
167
+
168
+ privateKey := NewKeyFromSeed(seed)
169
+ publicKey := privateKey.Public().(PublicKey)
170
+ return publicKey, privateKey, nil
171
+ }
172
+
173
+ // NewKeyFromSeed calculates a private key from a seed. It will panic if
174
+ // len(seed) is not [SeedSize]. This function is provided for interoperability
175
+ // with RFC 8032. RFC 8032's private keys correspond to seeds in this
176
+ // package.
177
+ func NewKeyFromSeed(seed []byte) PrivateKey {
178
+ // Outline the function body so that the returned key can be stack-allocated.
179
+ privateKey := make([]byte, PrivateKeySize)
180
+ newKeyFromSeed(privateKey, seed)
181
+ return privateKey
182
+ }
183
+
184
+ func newKeyFromSeed(privateKey, seed []byte) {
185
+ k, err := ed25519.NewPrivateKeyFromSeed(seed)
186
+ if err != nil {
187
+ // NewPrivateKeyFromSeed only returns an error if the seed length is incorrect.
188
+ panic("ed25519: bad seed length: " + strconv.Itoa(len(seed)))
189
+ }
190
+ copy(privateKey, k.Bytes())
191
+ }
192
+
193
+ // Sign signs the message with privateKey and returns a signature. It will
194
+ // panic if len(privateKey) is not [PrivateKeySize].
195
+ func Sign(privateKey PrivateKey, message []byte) []byte {
196
+ // Outline the function body so that the returned signature can be
197
+ // stack-allocated.
198
+ signature := make([]byte, SignatureSize)
199
+ sign(signature, privateKey, message)
200
+ return signature
201
+ }
202
+
203
+ func sign(signature []byte, privateKey PrivateKey, message []byte) {
204
+ k, err := privateKeyCache.Get(&privateKey[0], func() (*ed25519.PrivateKey, error) {
205
+ return ed25519.NewPrivateKey(privateKey)
206
+ }, func(k *ed25519.PrivateKey) bool {
207
+ return subtle.ConstantTimeCompare(privateKey, k.Bytes()) == 1
208
+ })
209
+ if err != nil {
210
+ panic("ed25519: bad private key: " + err.Error())
211
+ }
212
+ sig := ed25519.Sign(k, message)
213
+ copy(signature, sig)
214
+ }
215
+
216
+ // Verify reports whether sig is a valid signature of message by publicKey. It
217
+ // will panic if len(publicKey) is not [PublicKeySize].
218
+ //
219
+ // The inputs are not considered confidential, and may leak through timing side
220
+ // channels, or if an attacker has control of part of the inputs.
221
+ func Verify(publicKey PublicKey, message, sig []byte) bool {
222
+ return VerifyWithOptions(publicKey, message, sig, &Options{Hash: crypto.Hash(0)}) == nil
223
+ }
224
+
225
+ // VerifyWithOptions reports whether sig is a valid signature of message by
226
+ // publicKey. A valid signature is indicated by returning a nil error. It will
227
+ // panic if len(publicKey) is not [PublicKeySize].
228
+ //
229
+ // If opts.Hash is [crypto.SHA512], the pre-hashed variant Ed25519ph is used and
230
+ // message is expected to be a SHA-512 hash, otherwise opts.Hash must be
231
+ // [crypto.Hash](0) and the message must not be hashed, as Ed25519 performs two
232
+ // passes over messages to be signed.
233
+ //
234
+ // The inputs are not considered confidential, and may leak through timing side
235
+ // channels, or if an attacker has control of part of the inputs.
236
+ func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error {
237
+ if l := len(publicKey); l != PublicKeySize {
238
+ panic("ed25519: bad public key length: " + strconv.Itoa(l))
239
+ }
240
+ k, err := ed25519.NewPublicKey(publicKey)
241
+ if err != nil {
242
+ return err
243
+ }
244
+ switch {
245
+ case opts.Hash == crypto.SHA512: // Ed25519ph
246
+ return ed25519.VerifyPH(k, message, sig, opts.Context)
247
+ case opts.Hash == crypto.Hash(0) && opts.Context != "": // Ed25519ctx
248
+ if fips140only.Enforced() {
249
+ return errors.New("crypto/ed25519: use of Ed25519ctx is not allowed in FIPS 140-only mode")
250
+ }
251
+ return ed25519.VerifyCtx(k, message, sig, opts.Context)
252
+ case opts.Hash == crypto.Hash(0): // Ed25519
253
+ return ed25519.Verify(k, message, sig)
254
+ default:
255
+ return errors.New("ed25519: expected opts.Hash zero (unhashed message, for standard Ed25519) or SHA-512 (for Ed25519ph)")
256
+ }
257
+ }
go/src/crypto/ed25519/ed25519_test.go ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 ed25519
6
+
7
+ import (
8
+ "bufio"
9
+ "bytes"
10
+ "compress/gzip"
11
+ "crypto"
12
+ "crypto/internal/cryptotest"
13
+ "crypto/rand"
14
+ "crypto/sha512"
15
+ "encoding/hex"
16
+ "log"
17
+ "os"
18
+ "strings"
19
+ "testing"
20
+ )
21
+
22
+ func Example_ed25519ctx() {
23
+ pub, priv, err := GenerateKey(nil)
24
+ if err != nil {
25
+ log.Fatal(err)
26
+ }
27
+
28
+ msg := []byte("The quick brown fox jumps over the lazy dog")
29
+
30
+ sig, err := priv.Sign(nil, msg, &Options{
31
+ Context: "Example_ed25519ctx",
32
+ })
33
+ if err != nil {
34
+ log.Fatal(err)
35
+ }
36
+
37
+ if err := VerifyWithOptions(pub, msg, sig, &Options{
38
+ Context: "Example_ed25519ctx",
39
+ }); err != nil {
40
+ log.Fatal("invalid signature")
41
+ }
42
+ }
43
+
44
+ func TestGenerateKey(t *testing.T) {
45
+ // nil is like using crypto/rand.Reader.
46
+ public, private, err := GenerateKey(nil)
47
+ if err != nil {
48
+ t.Fatal(err)
49
+ }
50
+
51
+ if len(public) != PublicKeySize {
52
+ t.Errorf("public key has the wrong size: %d", len(public))
53
+ }
54
+ if len(private) != PrivateKeySize {
55
+ t.Errorf("private key has the wrong size: %d", len(private))
56
+ }
57
+ if !bytes.Equal(private.Public().(PublicKey), public) {
58
+ t.Errorf("public key doesn't match private key")
59
+ }
60
+ fromSeed := NewKeyFromSeed(private.Seed())
61
+ if !bytes.Equal(private, fromSeed) {
62
+ t.Errorf("recreating key pair from seed gave different private key")
63
+ }
64
+
65
+ _, k2, err := GenerateKey(nil)
66
+ if err != nil {
67
+ t.Fatal(err)
68
+ }
69
+ if bytes.Equal(private, k2) {
70
+ t.Errorf("GenerateKey returned the same private key twice")
71
+ }
72
+
73
+ _, k3, err := GenerateKey(rand.Reader)
74
+ if err != nil {
75
+ t.Fatal(err)
76
+ }
77
+ if bytes.Equal(private, k3) {
78
+ t.Errorf("GenerateKey returned the same private key twice")
79
+ }
80
+
81
+ // GenerateKey is documented to be the same as NewKeyFromSeed.
82
+ seed := make([]byte, SeedSize)
83
+ rand.Read(seed)
84
+ _, k4, err := GenerateKey(bytes.NewReader(seed))
85
+ if err != nil {
86
+ t.Fatal(err)
87
+ }
88
+ k4n := NewKeyFromSeed(seed)
89
+ if !bytes.Equal(k4, k4n) {
90
+ t.Errorf("GenerateKey with seed gave different private key")
91
+ }
92
+ }
93
+
94
+ type zeroReader struct{}
95
+
96
+ func (zeroReader) Read(buf []byte) (int, error) {
97
+ clear(buf)
98
+ return len(buf), nil
99
+ }
100
+
101
+ func TestSignVerify(t *testing.T) {
102
+ var zero zeroReader
103
+ public, private, _ := GenerateKey(zero)
104
+
105
+ message := []byte("test message")
106
+ sig := Sign(private, message)
107
+ if !Verify(public, message, sig) {
108
+ t.Errorf("valid signature rejected")
109
+ }
110
+
111
+ wrongMessage := []byte("wrong message")
112
+ if Verify(public, wrongMessage, sig) {
113
+ t.Errorf("signature of different message accepted")
114
+ }
115
+ }
116
+
117
+ func TestSignVerifyHashed(t *testing.T) {
118
+ // From RFC 8032, Section 7.3
119
+ key, _ := hex.DecodeString("833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf")
120
+ expectedSig, _ := hex.DecodeString("98a70222f0b8121aa9d30f813d683f809e462b469c7ff87639499bb94e6dae4131f85042463c2a355a2003d062adf5aaa10b8c61e636062aaad11c2a26083406")
121
+ message, _ := hex.DecodeString("616263")
122
+
123
+ private := PrivateKey(key)
124
+ public := private.Public().(PublicKey)
125
+ hash := sha512.Sum512(message)
126
+ sig, err := private.Sign(nil, hash[:], crypto.SHA512)
127
+ if err != nil {
128
+ t.Fatal(err)
129
+ }
130
+ if !bytes.Equal(sig, expectedSig) {
131
+ t.Error("signature doesn't match test vector")
132
+ }
133
+ sig, err = private.Sign(nil, hash[:], &Options{Hash: crypto.SHA512})
134
+ if err != nil {
135
+ t.Fatal(err)
136
+ }
137
+ if !bytes.Equal(sig, expectedSig) {
138
+ t.Error("signature doesn't match test vector")
139
+ }
140
+ if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}); err != nil {
141
+ t.Errorf("valid signature rejected: %v", err)
142
+ }
143
+
144
+ if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA256}); err == nil {
145
+ t.Errorf("expected error for wrong hash")
146
+ }
147
+
148
+ wrongHash := sha512.Sum512([]byte("wrong message"))
149
+ if VerifyWithOptions(public, wrongHash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
150
+ t.Errorf("signature of different message accepted")
151
+ }
152
+
153
+ sig[0] ^= 0xff
154
+ if VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
155
+ t.Errorf("invalid signature accepted")
156
+ }
157
+ sig[0] ^= 0xff
158
+ sig[SignatureSize-1] ^= 0xff
159
+ if VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
160
+ t.Errorf("invalid signature accepted")
161
+ }
162
+
163
+ // The RFC provides no test vectors for Ed25519ph with context, so just sign
164
+ // and verify something.
165
+ sig, err = private.Sign(nil, hash[:], &Options{Hash: crypto.SHA512, Context: "123"})
166
+ if err != nil {
167
+ t.Fatal(err)
168
+ }
169
+ if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512, Context: "123"}); err != nil {
170
+ t.Errorf("valid signature rejected: %v", err)
171
+ }
172
+ if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512, Context: "321"}); err == nil {
173
+ t.Errorf("expected error for wrong context")
174
+ }
175
+ if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA256, Context: "123"}); err == nil {
176
+ t.Errorf("expected error for wrong hash")
177
+ }
178
+ }
179
+
180
+ func TestSignVerifyContext(t *testing.T) {
181
+ // From RFC 8032, Section 7.2
182
+ key, _ := hex.DecodeString("0305334e381af78f141cb666f6199f57bc3495335a256a95bd2a55bf546663f6dfc9425e4f968f7f0c29f0259cf5f9aed6851c2bb4ad8bfb860cfee0ab248292")
183
+ expectedSig, _ := hex.DecodeString("55a4cc2f70a54e04288c5f4cd1e45a7bb520b36292911876cada7323198dd87a8b36950b95130022907a7fb7c4e9b2d5f6cca685a587b4b21f4b888e4e7edb0d")
184
+ message, _ := hex.DecodeString("f726936d19c800494e3fdaff20b276a8")
185
+ context := "foo"
186
+
187
+ private := PrivateKey(key)
188
+ public := private.Public().(PublicKey)
189
+ sig, err := private.Sign(nil, message, &Options{Context: context})
190
+ if err != nil {
191
+ t.Fatal(err)
192
+ }
193
+ if !bytes.Equal(sig, expectedSig) {
194
+ t.Error("signature doesn't match test vector")
195
+ }
196
+ if err := VerifyWithOptions(public, message, sig, &Options{Context: context}); err != nil {
197
+ t.Errorf("valid signature rejected: %v", err)
198
+ }
199
+
200
+ if VerifyWithOptions(public, []byte("bar"), sig, &Options{Context: context}) == nil {
201
+ t.Errorf("signature of different message accepted")
202
+ }
203
+ if VerifyWithOptions(public, message, sig, &Options{Context: "bar"}) == nil {
204
+ t.Errorf("signature with different context accepted")
205
+ }
206
+
207
+ sig[0] ^= 0xff
208
+ if VerifyWithOptions(public, message, sig, &Options{Context: context}) == nil {
209
+ t.Errorf("invalid signature accepted")
210
+ }
211
+ sig[0] ^= 0xff
212
+ sig[SignatureSize-1] ^= 0xff
213
+ if VerifyWithOptions(public, message, sig, &Options{Context: context}) == nil {
214
+ t.Errorf("invalid signature accepted")
215
+ }
216
+ }
217
+
218
+ func TestCryptoSigner(t *testing.T) {
219
+ var zero zeroReader
220
+ public, private, _ := GenerateKey(zero)
221
+
222
+ signer := crypto.Signer(private)
223
+
224
+ publicInterface := signer.Public()
225
+ public2, ok := publicInterface.(PublicKey)
226
+ if !ok {
227
+ t.Fatalf("expected PublicKey from Public() but got %T", publicInterface)
228
+ }
229
+
230
+ if !bytes.Equal(public, public2) {
231
+ t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2)
232
+ }
233
+
234
+ message := []byte("message")
235
+ var noHash crypto.Hash
236
+ signature, err := signer.Sign(zero, message, noHash)
237
+ if err != nil {
238
+ t.Fatalf("error from Sign(): %s", err)
239
+ }
240
+
241
+ signature2, err := signer.Sign(zero, message, &Options{Hash: noHash})
242
+ if err != nil {
243
+ t.Fatalf("error from Sign(): %s", err)
244
+ }
245
+ if !bytes.Equal(signature, signature2) {
246
+ t.Errorf("signatures keys do not match")
247
+ }
248
+
249
+ if !Verify(public, message, signature) {
250
+ t.Errorf("Verify failed on signature from Sign()")
251
+ }
252
+ }
253
+
254
+ func TestEqual(t *testing.T) {
255
+ public, private, _ := GenerateKey(rand.Reader)
256
+
257
+ if !public.Equal(public) {
258
+ t.Errorf("public key is not equal to itself: %q", public)
259
+ }
260
+ if !public.Equal(crypto.Signer(private).Public()) {
261
+ t.Errorf("private.Public() is not Equal to public: %q", public)
262
+ }
263
+ if !private.Equal(private) {
264
+ t.Errorf("private key is not equal to itself: %q", private)
265
+ }
266
+
267
+ otherPub, otherPriv, _ := GenerateKey(rand.Reader)
268
+ if public.Equal(otherPub) {
269
+ t.Errorf("different public keys are Equal")
270
+ }
271
+ if private.Equal(otherPriv) {
272
+ t.Errorf("different private keys are Equal")
273
+ }
274
+ }
275
+
276
+ func TestGolden(t *testing.T) {
277
+ // sign.input.gz is a selection of test cases from
278
+ // https://ed25519.cr.yp.to/python/sign.input
279
+ testDataZ, err := os.Open("testdata/sign.input.gz")
280
+ if err != nil {
281
+ t.Fatal(err)
282
+ }
283
+ defer testDataZ.Close()
284
+ testData, err := gzip.NewReader(testDataZ)
285
+ if err != nil {
286
+ t.Fatal(err)
287
+ }
288
+ defer testData.Close()
289
+
290
+ scanner := bufio.NewScanner(testData)
291
+ lineNo := 0
292
+
293
+ for scanner.Scan() {
294
+ lineNo++
295
+
296
+ line := scanner.Text()
297
+ parts := strings.Split(line, ":")
298
+ if len(parts) != 5 {
299
+ t.Fatalf("bad number of parts on line %d", lineNo)
300
+ }
301
+
302
+ privBytes, _ := hex.DecodeString(parts[0])
303
+ pubKey, _ := hex.DecodeString(parts[1])
304
+ msg, _ := hex.DecodeString(parts[2])
305
+ sig, _ := hex.DecodeString(parts[3])
306
+ // The signatures in the test vectors also include the message
307
+ // at the end, but we just want R and S.
308
+ sig = sig[:SignatureSize]
309
+
310
+ if l := len(pubKey); l != PublicKeySize {
311
+ t.Fatalf("bad public key length on line %d: got %d bytes", lineNo, l)
312
+ }
313
+
314
+ var priv [PrivateKeySize]byte
315
+ copy(priv[:], privBytes)
316
+ copy(priv[32:], pubKey)
317
+
318
+ sig2 := Sign(priv[:], msg)
319
+ if !bytes.Equal(sig, sig2[:]) {
320
+ t.Errorf("different signature result on line %d: %x vs %x", lineNo, sig, sig2)
321
+ }
322
+
323
+ if !Verify(pubKey, msg, sig2) {
324
+ t.Errorf("signature failed to verify on line %d", lineNo)
325
+ }
326
+
327
+ priv2 := NewKeyFromSeed(priv[:32])
328
+ if !bytes.Equal(priv[:], priv2) {
329
+ t.Errorf("recreating key pair gave different private key on line %d: %x vs %x", lineNo, priv[:], priv2)
330
+ }
331
+
332
+ if pubKey2 := priv2.Public().(PublicKey); !bytes.Equal(pubKey, pubKey2) {
333
+ t.Errorf("recreating key pair gave different public key on line %d: %x vs %x", lineNo, pubKey, pubKey2)
334
+ }
335
+
336
+ if seed := priv2.Seed(); !bytes.Equal(priv[:32], seed) {
337
+ t.Errorf("recreating key pair gave different seed on line %d: %x vs %x", lineNo, priv[:32], seed)
338
+ }
339
+ }
340
+
341
+ if err := scanner.Err(); err != nil {
342
+ t.Fatalf("error reading test data: %s", err)
343
+ }
344
+ }
345
+
346
+ func TestMalleability(t *testing.T) {
347
+ // https://tools.ietf.org/html/rfc8032#section-5.1.7 adds an additional test
348
+ // that s be in [0, order). This prevents someone from adding a multiple of
349
+ // order to s and obtaining a second valid signature for the same message.
350
+ msg := []byte{0x54, 0x65, 0x73, 0x74}
351
+ sig := []byte{
352
+ 0x7c, 0x38, 0xe0, 0x26, 0xf2, 0x9e, 0x14, 0xaa, 0xbd, 0x05, 0x9a,
353
+ 0x0f, 0x2d, 0xb8, 0xb0, 0xcd, 0x78, 0x30, 0x40, 0x60, 0x9a, 0x8b,
354
+ 0xe6, 0x84, 0xdb, 0x12, 0xf8, 0x2a, 0x27, 0x77, 0x4a, 0xb0, 0x67,
355
+ 0x65, 0x4b, 0xce, 0x38, 0x32, 0xc2, 0xd7, 0x6f, 0x8f, 0x6f, 0x5d,
356
+ 0xaf, 0xc0, 0x8d, 0x93, 0x39, 0xd4, 0xee, 0xf6, 0x76, 0x57, 0x33,
357
+ 0x36, 0xa5, 0xc5, 0x1e, 0xb6, 0xf9, 0x46, 0xb3, 0x1d,
358
+ }
359
+ publicKey := []byte{
360
+ 0x7d, 0x4d, 0x0e, 0x7f, 0x61, 0x53, 0xa6, 0x9b, 0x62, 0x42, 0xb5,
361
+ 0x22, 0xab, 0xbe, 0xe6, 0x85, 0xfd, 0xa4, 0x42, 0x0f, 0x88, 0x34,
362
+ 0xb1, 0x08, 0xc3, 0xbd, 0xae, 0x36, 0x9e, 0xf5, 0x49, 0xfa,
363
+ }
364
+
365
+ if Verify(publicKey, msg, sig) {
366
+ t.Fatal("non-canonical signature accepted")
367
+ }
368
+ }
369
+
370
+ func TestAllocations(t *testing.T) {
371
+ cryptotest.SkipTestAllocations(t)
372
+ seed := make([]byte, SeedSize)
373
+ priv := NewKeyFromSeed(seed)
374
+ if allocs := testing.AllocsPerRun(100, func() {
375
+ message := []byte("Hello, world!")
376
+ pub := priv.Public().(PublicKey)
377
+ signature := Sign(priv, message)
378
+ if !Verify(pub, message, signature) {
379
+ t.Fatal("signature didn't verify")
380
+ }
381
+ }); allocs > 0 {
382
+ t.Errorf("expected zero allocations, got %0.1f", allocs)
383
+ }
384
+ }
385
+
386
+ func BenchmarkKeyGeneration(b *testing.B) {
387
+ var zero zeroReader
388
+ for i := 0; i < b.N; i++ {
389
+ if _, _, err := GenerateKey(zero); err != nil {
390
+ b.Fatal(err)
391
+ }
392
+ }
393
+ }
394
+
395
+ func BenchmarkNewKeyFromSeed(b *testing.B) {
396
+ seed := make([]byte, SeedSize)
397
+ for i := 0; i < b.N; i++ {
398
+ _ = NewKeyFromSeed(seed)
399
+ }
400
+ }
401
+
402
+ func BenchmarkSigning(b *testing.B) {
403
+ var zero zeroReader
404
+ _, priv, err := GenerateKey(zero)
405
+ if err != nil {
406
+ b.Fatal(err)
407
+ }
408
+ message := []byte("Hello, world!")
409
+ b.ResetTimer()
410
+ for i := 0; i < b.N; i++ {
411
+ Sign(priv, message)
412
+ }
413
+ }
414
+
415
+ func BenchmarkVerification(b *testing.B) {
416
+ var zero zeroReader
417
+ pub, priv, err := GenerateKey(zero)
418
+ if err != nil {
419
+ b.Fatal(err)
420
+ }
421
+ message := []byte("Hello, world!")
422
+ signature := Sign(priv, message)
423
+ b.ResetTimer()
424
+ for i := 0; i < b.N; i++ {
425
+ Verify(pub, message, signature)
426
+ }
427
+ }
go/src/crypto/ed25519/ed25519vectors_test.go ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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 ed25519_test
6
+
7
+ import (
8
+ "crypto/ed25519"
9
+ "crypto/internal/cryptotest"
10
+ "encoding/hex"
11
+ "encoding/json"
12
+ "os"
13
+ "path/filepath"
14
+ "testing"
15
+ )
16
+
17
+ // TestEd25519Vectors runs a very large set of test vectors that exercise all
18
+ // combinations of low-order points, low-order components, and non-canonical
19
+ // encodings. These vectors lock in unspecified and spec-divergent behaviors in
20
+ // edge cases that are not security relevant in most contexts, but that can
21
+ // cause issues in consensus applications if changed.
22
+ //
23
+ // Our behavior matches the "classic" unwritten verification rules of the
24
+ // "ref10" reference implementation.
25
+ //
26
+ // Note that although we test for these edge cases, they are not covered by the
27
+ // Go 1 Compatibility Promise. Applications that need stable verification rules
28
+ // should use github.com/hdevalence/ed25519consensus.
29
+ //
30
+ // See https://hdevalence.ca/blog/2020-10-04-its-25519am for more details.
31
+ func TestEd25519Vectors(t *testing.T) {
32
+ jsonVectors := downloadEd25519Vectors(t)
33
+ var vectors []struct {
34
+ A, R, S, M string
35
+ Flags []string
36
+ }
37
+ if err := json.Unmarshal(jsonVectors, &vectors); err != nil {
38
+ t.Fatal(err)
39
+ }
40
+ for i, v := range vectors {
41
+ expectedToVerify := true
42
+ for _, f := range v.Flags {
43
+ switch f {
44
+ // We use the simplified verification formula that doesn't multiply
45
+ // by the cofactor, so any low order residue will cause the
46
+ // signature not to verify.
47
+ //
48
+ // This is allowed, but not required, by RFC 8032.
49
+ case "LowOrderResidue":
50
+ expectedToVerify = false
51
+ // Our point decoding allows non-canonical encodings (in violation
52
+ // of RFC 8032) but R is not decoded: instead, R is recomputed and
53
+ // compared bytewise against the canonical encoding.
54
+ case "NonCanonicalR":
55
+ expectedToVerify = false
56
+ }
57
+ }
58
+
59
+ publicKey := decodeHex(t, v.A)
60
+ signature := append(decodeHex(t, v.R), decodeHex(t, v.S)...)
61
+ message := []byte(v.M)
62
+
63
+ didVerify := ed25519.Verify(publicKey, message, signature)
64
+ if didVerify && !expectedToVerify {
65
+ t.Errorf("#%d: vector with flags %s unexpectedly verified", i, v.Flags)
66
+ }
67
+ if !didVerify && expectedToVerify {
68
+ t.Errorf("#%d: vector with flags %s unexpectedly rejected", i, v.Flags)
69
+ }
70
+ }
71
+ }
72
+
73
+ func downloadEd25519Vectors(t *testing.T) []byte {
74
+ // Download the JSON test file from the GOPROXY with `go mod download`,
75
+ // pinning the version so test and module caching works as expected.
76
+ path := "filippo.io/mostly-harmless/ed25519vectors"
77
+ version := "v0.0.0-20210322192420-30a2d7243a94"
78
+ dir := cryptotest.FetchModule(t, path, version)
79
+
80
+ jsonVectors, err := os.ReadFile(filepath.Join(dir, "ed25519vectors.json"))
81
+ if err != nil {
82
+ t.Fatalf("failed to read ed25519vectors.json: %v", err)
83
+ }
84
+ return jsonVectors
85
+ }
86
+
87
+ func decodeHex(t *testing.T, s string) []byte {
88
+ t.Helper()
89
+ b, err := hex.DecodeString(s)
90
+ if err != nil {
91
+ t.Errorf("invalid hex: %v", err)
92
+ }
93
+ return b
94
+ }
go/src/crypto/elliptic/elliptic.go ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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 elliptic implements the standard NIST P-224, P-256, P-384, and P-521
6
+ // elliptic curves over prime fields.
7
+ //
8
+ // Direct use of this package is deprecated, beyond the [P224], [P256], [P384],
9
+ // and [P521] values necessary to use [crypto/ecdsa]. Most other uses
10
+ // should migrate to the more efficient and safer [crypto/ecdh], or to
11
+ // third-party modules for lower-level functionality.
12
+ package elliptic
13
+
14
+ import (
15
+ "io"
16
+ "math/big"
17
+ "sync"
18
+ )
19
+
20
+ // A Curve represents a short-form Weierstrass curve with a=-3.
21
+ //
22
+ // The behavior of Add, Double, and ScalarMult when the input is not a point on
23
+ // the curve is undefined.
24
+ //
25
+ // Note that the conventional point at infinity (0, 0) is not considered on the
26
+ // curve, although it can be returned by Add, Double, ScalarMult, or
27
+ // ScalarBaseMult (but not the [Unmarshal] or [UnmarshalCompressed] functions).
28
+ //
29
+ // Using Curve implementations besides those returned by [P224], [P256], [P384],
30
+ // and [P521] is deprecated.
31
+ type Curve interface {
32
+ // Params returns the parameters for the curve.
33
+ Params() *CurveParams
34
+
35
+ // IsOnCurve reports whether the given (x,y) lies on the curve.
36
+ //
37
+ // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
38
+ // package. The NewPublicKey methods of NIST curves in crypto/ecdh accept
39
+ // the same encoding as the Unmarshal function, and perform on-curve checks.
40
+ IsOnCurve(x, y *big.Int) bool
41
+
42
+ // Add returns the sum of (x1,y1) and (x2,y2).
43
+ //
44
+ // Deprecated: this is a low-level unsafe API.
45
+ Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
46
+
47
+ // Double returns 2*(x,y).
48
+ //
49
+ // Deprecated: this is a low-level unsafe API.
50
+ Double(x1, y1 *big.Int) (x, y *big.Int)
51
+
52
+ // ScalarMult returns k*(x,y) where k is an integer in big-endian form.
53
+ //
54
+ // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
55
+ // package. Most uses of ScalarMult can be replaced by a call to the ECDH
56
+ // methods of NIST curves in crypto/ecdh.
57
+ ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
58
+
59
+ // ScalarBaseMult returns k*G, where G is the base point of the group
60
+ // and k is an integer in big-endian form.
61
+ //
62
+ // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
63
+ // package. Most uses of ScalarBaseMult can be replaced by a call to the
64
+ // PrivateKey.PublicKey method in crypto/ecdh.
65
+ ScalarBaseMult(k []byte) (x, y *big.Int)
66
+ }
67
+
68
+ var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
69
+
70
+ // GenerateKey returns a public/private key pair. The private key is
71
+ // generated using the given reader, which must return random data.
72
+ //
73
+ // Deprecated: for ECDH, use the GenerateKey methods of the [crypto/ecdh] package;
74
+ // for ECDSA, use the GenerateKey function of the crypto/ecdsa package.
75
+ func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error) {
76
+ N := curve.Params().N
77
+ bitSize := N.BitLen()
78
+ byteLen := (bitSize + 7) / 8
79
+ priv = make([]byte, byteLen)
80
+
81
+ for x == nil {
82
+ _, err = io.ReadFull(rand, priv)
83
+ if err != nil {
84
+ return
85
+ }
86
+ // We have to mask off any excess bits in the case that the size of the
87
+ // underlying field is not a whole number of bytes.
88
+ priv[0] &= mask[bitSize%8]
89
+ // This is because, in tests, rand will return all zeros and we don't
90
+ // want to get the point at infinity and loop forever.
91
+ priv[1] ^= 0x42
92
+
93
+ // If the scalar is out of range, sample another random number.
94
+ if new(big.Int).SetBytes(priv).Cmp(N) >= 0 {
95
+ continue
96
+ }
97
+
98
+ x, y = curve.ScalarBaseMult(priv)
99
+ }
100
+ return
101
+ }
102
+
103
+ // Marshal converts a point on the curve into the uncompressed form specified in
104
+ // SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is
105
+ // the conventional point at infinity), the behavior is undefined.
106
+ //
107
+ // Deprecated: for ECDH, use the crypto/ecdh package. This function returns an
108
+ // encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.
109
+ func Marshal(curve Curve, x, y *big.Int) []byte {
110
+ panicIfNotOnCurve(curve, x, y)
111
+
112
+ byteLen := (curve.Params().BitSize + 7) / 8
113
+
114
+ ret := make([]byte, 1+2*byteLen)
115
+ ret[0] = 4 // uncompressed point
116
+
117
+ x.FillBytes(ret[1 : 1+byteLen])
118
+ y.FillBytes(ret[1+byteLen : 1+2*byteLen])
119
+
120
+ return ret
121
+ }
122
+
123
+ // MarshalCompressed converts a point on the curve into the compressed form
124
+ // specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the
125
+ // curve (or is the conventional point at infinity), the behavior is undefined.
126
+ func MarshalCompressed(curve Curve, x, y *big.Int) []byte {
127
+ panicIfNotOnCurve(curve, x, y)
128
+ byteLen := (curve.Params().BitSize + 7) / 8
129
+ compressed := make([]byte, 1+byteLen)
130
+ compressed[0] = byte(y.Bit(0)) | 2
131
+ x.FillBytes(compressed[1:])
132
+ return compressed
133
+ }
134
+
135
+ // unmarshaler is implemented by curves with their own constant-time Unmarshal.
136
+ //
137
+ // There isn't an equivalent interface for Marshal/MarshalCompressed because
138
+ // that doesn't involve any mathematical operations, only FillBytes and Bit.
139
+ type unmarshaler interface {
140
+ Unmarshal([]byte) (x, y *big.Int)
141
+ UnmarshalCompressed([]byte) (x, y *big.Int)
142
+ }
143
+
144
+ // Assert that the known curves implement unmarshaler.
145
+ var _ = []unmarshaler{p224, p256, p384, p521}
146
+
147
+ // Unmarshal converts a point, serialized by [Marshal], into an x, y pair. It is
148
+ // an error if the point is not in uncompressed form, is not on the curve, or is
149
+ // the point at infinity. On error, x = nil.
150
+ //
151
+ // Deprecated: for ECDH, use the crypto/ecdh package. This function accepts an
152
+ // encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.
153
+ func Unmarshal(curve Curve, data []byte) (x, y *big.Int) {
154
+ if c, ok := curve.(unmarshaler); ok {
155
+ return c.Unmarshal(data)
156
+ }
157
+
158
+ byteLen := (curve.Params().BitSize + 7) / 8
159
+ if len(data) != 1+2*byteLen {
160
+ return nil, nil
161
+ }
162
+ if data[0] != 4 { // uncompressed form
163
+ return nil, nil
164
+ }
165
+ p := curve.Params().P
166
+ x = new(big.Int).SetBytes(data[1 : 1+byteLen])
167
+ y = new(big.Int).SetBytes(data[1+byteLen:])
168
+ if x.Cmp(p) >= 0 || y.Cmp(p) >= 0 {
169
+ return nil, nil
170
+ }
171
+ if !curve.IsOnCurve(x, y) {
172
+ return nil, nil
173
+ }
174
+ return
175
+ }
176
+
177
+ // UnmarshalCompressed converts a point, serialized by [MarshalCompressed], into
178
+ // an x, y pair. It is an error if the point is not in compressed form, is not
179
+ // on the curve, or is the point at infinity. On error, x = nil.
180
+ func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int) {
181
+ if c, ok := curve.(unmarshaler); ok {
182
+ return c.UnmarshalCompressed(data)
183
+ }
184
+
185
+ byteLen := (curve.Params().BitSize + 7) / 8
186
+ if len(data) != 1+byteLen {
187
+ return nil, nil
188
+ }
189
+ if data[0] != 2 && data[0] != 3 { // compressed form
190
+ return nil, nil
191
+ }
192
+ p := curve.Params().P
193
+ x = new(big.Int).SetBytes(data[1:])
194
+ if x.Cmp(p) >= 0 {
195
+ return nil, nil
196
+ }
197
+ // y² = x³ - 3x + b
198
+ y = curve.Params().polynomial(x)
199
+ y = y.ModSqrt(y, p)
200
+ if y == nil {
201
+ return nil, nil
202
+ }
203
+ if byte(y.Bit(0)) != data[0]&1 {
204
+ y.Neg(y).Mod(y, p)
205
+ }
206
+ if !curve.IsOnCurve(x, y) {
207
+ return nil, nil
208
+ }
209
+ return
210
+ }
211
+
212
+ func panicIfNotOnCurve(curve Curve, x, y *big.Int) {
213
+ // (0, 0) is the point at infinity by convention. It's ok to operate on it,
214
+ // although IsOnCurve is documented to return false for it. See Issue 37294.
215
+ if x.Sign() == 0 && y.Sign() == 0 {
216
+ return
217
+ }
218
+
219
+ if !curve.IsOnCurve(x, y) {
220
+ panic("crypto/elliptic: attempted operation on invalid point")
221
+ }
222
+ }
223
+
224
+ var initonce sync.Once
225
+
226
+ func initAll() {
227
+ initP224()
228
+ initP256()
229
+ initP384()
230
+ initP521()
231
+ }
232
+
233
+ // P224 returns a [Curve] which implements NIST P-224 (FIPS 186-3, section D.2.2),
234
+ // also known as secp224r1. The CurveParams.Name of this [Curve] is "P-224".
235
+ //
236
+ // Multiple invocations of this function will return the same value, so it can
237
+ // be used for equality checks and switch statements.
238
+ //
239
+ // The cryptographic operations are implemented using constant-time algorithms.
240
+ func P224() Curve {
241
+ initonce.Do(initAll)
242
+ return p224
243
+ }
244
+
245
+ // P256 returns a [Curve] which implements NIST P-256 (FIPS 186-3, section D.2.3),
246
+ // also known as secp256r1 or prime256v1. The CurveParams.Name of this [Curve] is
247
+ // "P-256".
248
+ //
249
+ // Multiple invocations of this function will return the same value, so it can
250
+ // be used for equality checks and switch statements.
251
+ //
252
+ // The cryptographic operations are implemented using constant-time algorithms.
253
+ func P256() Curve {
254
+ initonce.Do(initAll)
255
+ return p256
256
+ }
257
+
258
+ // P384 returns a [Curve] which implements NIST P-384 (FIPS 186-3, section D.2.4),
259
+ // also known as secp384r1. The CurveParams.Name of this [Curve] is "P-384".
260
+ //
261
+ // Multiple invocations of this function will return the same value, so it can
262
+ // be used for equality checks and switch statements.
263
+ //
264
+ // The cryptographic operations are implemented using constant-time algorithms.
265
+ func P384() Curve {
266
+ initonce.Do(initAll)
267
+ return p384
268
+ }
269
+
270
+ // P521 returns a [Curve] which implements NIST P-521 (FIPS 186-3, section D.2.5),
271
+ // also known as secp521r1. The CurveParams.Name of this [Curve] is "P-521".
272
+ //
273
+ // Multiple invocations of this function will return the same value, so it can
274
+ // be used for equality checks and switch statements.
275
+ //
276
+ // The cryptographic operations are implemented using constant-time algorithms.
277
+ func P521() Curve {
278
+ initonce.Do(initAll)
279
+ return p521
280
+ }
go/src/crypto/elliptic/elliptic_test.go ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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 elliptic
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto/rand"
10
+ "encoding/hex"
11
+ "math/big"
12
+ "testing"
13
+ )
14
+
15
+ // genericParamsForCurve returns the dereferenced CurveParams for
16
+ // the specified curve. This is used to avoid the logic for
17
+ // upgrading a curve to its specific implementation, forcing
18
+ // usage of the generic implementation.
19
+ func genericParamsForCurve(c Curve) *CurveParams {
20
+ d := *(c.Params())
21
+ return &d
22
+ }
23
+
24
+ func testAllCurves(t *testing.T, f func(*testing.T, Curve)) {
25
+ tests := []struct {
26
+ name string
27
+ curve Curve
28
+ }{
29
+ {"P256", P256()},
30
+ {"P256/Params", genericParamsForCurve(P256())},
31
+ {"P224", P224()},
32
+ {"P224/Params", genericParamsForCurve(P224())},
33
+ {"P384", P384()},
34
+ {"P384/Params", genericParamsForCurve(P384())},
35
+ {"P521", P521()},
36
+ {"P521/Params", genericParamsForCurve(P521())},
37
+ }
38
+ if testing.Short() {
39
+ tests = tests[:1]
40
+ }
41
+ for _, test := range tests {
42
+ curve := test.curve
43
+ t.Run(test.name, func(t *testing.T) {
44
+ t.Parallel()
45
+ f(t, curve)
46
+ })
47
+ }
48
+ }
49
+
50
+ func TestOnCurve(t *testing.T) {
51
+ t.Parallel()
52
+ testAllCurves(t, func(t *testing.T, curve Curve) {
53
+ if !curve.IsOnCurve(curve.Params().Gx, curve.Params().Gy) {
54
+ t.Error("basepoint is not on the curve")
55
+ }
56
+ })
57
+ }
58
+
59
+ func TestOffCurve(t *testing.T) {
60
+ t.Parallel()
61
+ testAllCurves(t, func(t *testing.T, curve Curve) {
62
+ x, y := new(big.Int).SetInt64(1), new(big.Int).SetInt64(1)
63
+ if curve.IsOnCurve(x, y) {
64
+ t.Errorf("point off curve is claimed to be on the curve")
65
+ }
66
+
67
+ byteLen := (curve.Params().BitSize + 7) / 8
68
+ b := make([]byte, 1+2*byteLen)
69
+ b[0] = 4 // uncompressed point
70
+ x.FillBytes(b[1 : 1+byteLen])
71
+ y.FillBytes(b[1+byteLen : 1+2*byteLen])
72
+
73
+ x1, y1 := Unmarshal(curve, b)
74
+ if x1 != nil || y1 != nil {
75
+ t.Errorf("unmarshaling a point not on the curve succeeded")
76
+ }
77
+ })
78
+ }
79
+
80
+ func TestInfinity(t *testing.T) {
81
+ t.Parallel()
82
+ testAllCurves(t, testInfinity)
83
+ }
84
+
85
+ func isInfinity(x, y *big.Int) bool {
86
+ return x.Sign() == 0 && y.Sign() == 0
87
+ }
88
+
89
+ func testInfinity(t *testing.T, curve Curve) {
90
+ x0, y0 := new(big.Int), new(big.Int)
91
+ xG, yG := curve.Params().Gx, curve.Params().Gy
92
+
93
+ if !isInfinity(curve.ScalarMult(xG, yG, curve.Params().N.Bytes())) {
94
+ t.Errorf("x^q != ∞")
95
+ }
96
+ if !isInfinity(curve.ScalarMult(xG, yG, []byte{0})) {
97
+ t.Errorf("x^0 != ∞")
98
+ }
99
+
100
+ if !isInfinity(curve.ScalarMult(x0, y0, []byte{1, 2, 3})) {
101
+ t.Errorf("∞^k != ∞")
102
+ }
103
+ if !isInfinity(curve.ScalarMult(x0, y0, []byte{0})) {
104
+ t.Errorf("∞^0 != ∞")
105
+ }
106
+
107
+ if !isInfinity(curve.ScalarBaseMult(curve.Params().N.Bytes())) {
108
+ t.Errorf("b^q != ∞")
109
+ }
110
+ if !isInfinity(curve.ScalarBaseMult([]byte{0})) {
111
+ t.Errorf("b^0 != ∞")
112
+ }
113
+
114
+ if !isInfinity(curve.Double(x0, y0)) {
115
+ t.Errorf("2∞ != ∞")
116
+ }
117
+ // There is no other point of order two on the NIST curves (as they have
118
+ // cofactor one), so Double can't otherwise return the point at infinity.
119
+
120
+ nMinusOne := new(big.Int).Sub(curve.Params().N, big.NewInt(1))
121
+ x, y := curve.ScalarMult(xG, yG, nMinusOne.Bytes())
122
+ x, y = curve.Add(x, y, xG, yG)
123
+ if !isInfinity(x, y) {
124
+ t.Errorf("x^(q-1) + x != ∞")
125
+ }
126
+ x, y = curve.Add(xG, yG, x0, y0)
127
+ if x.Cmp(xG) != 0 || y.Cmp(yG) != 0 {
128
+ t.Errorf("x+∞ != x")
129
+ }
130
+ x, y = curve.Add(x0, y0, xG, yG)
131
+ if x.Cmp(xG) != 0 || y.Cmp(yG) != 0 {
132
+ t.Errorf("∞+x != x")
133
+ }
134
+
135
+ if curve.IsOnCurve(x0, y0) {
136
+ t.Errorf("IsOnCurve(∞) == true")
137
+ }
138
+
139
+ if xx, yy := Unmarshal(curve, Marshal(curve, x0, y0)); xx != nil || yy != nil {
140
+ t.Errorf("Unmarshal(Marshal(∞)) did not return an error")
141
+ }
142
+ // We don't test UnmarshalCompressed(MarshalCompressed(∞)) because there are
143
+ // two valid points with x = 0.
144
+ if xx, yy := Unmarshal(curve, []byte{0x00}); xx != nil || yy != nil {
145
+ t.Errorf("Unmarshal(∞) did not return an error")
146
+ }
147
+ byteLen := (curve.Params().BitSize + 7) / 8
148
+ buf := make([]byte, byteLen*2+1)
149
+ buf[0] = 4 // Uncompressed format.
150
+ if xx, yy := Unmarshal(curve, buf); xx != nil || yy != nil {
151
+ t.Errorf("Unmarshal((0,0)) did not return an error")
152
+ }
153
+ }
154
+
155
+ func TestMarshal(t *testing.T) {
156
+ t.Parallel()
157
+ testAllCurves(t, func(t *testing.T, curve Curve) {
158
+ _, x, y, err := GenerateKey(curve, rand.Reader)
159
+ if err != nil {
160
+ t.Fatal(err)
161
+ }
162
+ serialized := Marshal(curve, x, y)
163
+ xx, yy := Unmarshal(curve, serialized)
164
+ if xx == nil {
165
+ t.Fatal("failed to unmarshal")
166
+ }
167
+ if xx.Cmp(x) != 0 || yy.Cmp(y) != 0 {
168
+ t.Fatal("unmarshal returned different values")
169
+ }
170
+ })
171
+ }
172
+
173
+ func TestUnmarshalToLargeCoordinates(t *testing.T) {
174
+ t.Parallel()
175
+ // See https://golang.org/issues/20482.
176
+ testAllCurves(t, testUnmarshalToLargeCoordinates)
177
+ }
178
+
179
+ func testUnmarshalToLargeCoordinates(t *testing.T, curve Curve) {
180
+ p := curve.Params().P
181
+ byteLen := (p.BitLen() + 7) / 8
182
+
183
+ // Set x to be greater than curve's parameter P – specifically, to P+5.
184
+ // Set y to mod_sqrt(x^3 - 3x + B)) so that (x mod P = 5 , y) is on the
185
+ // curve.
186
+ x := new(big.Int).Add(p, big.NewInt(5))
187
+ y := curve.Params().polynomial(x)
188
+ y.ModSqrt(y, p)
189
+
190
+ invalid := make([]byte, byteLen*2+1)
191
+ invalid[0] = 4 // uncompressed encoding
192
+ x.FillBytes(invalid[1 : 1+byteLen])
193
+ y.FillBytes(invalid[1+byteLen:])
194
+
195
+ if X, Y := Unmarshal(curve, invalid); X != nil || Y != nil {
196
+ t.Errorf("Unmarshal accepts invalid X coordinate")
197
+ }
198
+
199
+ if curve == p256 {
200
+ // This is a point on the curve with a small y value, small enough that
201
+ // we can add p and still be within 32 bytes.
202
+ x, _ = new(big.Int).SetString("31931927535157963707678568152204072984517581467226068221761862915403492091210", 10)
203
+ y, _ = new(big.Int).SetString("5208467867388784005506817585327037698770365050895731383201516607147", 10)
204
+ y.Add(y, p)
205
+
206
+ if p.Cmp(y) > 0 || y.BitLen() != 256 {
207
+ t.Fatal("y not within expected range")
208
+ }
209
+
210
+ // marshal
211
+ x.FillBytes(invalid[1 : 1+byteLen])
212
+ y.FillBytes(invalid[1+byteLen:])
213
+
214
+ if X, Y := Unmarshal(curve, invalid); X != nil || Y != nil {
215
+ t.Errorf("Unmarshal accepts invalid Y coordinate")
216
+ }
217
+ }
218
+ }
219
+
220
+ // TestInvalidCoordinates tests big.Int values that are not valid field elements
221
+ // (negative or bigger than P). They are expected to return false from
222
+ // IsOnCurve, all other behavior is undefined.
223
+ func TestInvalidCoordinates(t *testing.T) {
224
+ t.Parallel()
225
+ testAllCurves(t, testInvalidCoordinates)
226
+ }
227
+
228
+ func testInvalidCoordinates(t *testing.T, curve Curve) {
229
+ checkIsOnCurveFalse := func(name string, x, y *big.Int) {
230
+ if curve.IsOnCurve(x, y) {
231
+ t.Errorf("IsOnCurve(%s) unexpectedly returned true", name)
232
+ }
233
+ }
234
+
235
+ p := curve.Params().P
236
+ _, x, y, _ := GenerateKey(curve, rand.Reader)
237
+ xx, yy := new(big.Int), new(big.Int)
238
+
239
+ // Check if the sign is getting dropped.
240
+ xx.Neg(x)
241
+ checkIsOnCurveFalse("-x, y", xx, y)
242
+ yy.Neg(y)
243
+ checkIsOnCurveFalse("x, -y", x, yy)
244
+
245
+ // Check if negative values are reduced modulo P.
246
+ xx.Sub(x, p)
247
+ checkIsOnCurveFalse("x-P, y", xx, y)
248
+ yy.Sub(y, p)
249
+ checkIsOnCurveFalse("x, y-P", x, yy)
250
+
251
+ // Check if positive values are reduced modulo P.
252
+ xx.Add(x, p)
253
+ checkIsOnCurveFalse("x+P, y", xx, y)
254
+ yy.Add(y, p)
255
+ checkIsOnCurveFalse("x, y+P", x, yy)
256
+
257
+ // Check if the overflow is dropped.
258
+ xx.Add(x, new(big.Int).Lsh(big.NewInt(1), 535))
259
+ checkIsOnCurveFalse("x+2⁵³⁵, y", xx, y)
260
+ yy.Add(y, new(big.Int).Lsh(big.NewInt(1), 535))
261
+ checkIsOnCurveFalse("x, y+2⁵³⁵", x, yy)
262
+
263
+ // Check if P is treated like zero (if possible).
264
+ // y^2 = x^3 - 3x + B
265
+ // y = mod_sqrt(x^3 - 3x + B)
266
+ // y = mod_sqrt(B) if x = 0
267
+ // If there is no modsqrt, there is no point with x = 0, can't test x = P.
268
+ if yy := new(big.Int).ModSqrt(curve.Params().B, p); yy != nil {
269
+ if !curve.IsOnCurve(big.NewInt(0), yy) {
270
+ t.Fatal("(0, mod_sqrt(B)) is not on the curve?")
271
+ }
272
+ checkIsOnCurveFalse("P, y", p, yy)
273
+ }
274
+ }
275
+
276
+ func TestMarshalCompressed(t *testing.T) {
277
+ t.Parallel()
278
+ t.Run("P-256/03", func(t *testing.T) {
279
+ data, _ := hex.DecodeString("031e3987d9f9ea9d7dd7155a56a86b2009e1e0ab332f962d10d8beb6406ab1ad79")
280
+ x, _ := new(big.Int).SetString("13671033352574878777044637384712060483119675368076128232297328793087057702265", 10)
281
+ y, _ := new(big.Int).SetString("66200849279091436748794323380043701364391950689352563629885086590854940586447", 10)
282
+ testMarshalCompressed(t, P256(), x, y, data)
283
+ })
284
+ t.Run("P-256/02", func(t *testing.T) {
285
+ data, _ := hex.DecodeString("021e3987d9f9ea9d7dd7155a56a86b2009e1e0ab332f962d10d8beb6406ab1ad79")
286
+ x, _ := new(big.Int).SetString("13671033352574878777044637384712060483119675368076128232297328793087057702265", 10)
287
+ y, _ := new(big.Int).SetString("49591239931264812013903123569363872165694192725937750565648544718012157267504", 10)
288
+ testMarshalCompressed(t, P256(), x, y, data)
289
+ })
290
+
291
+ t.Run("Invalid", func(t *testing.T) {
292
+ data, _ := hex.DecodeString("02fd4bf61763b46581fd9174d623516cf3c81edd40e29ffa2777fb6cb0ae3ce535")
293
+ X, Y := UnmarshalCompressed(P256(), data)
294
+ if X != nil || Y != nil {
295
+ t.Error("expected an error for invalid encoding")
296
+ }
297
+ })
298
+
299
+ if testing.Short() {
300
+ t.Skip("skipping other curves on short test")
301
+ }
302
+
303
+ testAllCurves(t, func(t *testing.T, curve Curve) {
304
+ _, x, y, err := GenerateKey(curve, rand.Reader)
305
+ if err != nil {
306
+ t.Fatal(err)
307
+ }
308
+ testMarshalCompressed(t, curve, x, y, nil)
309
+ })
310
+
311
+ }
312
+
313
+ func testMarshalCompressed(t *testing.T, curve Curve, x, y *big.Int, want []byte) {
314
+ if !curve.IsOnCurve(x, y) {
315
+ t.Fatal("invalid test point")
316
+ }
317
+ got := MarshalCompressed(curve, x, y)
318
+ if want != nil && !bytes.Equal(got, want) {
319
+ t.Errorf("got unexpected MarshalCompressed result: got %x, want %x", got, want)
320
+ }
321
+
322
+ X, Y := UnmarshalCompressed(curve, got)
323
+ if X == nil || Y == nil {
324
+ t.Fatalf("UnmarshalCompressed failed unexpectedly")
325
+ }
326
+
327
+ if !curve.IsOnCurve(X, Y) {
328
+ t.Error("UnmarshalCompressed returned a point not on the curve")
329
+ }
330
+ if X.Cmp(x) != 0 || Y.Cmp(y) != 0 {
331
+ t.Errorf("point did not round-trip correctly: got (%v, %v), want (%v, %v)", X, Y, x, y)
332
+ }
333
+ }
334
+
335
+ func TestLargeIsOnCurve(t *testing.T) {
336
+ t.Parallel()
337
+ testAllCurves(t, func(t *testing.T, curve Curve) {
338
+ large := big.NewInt(1)
339
+ large.Lsh(large, 1000)
340
+ if curve.IsOnCurve(large, large) {
341
+ t.Errorf("(2^1000, 2^1000) is reported on the curve")
342
+ }
343
+ })
344
+ }
345
+
346
+ func benchmarkAllCurves(b *testing.B, f func(*testing.B, Curve)) {
347
+ tests := []struct {
348
+ name string
349
+ curve Curve
350
+ }{
351
+ {"P256", P256()},
352
+ {"P224", P224()},
353
+ {"P384", P384()},
354
+ {"P521", P521()},
355
+ }
356
+ for _, test := range tests {
357
+ curve := test.curve
358
+ b.Run(test.name, func(b *testing.B) {
359
+ f(b, curve)
360
+ })
361
+ }
362
+ }
363
+
364
+ func BenchmarkScalarBaseMult(b *testing.B) {
365
+ benchmarkAllCurves(b, func(b *testing.B, curve Curve) {
366
+ priv, _, _, _ := GenerateKey(curve, rand.Reader)
367
+ b.ReportAllocs()
368
+ b.ResetTimer()
369
+ for i := 0; i < b.N; i++ {
370
+ x, _ := curve.ScalarBaseMult(priv)
371
+ // Prevent the compiler from optimizing out the operation.
372
+ priv[0] ^= byte(x.Bits()[0])
373
+ }
374
+ })
375
+ }
376
+
377
+ func BenchmarkScalarMult(b *testing.B) {
378
+ benchmarkAllCurves(b, func(b *testing.B, curve Curve) {
379
+ _, x, y, _ := GenerateKey(curve, rand.Reader)
380
+ priv, _, _, _ := GenerateKey(curve, rand.Reader)
381
+ b.ReportAllocs()
382
+ b.ResetTimer()
383
+ for i := 0; i < b.N; i++ {
384
+ x, y = curve.ScalarMult(x, y, priv)
385
+ }
386
+ })
387
+ }
388
+
389
+ func BenchmarkMarshalUnmarshal(b *testing.B) {
390
+ benchmarkAllCurves(b, func(b *testing.B, curve Curve) {
391
+ _, x, y, _ := GenerateKey(curve, rand.Reader)
392
+ b.Run("Uncompressed", func(b *testing.B) {
393
+ b.ReportAllocs()
394
+ for i := 0; i < b.N; i++ {
395
+ buf := Marshal(curve, x, y)
396
+ xx, yy := Unmarshal(curve, buf)
397
+ if xx.Cmp(x) != 0 || yy.Cmp(y) != 0 {
398
+ b.Error("Unmarshal output different from Marshal input")
399
+ }
400
+ }
401
+ })
402
+ b.Run("Compressed", func(b *testing.B) {
403
+ b.ReportAllocs()
404
+ for i := 0; i < b.N; i++ {
405
+ buf := MarshalCompressed(curve, x, y)
406
+ xx, yy := UnmarshalCompressed(curve, buf)
407
+ if xx.Cmp(x) != 0 || yy.Cmp(y) != 0 {
408
+ b.Error("Unmarshal output different from Marshal input")
409
+ }
410
+ }
411
+ })
412
+ })
413
+ }
go/src/crypto/elliptic/nistec.go ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 elliptic
6
+
7
+ import (
8
+ "crypto/internal/fips140/nistec"
9
+ "errors"
10
+ "math/big"
11
+ )
12
+
13
+ var p224 = &nistCurve[*nistec.P224Point]{
14
+ newPoint: nistec.NewP224Point,
15
+ }
16
+
17
+ func initP224() {
18
+ p224.params = &CurveParams{
19
+ Name: "P-224",
20
+ BitSize: 224,
21
+ // SP 800-186, Section 3.2.1.2
22
+ P: bigFromDecimal("26959946667150639794667015087019630673557916260026308143510066298881"),
23
+ N: bigFromDecimal("26959946667150639794667015087019625940457807714424391721682722368061"),
24
+ B: bigFromHex("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4"),
25
+ Gx: bigFromHex("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"),
26
+ Gy: bigFromHex("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"),
27
+ }
28
+ }
29
+
30
+ var p256 = &nistCurve[*nistec.P256Point]{
31
+ newPoint: nistec.NewP256Point,
32
+ }
33
+
34
+ func initP256() {
35
+ p256.params = &CurveParams{
36
+ Name: "P-256",
37
+ BitSize: 256,
38
+ // SP 800-186, Section 3.2.1.3
39
+ P: bigFromDecimal("115792089210356248762697446949407573530086143415290314195533631308867097853951"),
40
+ N: bigFromDecimal("115792089210356248762697446949407573529996955224135760342422259061068512044369"),
41
+ B: bigFromHex("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
42
+ Gx: bigFromHex("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
43
+ Gy: bigFromHex("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),
44
+ }
45
+ }
46
+
47
+ var p384 = &nistCurve[*nistec.P384Point]{
48
+ newPoint: nistec.NewP384Point,
49
+ }
50
+
51
+ func initP384() {
52
+ p384.params = &CurveParams{
53
+ Name: "P-384",
54
+ BitSize: 384,
55
+ // SP 800-186, Section 3.2.1.4
56
+ P: bigFromDecimal("394020061963944792122790401001436138050797392704654" +
57
+ "46667948293404245721771496870329047266088258938001861606973112319"),
58
+ N: bigFromDecimal("394020061963944792122790401001436138050797392704654" +
59
+ "46667946905279627659399113263569398956308152294913554433653942643"),
60
+ B: bigFromHex("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088" +
61
+ "f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),
62
+ Gx: bigFromHex("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741" +
63
+ "e082542a385502f25dbf55296c3a545e3872760ab7"),
64
+ Gy: bigFromHex("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da31" +
65
+ "13b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),
66
+ }
67
+ }
68
+
69
+ var p521 = &nistCurve[*nistec.P521Point]{
70
+ newPoint: nistec.NewP521Point,
71
+ }
72
+
73
+ func initP521() {
74
+ p521.params = &CurveParams{
75
+ Name: "P-521",
76
+ BitSize: 521,
77
+ // SP 800-186, Section 3.2.1.5
78
+ P: bigFromDecimal("68647976601306097149819007990813932172694353001433" +
79
+ "0540939446345918554318339765605212255964066145455497729631139148" +
80
+ "0858037121987999716643812574028291115057151"),
81
+ N: bigFromDecimal("68647976601306097149819007990813932172694353001433" +
82
+ "0540939446345918554318339765539424505774633321719753296399637136" +
83
+ "3321113864768612440380340372808892707005449"),
84
+ B: bigFromHex("0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8" +
85
+ "b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef" +
86
+ "451fd46b503f00"),
87
+ Gx: bigFromHex("00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f8" +
88
+ "28af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf9" +
89
+ "7e7e31c2e5bd66"),
90
+ Gy: bigFromHex("011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817" +
91
+ "afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088" +
92
+ "be94769fd16650"),
93
+ }
94
+ }
95
+
96
+ // nistCurve is a Curve implementation based on a nistec Point.
97
+ //
98
+ // It's a wrapper that exposes the big.Int-based Curve interface and encodes the
99
+ // legacy idiosyncrasies it requires, such as invalid and infinity point
100
+ // handling.
101
+ //
102
+ // To interact with the nistec package, points are encoded into and decoded from
103
+ // properly formatted byte slices. All big.Int use is limited to this package.
104
+ // Encoding and decoding is 1/1000th of the runtime of a scalar multiplication,
105
+ // so the overhead is acceptable.
106
+ type nistCurve[Point nistPoint[Point]] struct {
107
+ newPoint func() Point
108
+ params *CurveParams
109
+ }
110
+
111
+ // nistPoint is a generic constraint for the nistec Point types.
112
+ type nistPoint[T any] interface {
113
+ Bytes() []byte
114
+ SetBytes([]byte) (T, error)
115
+ Add(T, T) T
116
+ Double(T) T
117
+ ScalarMult(T, []byte) (T, error)
118
+ ScalarBaseMult([]byte) (T, error)
119
+ }
120
+
121
+ func (curve *nistCurve[Point]) Params() *CurveParams {
122
+ return curve.params
123
+ }
124
+
125
+ func (curve *nistCurve[Point]) IsOnCurve(x, y *big.Int) bool {
126
+ // IsOnCurve is documented to reject (0, 0), the conventional point at
127
+ // infinity, which however is accepted by pointFromAffine.
128
+ if x.Sign() == 0 && y.Sign() == 0 {
129
+ return false
130
+ }
131
+ _, err := curve.pointFromAffine(x, y)
132
+ return err == nil
133
+ }
134
+
135
+ func (curve *nistCurve[Point]) pointFromAffine(x, y *big.Int) (p Point, err error) {
136
+ // (0, 0) is by convention the point at infinity, which can't be represented
137
+ // in affine coordinates. See Issue 37294.
138
+ if x.Sign() == 0 && y.Sign() == 0 {
139
+ return curve.newPoint(), nil
140
+ }
141
+ // Reject values that would not get correctly encoded.
142
+ if x.Sign() < 0 || y.Sign() < 0 {
143
+ return p, errors.New("negative coordinate")
144
+ }
145
+ if x.BitLen() > curve.params.BitSize || y.BitLen() > curve.params.BitSize {
146
+ return p, errors.New("overflowing coordinate")
147
+ }
148
+ // Encode the coordinates and let SetBytes reject invalid points.
149
+ byteLen := (curve.params.BitSize + 7) / 8
150
+ buf := make([]byte, 1+2*byteLen)
151
+ buf[0] = 4 // uncompressed point
152
+ x.FillBytes(buf[1 : 1+byteLen])
153
+ y.FillBytes(buf[1+byteLen : 1+2*byteLen])
154
+ return curve.newPoint().SetBytes(buf)
155
+ }
156
+
157
+ func (curve *nistCurve[Point]) pointToAffine(p Point) (x, y *big.Int) {
158
+ out := p.Bytes()
159
+ if len(out) == 1 && out[0] == 0 {
160
+ // This is the encoding of the point at infinity, which the affine
161
+ // coordinates API represents as (0, 0) by convention.
162
+ return new(big.Int), new(big.Int)
163
+ }
164
+ byteLen := (curve.params.BitSize + 7) / 8
165
+ x = new(big.Int).SetBytes(out[1 : 1+byteLen])
166
+ y = new(big.Int).SetBytes(out[1+byteLen:])
167
+ return x, y
168
+ }
169
+
170
+ func (curve *nistCurve[Point]) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
171
+ p1, err := curve.pointFromAffine(x1, y1)
172
+ if err != nil {
173
+ panic("crypto/elliptic: Add was called on an invalid point")
174
+ }
175
+ p2, err := curve.pointFromAffine(x2, y2)
176
+ if err != nil {
177
+ panic("crypto/elliptic: Add was called on an invalid point")
178
+ }
179
+ return curve.pointToAffine(p1.Add(p1, p2))
180
+ }
181
+
182
+ func (curve *nistCurve[Point]) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
183
+ p, err := curve.pointFromAffine(x1, y1)
184
+ if err != nil {
185
+ panic("crypto/elliptic: Double was called on an invalid point")
186
+ }
187
+ return curve.pointToAffine(p.Double(p))
188
+ }
189
+
190
+ // normalizeScalar brings the scalar within the byte size of the order of the
191
+ // curve, as expected by the nistec scalar multiplication functions.
192
+ func (curve *nistCurve[Point]) normalizeScalar(scalar []byte) []byte {
193
+ byteSize := (curve.params.N.BitLen() + 7) / 8
194
+ if len(scalar) == byteSize {
195
+ return scalar
196
+ }
197
+ s := new(big.Int).SetBytes(scalar)
198
+ if len(scalar) > byteSize {
199
+ s.Mod(s, curve.params.N)
200
+ }
201
+ out := make([]byte, byteSize)
202
+ return s.FillBytes(out)
203
+ }
204
+
205
+ func (curve *nistCurve[Point]) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) {
206
+ p, err := curve.pointFromAffine(Bx, By)
207
+ if err != nil {
208
+ panic("crypto/elliptic: ScalarMult was called on an invalid point")
209
+ }
210
+ scalar = curve.normalizeScalar(scalar)
211
+ p, err = p.ScalarMult(p, scalar)
212
+ if err != nil {
213
+ panic("crypto/elliptic: nistec rejected normalized scalar")
214
+ }
215
+ return curve.pointToAffine(p)
216
+ }
217
+
218
+ func (curve *nistCurve[Point]) ScalarBaseMult(scalar []byte) (*big.Int, *big.Int) {
219
+ scalar = curve.normalizeScalar(scalar)
220
+ p, err := curve.newPoint().ScalarBaseMult(scalar)
221
+ if err != nil {
222
+ panic("crypto/elliptic: nistec rejected normalized scalar")
223
+ }
224
+ return curve.pointToAffine(p)
225
+ }
226
+
227
+ func (curve *nistCurve[Point]) Unmarshal(data []byte) (x, y *big.Int) {
228
+ if len(data) == 0 || data[0] != 4 {
229
+ return nil, nil
230
+ }
231
+ // Use SetBytes to check that data encodes a valid point.
232
+ _, err := curve.newPoint().SetBytes(data)
233
+ if err != nil {
234
+ return nil, nil
235
+ }
236
+ // We don't use pointToAffine because it involves an expensive field
237
+ // inversion to convert from Jacobian to affine coordinates, which we
238
+ // already have.
239
+ byteLen := (curve.params.BitSize + 7) / 8
240
+ x = new(big.Int).SetBytes(data[1 : 1+byteLen])
241
+ y = new(big.Int).SetBytes(data[1+byteLen:])
242
+ return x, y
243
+ }
244
+
245
+ func (curve *nistCurve[Point]) UnmarshalCompressed(data []byte) (x, y *big.Int) {
246
+ if len(data) == 0 || (data[0] != 2 && data[0] != 3) {
247
+ return nil, nil
248
+ }
249
+ p, err := curve.newPoint().SetBytes(data)
250
+ if err != nil {
251
+ return nil, nil
252
+ }
253
+ return curve.pointToAffine(p)
254
+ }
255
+
256
+ func bigFromDecimal(s string) *big.Int {
257
+ b, ok := new(big.Int).SetString(s, 10)
258
+ if !ok {
259
+ panic("crypto/elliptic: internal error: invalid encoding")
260
+ }
261
+ return b
262
+ }
263
+
264
+ func bigFromHex(s string) *big.Int {
265
+ b, ok := new(big.Int).SetString(s, 16)
266
+ if !ok {
267
+ panic("crypto/elliptic: internal error: invalid encoding")
268
+ }
269
+ return b
270
+ }