-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert_test.go
112 lines (89 loc) · 2.39 KB
/
cert_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
package pcert
import (
"crypto"
"crypto/x509"
"crypto/x509/pkix"
"strings"
"testing"
)
func createAndParse(name string, signCert *x509.Certificate, signKey crypto.PrivateKey) (*x509.Certificate, crypto.PrivateKey, error) {
crt := NewCertificate(&CertificateOptions{
Certificate: x509.Certificate{
Subject: pkix.Name{
CommonName: name,
},
},
})
certDER, key, err := CreateCertificate(crt, signCert, signKey)
if err != nil {
return nil, nil, err
}
certPEM := Encode(certDER)
keyPEM, err := EncodeKey(key)
if err != nil {
return nil, nil, err
}
crt, err = Parse(certPEM)
if err != nil {
return nil, nil, err
}
privKey, err := ParseKey(keyPEM)
if err != nil {
return nil, nil, err
}
return crt, privKey, nil
}
func TestCreate_selfSigned(t *testing.T) {
crt, _, err := createAndParse("My Server", nil, nil)
if err != nil {
t.Fatal(err)
}
if crt.Issuer.CommonName != crt.Subject.CommonName {
t.Errorf("issuer and subject common name are not equal: subject=%s issuer=%s", crt.Subject.CommonName, crt.Issuer.CommonName)
}
}
func TestCreate_signed(t *testing.T) {
caName := "My CA"
serverName := "My Server"
caCrt, caPrivKey, err := createAndParse(caName, nil, nil)
if err != nil {
t.Fatal(err)
}
crt, _, err := createAndParse(serverName, caCrt, caPrivKey)
if err != nil {
t.Fatal(err)
}
if crt.Issuer.CommonName != caCrt.Subject.CommonName {
t.Errorf("certificate has wrong issuer: got=%s want=%s", caCrt.Subject.CommonName, crt.Issuer.CommonName)
}
}
func TestCreate_missing_key(t *testing.T) {
caName := "My CA"
serverName := "My Server"
caCrt, _, err := createAndParse(caName, nil, nil)
if err != nil {
t.Fatal(err)
}
_, _, err = createAndParse(serverName, caCrt, nil)
if err == nil {
t.Fatal("no error returned")
}
if !strings.Contains(err.Error(), "signing key cannot be nil") {
t.Fatalf("error does not contain string 'signing key cannot be nil': %s", err.Error())
}
}
func TestCreate_missing_certificate(t *testing.T) {
caName := "My CA"
serverName := "My Server"
_, caPrivKey, err := createAndParse(caName, nil, nil)
if err != nil {
t.Fatal(err)
}
_, _, err = createAndParse(serverName, nil, caPrivKey)
if err == nil {
t.Fatal("no error returned")
}
if !strings.Contains(err.Error(), "signing certificate cannot be nil") {
t.Fatalf("error does not contain string 'signing certificate cannot be nil': %s", err.Error())
}
}