-
Notifications
You must be signed in to change notification settings - Fork 86
/
symmetric_test.go
263 lines (226 loc) · 7.09 KB
/
symmetric_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright 2024 Thales Group
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package crypto11
import (
"bytes"
"crypto/cipher"
"runtime"
"testing"
"github.com/miekg/pkcs11"
"github.com/stretchr/testify/require"
)
func TestHardSymmetric(t *testing.T) {
ctx, err := ConfigureFromFile("config")
require.NoError(t, err)
defer func() {
require.NoError(t, ctx.Close())
}()
t.Run("AES128", func(t *testing.T) { testHardSymmetric(t, ctx, pkcs11.CKK_AES, 128) })
t.Run("AES192", func(t *testing.T) { testHardSymmetric(t, ctx, pkcs11.CKK_AES, 192) })
t.Run("AES256", func(t *testing.T) { testHardSymmetric(t, ctx, pkcs11.CKK_AES, 256) })
t.Run("DES3", func(t *testing.T) { testHardSymmetric(t, ctx, pkcs11.CKK_DES3, 0) })
}
func testHardSymmetric(t *testing.T, ctx *Context, keytype int, bits int) {
for _, p := range Ciphers[keytype].GenParams {
skipIfMechUnsupported(t, ctx, p.GenMech)
}
id := randomBytes()
key, err := ctx.GenerateSecretKey(id, bits, Ciphers[keytype])
require.NoError(t, err)
require.NotNil(t, key)
defer key.Delete()
var key2 *SecretKey
t.Run("Find", func(t *testing.T) {
key2, err = ctx.FindKey(id, nil)
require.NoError(t, err)
})
iv := make([]byte, key.Cipher.BlockSize)
for i := range iv {
iv[i] = 0xF0
}
t.Run("CBCClose", func(t *testing.T) {
skipIfMechUnsupported(t, key2.context, key2.Cipher.CBCMech)
enc, err := key2.NewCBCEncrypterCloser(iv)
require.NoError(t, err)
dec, err := key2.NewCBCDecrypterCloser(iv)
require.NoError(t, err)
testSymmetricMode(t, enc, dec)
enc.Close()
dec.Close()
})
t.Run("CBCNoClose", func(t *testing.T) {
skipIfMechUnsupported(t, key2.context, key2.Cipher.CBCMech)
enc, err := key2.NewCBCEncrypter(iv)
require.NoError(t, err)
dec, err := key2.NewCBCDecrypter(iv)
require.NoError(t, err)
testSymmetricMode(t, enc, dec)
// See discussion at BlockModeCloser.
runtime.GC()
})
if bits == 128 {
t.Run("GCMSoft", func(t *testing.T) {
aead, err := key2.NewGCM()
require.NoError(t, err)
testAEADMode(t, aead, 127, 129)
})
t.Run("GCMHard", func(t *testing.T) {
aead, err := key2.NewGCM()
require.NoError(t, err)
skipIfMechUnsupported(t, key2.context, pkcs11.CKM_AES_GCM)
testAEADMode(t, aead, 127, 129)
})
// TODO check that hard/soft is consistent!
}
// TODO CFB
// TODO OFB
// TODO CTR
}
func testSymmetricMode(t *testing.T, encrypt cipher.BlockMode, decrypt cipher.BlockMode) {
// The functions in cipher.Block have no error returns, so they panic if they encounter
// a problem. We catch these panics here, so the test can fail nicely
defer func() {
if cause := recover(); cause != nil {
t.Fatalf("Caught panic: %q", cause)
}
}()
input := make([]byte, 256)
middle := make([]byte, 256)
output := make([]byte, 256)
// Set a recognizable pattern in the buffers
for i := 0; i < 256; i++ {
input[i] = byte(i)
middle[i] = byte(i + 32)
output[i] = byte(i + 64)
}
// Encrypt the first 128 bytes
encrypt.CryptBlocks(middle, input[:128])
if bytes.Equal(input[:128], middle[:128]) {
t.Errorf("BlockMode.Encrypt: did not modify destination")
return
}
for i := 0; i < 128; i++ {
if input[i] != byte(i) {
t.Errorf("BlockMode.Encrypt: corrupted source")
return
}
}
for i := 128; i < 256; i++ {
if middle[i] != byte(i+32) {
t.Errorf("BlockMode.Encrypt: corrupted destination past input size")
return
}
}
// Encrypt the rest
encrypt.CryptBlocks(middle[128:], input[128:])
// Decrypt in a single go
decrypt.CryptBlocks(output, middle)
if !bytes.Equal(input, output) {
t.Errorf("BlockMode.Decrypt: plaintext wrong")
return
}
}
func testAEADMode(t *testing.T, aead cipher.AEAD, ptlen int, adlen int) {
nonce := make([]byte, aead.NonceSize())
plaintext := make([]byte, ptlen)
for i := 0; i < len(plaintext); i++ {
plaintext[i] = byte(i)
}
additionalData := make([]byte, adlen)
for i := 0; i < len(additionalData); i++ {
additionalData[i] = byte(i + 16)
}
ciphertext := aead.Seal([]byte{}, nonce, plaintext, additionalData)
/*
In some HSM configurations the IV may be generated and appended to the ciphertext + tag
If this is the case (based on the ciphertext length), the test assumes that the IV has been appended
*/
if len(ciphertext) == aead.NonceSize()+len(plaintext)+aead.Overhead() {
nonce = ciphertext[len(ciphertext)-aead.NonceSize():]
ciphertext = ciphertext[:len(ciphertext)-aead.NonceSize()]
}
decrypted, err := aead.Open([]byte{}, nonce, ciphertext, additionalData)
if err != nil {
t.Errorf("aead.Open: %s", err)
return
}
if !bytes.Equal(plaintext, decrypted) {
t.Errorf("aead.Open: mismatch")
return
}
}
func BenchmarkCBC(b *testing.B) {
ctx, err := ConfigureFromFile("config")
require.NoError(b, err)
defer func() {
require.NoError(b, ctx.Close())
}()
id := randomBytes()
key, err := ctx.GenerateSecretKey(id, 128, Ciphers[pkcs11.CKK_AES])
require.NoError(b, err)
require.NotNil(b, key)
defer key.Delete()
iv := make([]byte, 16)
plaintext := make([]byte, 65536)
ciphertext := make([]byte, 65536)
// No longer supported
//b.Run("Native", func(b *testing.B) {
// for i := 0; i < b.N; i++ {
// mode := cipher.NewCBCEncrypter(key, iv)
// mode.CryptBlocks(ciphertext, plaintext)
// }
//})
b.Run("IdiomaticClose", func(b *testing.B) {
for i := 0; i < b.N; i++ {
mode, err := key.NewCBCEncrypterCloser(iv)
if err != nil {
panic(err)
}
mode.CryptBlocks(ciphertext, plaintext)
mode.Close()
}
})
b.Run("Idiomatic", func(b *testing.B) {
for i := 0; i < b.N; i++ {
mode, err := key.NewCBCEncrypter(iv)
if err != nil {
panic(err)
}
mode.CryptBlocks(ciphertext, plaintext)
}
runtime.GC()
})
}
func TestSymmetricRequiredArgs(t *testing.T) {
ctx, err := ConfigureFromFile("config")
require.NoError(t, err)
defer func() {
require.NoError(t, ctx.Close())
}()
_, err = ctx.GenerateSecretKey(nil, 128, CipherAES)
require.Error(t, err)
val := randomBytes()
_, err = ctx.GenerateSecretKeyWithLabel(nil, val, 128, CipherAES)
require.Error(t, err)
_, err = ctx.GenerateSecretKeyWithLabel(val, nil, 128, CipherAES)
require.Error(t, err)
}
// TODO BenchmarkGCM along the same lines as above