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.
53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
10 months ago
|
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
|
||
|
}
|