|
|
|
package cert
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/x509"
|
|
|
|
"crypto/x509/pkix"
|
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
func GenerateCsr(country, province, city, org, orgUnit, name string, dnsName []string) *x509.CertificateRequest {
|
|
|
|
var trueDNS []string
|
|
|
|
var trueIp []net.IP
|
|
|
|
for _, v := range dnsName {
|
|
|
|
ip := net.ParseIP(v)
|
|
|
|
if ip == nil {
|
|
|
|
trueDNS = append(trueDNS, v)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
trueIp = append(trueIp, ip)
|
|
|
|
}
|
|
|
|
/*
|
|
|
|
ku := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment
|
|
|
|
eku := x509.ExtKeyUsageServerAuth
|
|
|
|
if isCa {
|
|
|
|
ku = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature
|
|
|
|
eku = x509.ExtKeyUsageAny
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
return &x509.CertificateRequest{
|
|
|
|
Version: 3,
|
|
|
|
//SerialNumber: big.NewInt(time.Now().Unix()),
|
|
|
|
Subject: pkix.Name{
|
|
|
|
Country: s2s(country),
|
|
|
|
Province: s2s(province),
|
|
|
|
Locality: s2s(city),
|
|
|
|
Organization: s2s((org)),
|
|
|
|
OrganizationalUnit: s2s(orgUnit),
|
|
|
|
CommonName: name,
|
|
|
|
},
|
|
|
|
DNSNames: trueDNS,
|
|
|
|
IPAddresses: trueIp,
|
|
|
|
//NotBefore: start,
|
|
|
|
//NotAfter: end,
|
|
|
|
//BasicConstraintsValid: true,
|
|
|
|
//IsCA: isCa,
|
|
|
|
//MaxPathLen: maxPathLen,
|
|
|
|
//MaxPathLenZero: maxPathLenZero,
|
|
|
|
//KeyUsage: ku,
|
|
|
|
//ExtKeyUsage: []x509.ExtKeyUsage{eku},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func outputCsr(csr *x509.CertificateRequest, priv interface{}) []byte {
|
|
|
|
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csr, priv)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return pem.EncodeToMemory(&pem.Block{
|
|
|
|
Type: "CERTIFICATE REQUEST",
|
|
|
|
Bytes: csrBytes,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func s2s(str string) []string {
|
|
|
|
if len(str) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return []string{str}
|
|
|
|
}
|
|
|
|
|
|
|
|
func LoadCsr(csrPath string) (*x509.CertificateRequest, error) {
|
|
|
|
csrBytes, err := os.ReadFile(csrPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
block, _ := pem.Decode(csrBytes)
|
|
|
|
if block == nil || block.Type != "CERTIFICATE REQUEST" {
|
|
|
|
return nil, errors.New("Failed to decode PEM block containing the certificate")
|
|
|
|
}
|
|
|
|
cert, err := x509.ParseCertificateRequest(block.Bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return cert, nil
|
|
|
|
}
|