/
convert_keypair_pkcs12.go
79 lines (66 loc) · 1.86 KB
/
convert_keypair_pkcs12.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
package rsa
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"software.sslmate.com/src/go-pkcs12"
"time"
)
func (r *FastRSA) ConvertKeyPairToPKCS12(privateKey, certificate, password string) (string, error) {
privateKeyCertKeyBase, err := r.readPrivateKey(privateKey)
if err != nil {
return "", err
}
privateKeyCert := privateKeyCertKeyBase
var certificateBytes []byte
if certificate == "" {
certificateBytes, err = createDefaultCertificate(privateKeyCert)
if err != nil {
return "", err
}
} else {
certificateBlock, _ := pem.Decode([]byte(certificate))
certificateBytes = certificateBlock.Bytes
}
certificateCert, err := x509.ParseCertificate(certificateBytes)
if err != nil {
return "", err
}
encoded, err := pkcs12.Encode(rand.Reader, privateKeyCert, certificateCert, nil, password)
if err != nil {
return "", err
}
output, err := encodeToPEMBase64(encoded)
if err != nil {
return "", err
}
return string(output), nil
}
func createDefaultCertificate(privateKeyCert *rsa.PrivateKey) ([]byte, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365)
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{""},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certificateCreated, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKeyCert.PublicKey, privateKeyCert)
if err != nil {
return nil, err
}
return certificateCreated, nil
}