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

89 lines
2.2 KiB
Go

8 months ago
package cert
import (
2 months ago
"crypto/rand"
8 months ago
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"net"
"os"
)
2 months ago
func GenerateCsr(country, province, city, org, orgUnit, name string, dnsName []string) *x509.CertificateRequest {
8 months ago
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)
}
2 months ago
/*
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()),
8 months ago
Subject: pkix.Name{
Country: s2s(country),
Province: s2s(province),
Locality: s2s(city),
Organization: s2s((org)),
OrganizationalUnit: s2s(orgUnit),
CommonName: name,
},
2 months ago
DNSNames: trueDNS,
IPAddresses: trueIp,
//NotBefore: start,
//NotAfter: end,
//BasicConstraintsValid: true,
//IsCA: isCa,
//MaxPathLen: maxPathLen,
//MaxPathLenZero: maxPathLenZero,
//KeyUsage: ku,
//ExtKeyUsage: []x509.ExtKeyUsage{eku},
8 months ago
}
}
2 months ago
func outputCsr(csr *x509.CertificateRequest, priv interface{}) []byte {
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csr, priv)
if err != nil {
return nil
}
8 months ago
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
2 months ago
Bytes: csrBytes,
8 months ago
})
}
func s2s(str string) []string {
if len(str) == 0 {
return nil
}
return []string{str}
}
2 months ago
func LoadCsr(csrPath string) (*x509.CertificateRequest, error) {
8 months ago
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")
}
2 months ago
cert, err := x509.ParseCertificateRequest(block.Bytes)
8 months ago
if err != nil {
return nil, err
}
return cert, nil
}