-
Notifications
You must be signed in to change notification settings - Fork 315
/
x509.go
61 lines (56 loc) · 1.36 KB
/
x509.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
package certificate
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
)
func GeneratePrivateKey() ([]byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
return derStream, nil
}
func CreateClientCertificateRequest(userName string, key []byte, org ...string) ([]byte, error) {
privateKey, err := x509.ParsePKCS1PrivateKey(key)
if err != nil {
return nil, err
}
subj := pkix.Name{
CommonName: userName,
}
for i := range org {
subj.Organization = append(subj.Organization, org[i])
}
rawSubj := subj.ToRDNSequence()
asn1Subj, err := asn1.Marshal(rawSubj)
if err != nil {
return nil, err
}
csr := &x509.CertificateRequest{
RawSubject: asn1Subj,
SignatureAlgorithm: x509.SHA256WithRSA,
}
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csr, privateKey)
if err != nil {
return nil, err
}
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes})
return pemBytes, nil
}
func ParseX509Certificate(certPem []byte) (*x509.Certificate, error) {
b, _ := pem.Decode(certPem)
if b == nil {
return nil, errors.New("can not decode pem block")
}
c, err := x509.ParseCertificate(b.Bytes)
if err != nil {
return nil, err
}
return c, nil
}