-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile.go
98 lines (87 loc) · 2.53 KB
/
profile.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 pcert
import (
"crypto/x509"
"crypto/x509/pkix"
)
const (
defaultKeyUsage = x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature
)
// NewClientCertificate returns a new certificate. The CommonName is set to name
// and typical client certificate settings are set (see SetClientProfile function).
func NewClientCertificate(name string) *x509.Certificate {
cert := NewCertificate(&CertificateOptions{
Certificate: x509.Certificate{
Subject: pkix.Name{
CommonName: name,
},
},
})
SetClientProfile(cert)
return cert
}
// NewServerCertificate returns a new certificate. The CommonName is set to name
// and typical server certificate settings are set (see SetServerProfile function).
func NewServerCertificate(name string) *x509.Certificate {
cert := NewCertificate(&CertificateOptions{
Certificate: x509.Certificate{
Subject: pkix.Name{
CommonName: name,
},
},
})
SetServerProfile(cert)
return cert
}
// NewCACertificate returns a new certificate. The CommonName is set to name and
// typical CA certificate settings are set (see SetCAProfile function).
func NewCACertificate(name string) *x509.Certificate {
cert := NewCertificate(&CertificateOptions{
Certificate: x509.Certificate{
Subject: pkix.Name{
CommonName: name,
},
},
})
SetCAProfile(cert)
return cert
}
// SetServerProfile sets typical characteristics of a server certificate.
func SetServerProfile(cert *x509.Certificate) {
present := false
for _, dns := range cert.DNSNames {
if dns == cert.Subject.CommonName {
present = true
break
}
}
if !present {
cert.DNSNames = append(cert.DNSNames, cert.Subject.CommonName)
}
addExtKeyUsage(cert, x509.ExtKeyUsageServerAuth)
addExtKeyUsage(cert, x509.ExtKeyUsageClientAuth)
cert.BasicConstraintsValid = true
cert.IsCA = false
cert.KeyUsage |= defaultKeyUsage
}
// SetCAProfile sets typical characteristics of a CA certificate.
func SetCAProfile(cert *x509.Certificate) {
cert.ExtKeyUsage = nil
cert.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
cert.BasicConstraintsValid = true
cert.IsCA = true
}
// SetClientProfile sets typical characteristics of a client certificate.
func SetClientProfile(cert *x509.Certificate) {
addExtKeyUsage(cert, x509.ExtKeyUsageClientAuth)
cert.BasicConstraintsValid = true
cert.IsCA = false
cert.KeyUsage |= defaultKeyUsage
}
func addExtKeyUsage(cert *x509.Certificate, newUsage x509.ExtKeyUsage) {
for _, eku := range cert.ExtKeyUsage {
if eku == newUsage {
return
}
}
cert.ExtKeyUsage = append(cert.ExtKeyUsage, newUsage)
}