57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package aux509
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"math/big"
|
|
"time"
|
|
)
|
|
|
|
func GenerateCAPair(orgName, commonName string) (string, string, error) {
|
|
var err error
|
|
var crtPem string
|
|
var keyPem string
|
|
now := time.Now()
|
|
|
|
const yearsAfter int = 10
|
|
const keySize int = 2048
|
|
|
|
key, err := rsa.GenerateKey(rand.Reader, keySize)
|
|
if err != nil {
|
|
err := fmt.Errorf("Can't create a private key: %w", err)
|
|
return crtPem, keyPem, err
|
|
}
|
|
keyPemBlock := pem.Block{
|
|
Type: "RSA PRIVATE KEY",
|
|
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
|
}
|
|
keyPem = string(pem.EncodeToMemory(&keyPemBlock))
|
|
|
|
tml := x509.Certificate{
|
|
SerialNumber: big.NewInt(now.Unix()),
|
|
NotBefore: now,
|
|
NotAfter: now.AddDate(yearsAfter, 0, 0),
|
|
Subject: pkix.Name{
|
|
CommonName: commonName,
|
|
Organization: []string{orgName},
|
|
},
|
|
BasicConstraintsValid: true,
|
|
}
|
|
certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
|
|
if err != nil {
|
|
return crtPem, keyPem, fmt.Errorf("Can't create a certificate: %w", err)
|
|
}
|
|
|
|
certPemBlock := pem.Block{
|
|
Type: "CERTIFICATE",
|
|
Bytes: certBytes,
|
|
}
|
|
certPem := string(pem.EncodeToMemory(&certPemBlock))
|
|
|
|
return certPem, keyPem, err
|
|
}
|