72 lines
2.1 KiB
Go
72 lines
2.1 KiB
Go
package test
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/ecdsa"
|
||
|
|
"crypto/elliptic"
|
||
|
|
"crypto/rand"
|
||
|
|
"crypto/x509"
|
||
|
|
"crypto/x509/pkix"
|
||
|
|
"encoding/pem"
|
||
|
|
"fmt"
|
||
|
|
"log"
|
||
|
|
"math/big"
|
||
|
|
"os"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
// UnsafeSelfSignedCertificates creates a pair of test certificates in the given test folder
|
||
|
|
func UnsafeSelfSignedCertificates(testfolder string) (privateKeyPath string, publicKeyPath string) {
|
||
|
|
privateKeyPath = fmt.Sprintf("%s/cert.key", testfolder)
|
||
|
|
publicKeyPath = fmt.Sprintf("%s/cert.pem", testfolder)
|
||
|
|
|
||
|
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to generatekey: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
template := x509.Certificate{
|
||
|
|
SerialNumber: big.NewInt(1234),
|
||
|
|
Subject: pkix.Name{
|
||
|
|
Organization: []string{"Gatus test"},
|
||
|
|
},
|
||
|
|
NotBefore: time.Now(),
|
||
|
|
NotAfter: time.Now().Add(time.Hour * 24),
|
||
|
|
KeyUsage: x509.KeyUsageDigitalSignature,
|
||
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||
|
|
BasicConstraintsValid: true,
|
||
|
|
DNSNames: []string{"localhost"},
|
||
|
|
}
|
||
|
|
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to create certificate: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
certOut, err := os.Create(publicKeyPath)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to open cert.pem for writing: %v", err)
|
||
|
|
}
|
||
|
|
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
|
||
|
|
log.Fatalf("Failed to write data to cert.pem: %v", err)
|
||
|
|
}
|
||
|
|
if err := certOut.Close(); err != nil {
|
||
|
|
log.Fatalf("Error closing cert.pem: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
keyOut, err := os.OpenFile(privateKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to open %s for writing: %v", privateKeyPath, err)
|
||
|
|
}
|
||
|
|
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Unable to marshal private key: %v", err)
|
||
|
|
}
|
||
|
|
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
|
||
|
|
log.Fatalf("Failed to write data to key.pem: %v", err)
|
||
|
|
}
|
||
|
|
if err := keyOut.Close(); err != nil {
|
||
|
|
log.Fatalf("Error closing key.pem: %v", err)
|
||
|
|
}
|
||
|
|
log.Print("wrote key.pem\n")
|
||
|
|
|
||
|
|
return
|
||
|
|
}
|