forked from kleopatra999/go-encrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt_test.go
67 lines (60 loc) · 1.51 KB
/
encrypt_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
package encrypt
import (
"bytes"
"crypto/rand"
"fmt"
"testing"
)
const (
testAESDataLength = 1 << 10
testRSADataLength = 1 << 5
)
func TestAES(t *testing.T) {
key, err := GenerateAESKey(AES256Bits)
if err != nil {
t.Fatal(err)
}
fmt.Printf("AES key is %s, length %d\n", key, len(key))
transformer, err := NewAESTransformer(key)
if err != nil {
t.Fatal(err)
}
testAll(t, transformer, testAESDataLength)
}
func TestRSA(t *testing.T) {
publicKey, privateKey, err := GenerateRSAKeys(RSA2048Bits)
if err != nil {
t.Fatal(err)
}
fmt.Printf("RSA public key is %s\nRSA private key is %s\n", publicKey, privateKey)
transformer, err := NewRSATransformer(privateKey)
if err != nil {
t.Fatal(err)
}
testAll(t, transformer, testRSADataLength)
}
func testAll(t *testing.T, transformer Transformer, randomDataLength int) {
testTransform(t, transformer, []byte("hello"))
testRandom(t, transformer, randomDataLength)
}
func testRandom(t *testing.T, transformer Transformer, dataLength int) {
expected := make([]byte, dataLength)
if _, err := rand.Read(expected); err != nil {
t.Fatal(err)
}
testTransform(t, transformer, expected)
}
func testTransform(t *testing.T, transformer Transformer, expected []byte) {
encrypted, err := transformer.Encrypt(expected)
if err != nil {
t.Fatal(err)
}
fmt.Printf("encrypted is %s\n", string(encrypted))
actual, err := transformer.Decrypt(encrypted)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(expected, actual) {
t.Errorf("expected %v, got %v", expected, actual)
}
}