-
Notifications
You must be signed in to change notification settings - Fork 3
/
crypto.go
87 lines (72 loc) · 2.25 KB
/
crypto.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
package est
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"github.com/fullsailor/pkcs7"
)
// PKCS7ToPEM converts PKCS7 formatted data to PEM formatted data.
func PKCS7ToPEM(data []byte) ([]byte, error) {
var d []byte
prefix := []byte{'-', '-', '-', '-', '-', 'B', 'E', 'G', 'I', 'N'}
if bytes.HasPrefix(data, prefix) {
result, _ := pem.Decode([]byte(data))
d = result.Bytes
} else {
d = data
}
p7, err := pkcs7.Parse(d)
if err != nil {
return nil, err
}
var certsPem []byte
for _, cert := range p7.Certificates {
block := pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
}
certsPem = append(certsPem, pem.EncodeToMemory(&block)...)
}
return certsPem, err
}
// CreateCsr generates a key pair, creates a CSR and returns the private key
// and CSR in PEM format.
func CreateCsr(commonName string, country string, state string, city string,
organization string, organizationalUnit string,
emailAddress string) ([]byte, []byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
template := x509.CertificateRequest{
Subject: pkix.Name{
CommonName: commonName,
Country: []string{country},
Province: []string{state},
Locality: []string{city},
Organization: []string{organization},
OrganizationalUnit: []string{organizationalUnit},
},
SignatureAlgorithm: x509.SHA256WithRSA,
EmailAddresses: []string{emailAddress},
}
random := rand.Reader
csrBytes, err := x509.CreateCertificateRequest(random, &template, priv)
if err != nil {
return nil, nil, err
}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrBytes,
}
certPem := pem.EncodeToMemory(&block)
block = pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}
privPem := pem.EncodeToMemory(&block)
return privPem, certPem, nil
}