-
Notifications
You must be signed in to change notification settings - Fork 8
/
tls_test.go
100 lines (75 loc) · 2.17 KB
/
tls_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
package amqprpc
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTLS(t *testing.T) {
tempCert, tempKey := createCertificateFiles()
defer func() {
os.Remove(tempCert)
os.Remove(tempKey)
}()
c := Certificates{tempCert, tempKey, tempCert}
assert.Contains(t, c.Cert, ".pem", "certificate defined")
cfg := c.TLSConfig()
require.NotNil(t, cfg, "config is not nil")
assert.NotNil(t, cfg.RootCAs, "root CAs exist")
assert.Len(t, cfg.Certificates, 1, "one certificate parsed")
c = Certificates{}
cfg = c.TLSConfig()
assert.NotNil(t, cfg, "successfully generate TLSConfig")
assert.Empty(t, cfg.Certificates, "no certificates for empty config")
}
func createPrivKey(priv *rsa.PrivateKey) string {
f, err := os.CreateTemp(".", "priv*.key")
if err != nil {
panic(err)
}
defer f.Close()
privateKey := &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}
_ = pem.Encode(f, privateKey)
return f.Name()
}
func createCertificate(priv *rsa.PrivateKey, pub rsa.PublicKey) string {
f, _ := os.CreateTemp(".", "pub*.pem")
defer f.Close()
cert := &x509.Certificate{
SerialNumber: big.NewInt(1653),
Subject: pkix.Name{
Organization: []string{"UNIT-TESTER"},
Country: []string{"SE"},
Locality: []string{"Stockholm"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
certificate, _ := x509.CreateCertificate(rand.Reader, cert, cert, &pub, priv)
certFile := &pem.Block{
Type: "CERTIFICATE",
Bytes: certificate,
}
_ = pem.Encode(f, certFile)
return f.Name()
}
func createCertificateFiles() (tempCert, tempKey string) {
key, _ := rsa.GenerateKey(rand.Reader, 2048)
tempKey = createPrivKey(key)
tempCert = createCertificate(key, key.PublicKey)
return tempCert, tempKey
}