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

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