HAOJX

代码自动签发证书

字数统计: 326阅读时长: 1 min
2022/01/05 Share
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
func GenK8sUser(cn,o string) {
caCert,caPriKey:= parseK8sCA(CAFILE,CAKEY)
if cn == "" {
goft.Error(fmt.Errorf("CN is required"))
}

//构建证书模板
certTemplate := &x509.Certificate{
SerialNumber: big.NewInt(rd.Int63()), //证书序列号
Subject: pkix.Name{
Country: []string{"CN"},
Organization: []string{o},
//OrganizationalUnit: []string{"可填课不填"},
Province: []string{"beijing"},
CommonName: cn,
Locality: []string{"beijing"},
},
NotBefore: time.Now(),//证书有效期开始时间
NotAfter: time.Now().AddDate(1, 0, 0),//证书有效期
BasicConstraintsValid: true, //基本的有效性约束
IsCA: false, //是否是根证书
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, //证书用途(客户端认证,数据加密)
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageDataEncipherment,
EmailAddresses: []string{"UserAccount@example.com"},
}

//生成公私钥--秘钥对
priKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return
}
//创建证书 对象
clientCert, err := x509.CreateCertificate(rand.Reader, certTemplate, caCert, &priKey.PublicKey, caPriKey)
if err != nil {
return
}

//编码证书文件和私钥文件
clientCertPem := &pem.Block{
Type: "CERTIFICATE",
Bytes: clientCert,
}

//certName:= fmt.Sprintf("./test/certs/%s.pem",cn)
certName:= fmt.Sprintf("./k8susers/%s.pem",cn)

clientCertFile, err := os.OpenFile(certName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatal(err)
}
err = pem.Encode(clientCertFile, clientCertPem)
if err != nil {
log.Fatal(err)
}

buf := x509.MarshalPKCS1PrivateKey(priKey)
keyPem := &pem.Block{
Type: "PRIVATE KEY",
Bytes: buf,
}

//certKeyName:= fmt.Sprintf("./test/certs/%s_key.pem",cn)
certKeyName:= fmt.Sprintf("./k8susers/%s_key.pem",cn)
clientKeyFile, _ := os.OpenFile(certKeyName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)

err = pem.Encode(clientKeyFile, keyPem)
if err != nil {
log.Fatal(err)
}

}
CATALOG