-
Notifications
You must be signed in to change notification settings - Fork 12
/
test_util.go
78 lines (69 loc) · 2.21 KB
/
test_util.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
package certificateutil
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"time"
)
// GenerateTestCertificate creates a certificate (signed by a self-signed CA cert) for test purposes
func GenerateTestCertificate(serial int64, teamID, teamName, commonName string, expiry time.Time) (*x509.Certificate, *rsa.PrivateKey, error) {
CAtemplate := &x509.Certificate{
IsCA: true,
BasicConstraintsValid: true,
SubjectKeyId: []byte{1, 2, 3},
SerialNumber: big.NewInt(1234),
Subject: pkix.Name{
Country: []string{"US"},
Organization: []string{"Pear Worldwide Developer Relations"},
CommonName: "Pear Worldwide Developer Relations CA",
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
// see http://golang.org/pkg/crypto/x509/#KeyUsage
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
}
CAprivatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
// Self-signed certificate, parent is the template
CAcertData, err := x509.CreateCertificate(rand.Reader, CAtemplate, CAtemplate, &CAprivatekey.PublicKey, CAprivatekey)
if err != nil {
return nil, nil, err
}
CAcert, err := x509.ParseCertificate(CAcertData)
if err != nil {
return nil, nil, err
}
template := &x509.Certificate{
IsCA: true,
BasicConstraintsValid: true,
SerialNumber: big.NewInt(serial),
Subject: pkix.Name{
Country: []string{"US"},
Organization: []string{teamName},
OrganizationalUnit: []string{teamID},
CommonName: commonName,
},
NotBefore: time.Now(),
NotAfter: expiry,
// see http://golang.org/pkg/crypto/x509/#KeyUsage
KeyUsage: x509.KeyUsageDigitalSignature,
}
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
certData, err := x509.CreateCertificate(rand.Reader, template, CAcert, &privatekey.PublicKey, CAprivatekey)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(certData)
if err != nil {
return nil, nil, err
}
return cert, privatekey, nil
}