-
Notifications
You must be signed in to change notification settings - Fork 25
/
make.go
127 lines (104 loc) · 3.07 KB
/
make.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package ca
import (
"net"
"time"
"math/big"
"math/rand"
"crypto/x509"
"crypto/x509/pkix"
)
// 生成证书请求
func (this CA) MakeCSR(
country []string,
organization []string,
organizationalUnit []string,
locality []string,
province []string,
streetAddress []string,
postalCode []string,
commonName string,
) CA {
this.certRequest = &x509.CertificateRequest{
Subject: pkix.Name{
Country: country,
Organization: organization,
OrganizationalUnit: organizationalUnit,
Locality: locality,
Province: province,
StreetAddress: streetAddress,
PostalCode: postalCode,
CommonName: commonName,
// SerialNumber: string,
// Names: []pkix.AttributeTypeAndValue{}
// ExtraNames: []pkix.AttributeTypeAndValue{}
},
}
return this
}
// 生成 CA 证书
func (this CA) MakeCA(
subject *pkix.Name,
expire int,
signAlgName string,
) CA {
signAlg := this.GetSignatureAlgorithm(signAlgName)
this.cert = &x509.Certificate{
SerialNumber: big.NewInt(rand.Int63n(time.Now().Unix())),
Subject: *subject,
// 生效时间
NotBefore: time.Now(),
// 过期时间,年为单位
NotAfter: time.Now().AddDate(expire, 0, 0),
// openssl 中的 extendedKeyUsage = clientAuth, serverAuth 字段
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
// openssl 中的 keyUsage 字段
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
// 表示用于CA
IsCA: true,
BasicConstraintsValid: true,
// 签名方式
SignatureAlgorithm: signAlg,
}
return this
}
// 生成自签名证书
func (this CA) MakeCert(
subject *pkix.Name,
expire int,
dns []string,
ip []net.IP,
signAlgName string,
) CA {
signAlg := this.GetSignatureAlgorithm(signAlgName)
this.cert = &x509.Certificate{
SerialNumber: big.NewInt(rand.Int63n(time.Now().Unix())),
Subject: *subject,
SubjectKeyId: []byte{1, 2, 3, 4, 6},
IPAddresses: ip,
DNSNames: dns,
NotBefore: time.Now(),
// 过期时间,年为单位
NotAfter: time.Now().AddDate(expire, 0, 0),
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature,
// 签名方式
SignatureAlgorithm: signAlg,
}
return this
}
// 更新 Cert 数据
func (this CA) UpdateCert(fn func(*x509.Certificate) *x509.Certificate) CA {
this.cert = fn(this.cert.(*x509.Certificate))
return this
}
// 更新证书请求数据
func (this CA) UpdateCertRequest(fn func(*x509.CertificateRequest) *x509.CertificateRequest) CA {
this.certRequest = fn(this.certRequest.(*x509.CertificateRequest))
return this
}