-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpackage_test.go
120 lines (100 loc) · 2.34 KB
/
package_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
package aes12_test
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"testing"
"github.com/lucas-clemente/aes12"
)
const plaintextLen = 1000
var (
key []byte
nonce []byte
aad []byte
plaintext []byte
)
func init() {
key = make([]byte, 32)
rand.Read(key)
nonce = make([]byte, 12)
rand.Read(nonce)
aad = make([]byte, 42)
rand.Read(aad)
plaintext = make([]byte, plaintextLen)
rand.Read(plaintext)
}
func TestEncryption(t *testing.T) {
c, err := aes12.NewCipher(key)
if err != nil {
t.Fatal(err)
}
gcm, err := aes12.NewGCM(c)
if err != nil {
t.Fatal(err)
}
ciphertext := gcm.Seal(nil, nonce, plaintext, aad)
if len(ciphertext) != plaintextLen+12 {
t.Fatal("expected ciphertext to have len(plaintext)+12")
}
// Test that it matches the stdlib
stdC, err := aes.NewCipher(key)
if err != nil {
t.Fatal(err)
}
stdGcm, err := cipher.NewGCM(stdC)
if err != nil {
t.Fatal(err)
}
stdCiphertext := stdGcm.Seal(nil, nonce, plaintext, aad)
if !bytes.Equal(ciphertext, stdCiphertext[:len(stdCiphertext)-4]) {
t.Fatal("did not match stdlib's ciphertext")
}
decrypted, err := gcm.Open(nil, nonce, ciphertext, aad)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plaintext, decrypted) {
t.Fatal("decryption yielded unexpected result")
}
}
func TestInplaceEncryption(t *testing.T) {
c, err := aes12.NewCipher(key)
if err != nil {
t.Fatal(err)
}
gcm, err := aes12.NewGCM(c)
if err != nil {
t.Fatal(err)
}
buffer := make([]byte, len(plaintext), len(plaintext)+12)
copy(buffer, plaintext)
ciphertext := gcm.Seal(buffer[:0], nonce, buffer, aad)
if len(ciphertext) != plaintextLen+12 {
t.Fatal("expected ciphertext to have len(plaintext)+12")
}
buffer = buffer[:len(plaintext)+12]
if !bytes.Equal(ciphertext, buffer) {
t.Fatal("ciphertext != buffer")
}
// Test that it matches the stdlib
stdC, err := aes.NewCipher(key)
if err != nil {
t.Fatal(err)
}
stdGcm, err := cipher.NewGCM(stdC)
if err != nil {
t.Fatal(err)
}
stdCiphertext := stdGcm.Seal(nil, nonce, plaintext, aad)
if !bytes.Equal(ciphertext, stdCiphertext[:len(stdCiphertext)-4]) {
t.Fatal("did not match stdlib's ciphertext")
}
decrypted, err := gcm.Open(buffer[:0], nonce, buffer, aad)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plaintext, decrypted) {
t.Fatal("decryption yielded unexpected result")
}
}