You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
star/cert/csr.go

84 lines
2.1 KiB
Go

8 months ago
package cert
import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"net"
"os"
"time"
)
func GenerateCsr(country, province, city, org, orgUnit, name string, dnsName []string, start, end time.Time, isCa bool, maxPathLenZero bool, maxPathLen int) *x509.Certificate {
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.Certificate{
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.Certificate) []byte {
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr.Raw,
})
}
func s2s(str string) []string {
if len(str) == 0 {
return nil
}
return []string{str}
}
func LoadCsr(csrPath string) (*x509.Certificate, 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.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return cert, nil
}