-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto_aead_test.go
73 lines (63 loc) · 1.72 KB
/
crypto_aead_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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha512"
"log"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/pbkdf2"
)
func TestAesGcm(t *testing.T) {
var (
key = pbkdf2.Key([]byte("pwd"), randomBytes(16), 1<<16, 256/8, sha512.New)
plaintext = []byte("hello aes-256-gcm")
nonce, ciphertext []byte
)
block, err := aes.NewCipher(key)
if err != nil {
t.Fatal(err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
t.Fatal(err)
}
nonce = randomBytes(aead.NonceSize())
ciphertext = aead.Seal(nil, nonce, plaintext, nil)
t.Run("decrypt", func(t *testing.T) {
dec, err := aead.Open(nil, nonce, ciphertext, nil)
assert.NoError(t, err)
assert.Equal(t, dec, plaintext)
})
t.Run("modify-ciphertext", func(t *testing.T) {
_enc := sliceCopy(ciphertext)
_enc[0] += 1
_, err := aead.Open(nil, nonce, _enc, nil)
assert.EqualError(t, err, "cipher: message authentication failed")
})
}
func TestChacha20Poly1305(t *testing.T) {
var (
key = randomBytes(chacha20poly1305.KeySize)
nonce = randomBytes(chacha20poly1305.NonceSize)
plaintext = []byte("Hello, Chacha20-ploy1305")
ciphertext []byte
)
aead, err := chacha20poly1305.New(key)
if err != nil {
log.Fatalln(err)
}
ciphertext = aead.Seal(nil, nonce, plaintext, nil)
t.Run("decrypt", func(t *testing.T) {
res, err := aead.Open(nil, nonce, ciphertext, nil)
assert.NoError(t, err)
assert.Equal(t, res, plaintext)
})
t.Run("modify-ciphertext", func(t *testing.T) {
_enc := sliceCopy(ciphertext)
_enc[0] += 1
_, err := aead.Open(nil, nonce, _enc, nil)
assert.EqualError(t, err, "chacha20poly1305: message authentication failed")
})
}