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/ca.go

65 lines
1.5 KiB
Go

package cert
import (
"b612.me/starcrypto"
"crypto"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"errors"
"os"
)
func MakeCert(caKey any, caCrt *x509.Certificate, csr *x509.Certificate, pub any) ([]byte, error) {
der, err := x509.CreateCertificate(rand.Reader, csr, caCrt, pub, caKey)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
certBlock := &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
}
pemData := pem.EncodeToMemory(certBlock)
return pemData, nil
}
func LoadCA(caKeyPath, caCertPath, KeyPwd string) (crypto.PrivateKey, *x509.Certificate, error) {
caKeyBytes, err := os.ReadFile(caKeyPath)
if err != nil {
return nil, nil, err
}
caCertBytes, err := os.ReadFile(caCertPath)
if err != nil {
return nil, nil, err
}
caKey, err := starcrypto.DecodePrivateKey(caKeyBytes, KeyPwd)
if err != nil {
return nil, nil, err
}
block, _ := pem.Decode(caCertBytes)
if block == nil || (block.Type != "CERTIFICATE" && block.Type != "CERTIFICATE REQUEST") {
return nil, nil, errors.New("Failed to decode PEM block containing the certificate")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, err
}
return caKey, cert, nil
}
func LoadPriv(caKeyPath, KeyPwd string) (crypto.PrivateKey, error) {
caKeyBytes, err := os.ReadFile(caKeyPath)
if err != nil {
return nil, err
}
caKey, err := starcrypto.DecodePrivateKey(caKeyBytes, KeyPwd)
if err != nil {
return nil, err
}
return caKey, nil
}