-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes_test.go
94 lines (76 loc) · 1.9 KB
/
aes_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
package crypt
import (
"crypto/rand"
"io"
math_rand "math/rand"
"testing"
)
func same(src, dst []byte) bool {
if len(src) != len(dst) {
return false
}
for i := 0; i < len(src); i++ {
if src[i] != dst[i] {
return false
}
}
return true
}
func TestAesEncryt(t *testing.T) {
key := []byte("example key 1234example key 1234")
plaintext := []byte("exampleplaintext hahaha")
ciphertext, err := AesEncrypt(plaintext, key)
if err != nil {
t.Error("Encrypt failed: %s", err)
}
decrypted, err := AesDecrypt(ciphertext, key)
if err != nil {
t.Error("Decrypt failed: %s", err)
}
if string(decrypted) != string(plaintext) {
t.Error("decrypted not the same with plaintext")
}
if !same(decrypted, plaintext) {
t.Error("not the same")
}
}
func TestWrongKey(t *testing.T) {
key := []byte("example key 1234example key 1234")
plaintext := []byte("exampleplaintext")
ciphertext, err := AesEncrypt(plaintext, key)
if err != nil {
t.Error("Encrypt failed: %s", err)
}
other_key := []byte("example key 1234example key 1233")
decrypted, err := AesDecrypt(ciphertext, other_key)
if err != nil {
t.Log("Decrypt failed, but that's expected: ", err)
}
if same(decrypted, plaintext) {
t.Error("the same with wrong key")
}
}
func TestAes(t *testing.T) {
key := make([]byte, 16)
for i := 0; i < 100; i++ {
rand_size := math_rand.Int()%255 + 1
plaintext := make([]byte, rand_size)
if _, err := io.ReadFull(rand.Reader, plaintext); err != nil {
t.Error("plaintext create failed: ", i, err)
}
if _, err := io.ReadFull(rand.Reader, key); err != nil {
t.Error("key create failed: ", i, err)
}
ciphertext, err := AesEncrypt(plaintext, key)
if err != nil {
t.Error("AesEncrypt failed: ", i, err)
}
decrypted, err := AesDecrypt(ciphertext, key)
if err != nil {
t.Error("AesDecrypt failed: ", i, err)
}
if !same(decrypted, plaintext) {
t.Error("not the same: ", i)
}
}
}