castor/certificates/certificates.go

98 lines
2.7 KiB
Go

package certificates
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"strings"
"time"
)
func GenerateKeyPair(host string) (*rsa.PrivateKey, []byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return &rsa.PrivateKey{}, []byte{}, err
}
keyUsage := x509.KeyUsageDigitalSignature
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365 * 5) // five yearss
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return &rsa.PrivateKey{}, []byte{}, err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Castor Server"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
bytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return &rsa.PrivateKey{}, []byte{}, err
}
return priv, bytes, nil
}
func TestCertificateExists(certname, keyname string) error {
_, err := os.Stat(certname)
if err != nil {
return fmt.Errorf("Could not open %s; %w", certname, err)
}
_, err = os.Stat(keyname)
if err != nil {
return fmt.Errorf("Could not open %s; %w", keyname, err)
}
return nil
}
func WriteCertsToFile(certname, keyname string, cert []byte, privkey *rsa.PrivateKey) error {
certOut, err := os.Create(certname)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %w", certname, err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return fmt.Errorf("Failed to write data to %s: %w", certname, err)
}
if err := certOut.Close(); err != nil {
return fmt.Errorf("Error closing %s: %w", certname, err)
}
keyOut, err := os.OpenFile(keyname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %w", keyname, err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(privkey)
if err != nil {
return fmt.Errorf("Unable to marshal private key: %v", err)
}
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
return fmt.Errorf("Failed to write data to %s: %v", keyname, err)
}
if err := keyOut.Close(); err != nil {
return fmt.Errorf("Error closing %s: %v", keyname, err)
}
return nil
}