-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto_test.go
98 lines (84 loc) · 2.01 KB
/
crypto_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
package main
import (
"path/filepath"
"testing"
)
func TestGetKey(t *testing.T) {
key, err := GetKey(filepath.Join("testdata", "key_file"))
if err != nil {
t.Error(err)
}
if len(key) != 32 {
t.Errorf("GetKey should returns 32 byte, but got %v", len(key))
}
}
func TestGetKeyWithFileNotExist(t *testing.T) {
_, err := GetKey(filepath.Join("testdata", "not_exist"))
if err == nil {
t.Error("GetKey with not exist file should rase error")
}
}
func TestKeyLength(t *testing.T) {
k1 := GenKey([]byte("short string"))
k2 := GenKey([]byte("abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789"))
if len(k1) != 32 {
t.Errorf("GenKey should returns 32 byte, but got %v", len(k1))
}
if len(k2) != 32 {
t.Errorf("GenKey should returns 32 byte, but got %v", len(k1))
}
}
func TestEncryptAndDecrypt(t *testing.T) {
key := GenKey([]byte("this is crypto key"))
pwd := "password"
e, err := Encrypt(key, []byte(pwd))
if err != nil {
t.Error(err)
}
d, err := Decrypt(key, e)
if err != nil {
t.Error(err)
}
if string(d) != pwd {
t.Errorf("Decrypt failure: %s", d)
}
}
func TestEncryptWithInvalidKey(t *testing.T) {
_, err := Encrypt([]byte("foobar"), []byte("password"))
if err == nil {
t.Error("Encrypt with invalid key should raise error")
}
}
func TestDecryptWithInvalidKey(t *testing.T) {
_, err := Decrypt([]byte("foobar"), "password")
if err == nil {
t.Error("Decrypt with invalid key should raise error")
}
}
func TestCannotDecryptWithOtherKey(t *testing.T) {
k1 := GenKey([]byte("this is crypto key"))
k2 := GenKey([]byte("this is other key"))
pwd := "password"
e, err := Encrypt(k1, []byte(pwd))
if err != nil {
t.Error(err)
}
d, err := Decrypt(k2, e)
if err != nil {
t.Error(err)
}
if string(d) == pwd {
t.Errorf("Decrypt with other key should fail")
}
}
func TestEncodeAndDecode(t *testing.T) {
data := []byte("password")
e := Encode(data)
d, err := Decode(e)
if err != nil {
t.Error(err)
}
if string(d) != "password" {
t.Error("Decorde failure")
}
}