gmifs/gemini/gencert.go

51 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-07-07 15:54:22 +03:00
package gemini
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
2021-07-08 16:44:18 +03:00
"fmt"
2021-07-07 15:54:22 +03:00
"math/big"
"time"
)
2021-07-08 16:44:18 +03:00
const rsaBits = 2048
2021-07-07 15:54:22 +03:00
// GenX509KeyPair generates a TLS keypair with one week validity.
2021-07-08 16:16:17 +03:00
func GenX509KeyPair(host string, daysvalid int) (tls.Certificate, error) {
2021-07-07 15:54:22 +03:00
now := time.Now()
template := &x509.Certificate{
SerialNumber: big.NewInt(now.Unix()),
Subject: pkix.Name{
CommonName: host,
Organization: []string{host},
},
NotBefore: now,
2021-07-08 16:16:17 +03:00
NotAfter: now.AddDate(0, 0, daysvalid),
2021-07-07 15:54:22 +03:00
BasicConstraintsValid: true,
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageKeyEncipherment |
x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
}
2021-07-08 16:44:18 +03:00
priv, err := rsa.GenerateKey(rand.Reader, rsaBits)
2021-07-07 15:54:22 +03:00
if err != nil {
2021-07-08 16:44:18 +03:00
return tls.Certificate{}, fmt.Errorf("generate key: %w", err)
2021-07-07 15:54:22 +03:00
}
cert, err := x509.CreateCertificate(rand.Reader, template, template,
priv.Public(), priv)
if err != nil {
2021-07-08 16:44:18 +03:00
return tls.Certificate{}, fmt.Errorf("create certificate: %w", err)
2021-07-07 15:54:22 +03:00
}
var out tls.Certificate
out.Certificate = append(out.Certificate, cert)
out.PrivateKey = priv
return out, nil
}