Created
November 21, 2019 11:31
-
-
Save tngranados/470fe21e2cfb73e835eb9118d604dd31 to your computer and use it in GitHub Desktop.
Go Fake Certificate test generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package certgen | |
import ( | |
"crypto/ecdsa" | |
"crypto/elliptic" | |
"crypto/rand" | |
"crypto/x509" | |
"crypto/x509/pkix" | |
"encoding/pem" | |
"io/ioutil" | |
"math/big" | |
"testing" | |
"time" | |
"github.com/stretchr/testify/assert" | |
) | |
// generateFakeTLSCertificate this function generates a certificate and a | |
// private key and stores them in temp files, returning the paths of both files. | |
// These paths can be passed directly to the tls.LoadX509KeyPair function. | |
func genereateFakeTLSCertificate(t *testing.T) (string, string) { | |
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
assert.NoError(t, err) | |
asn1Bytes, err := x509.MarshalECPrivateKey(priv) | |
assert.NoError(t, err) | |
privBytes := pem.EncodeToMemory(&pem.Block{ | |
Type: "EC PRIVATE KEY", | |
Bytes: asn1Bytes, | |
}) | |
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) | |
assert.NoError(t, err) | |
template := x509.Certificate{ | |
SerialNumber: serialNumber, | |
Subject: pkix.Name{ | |
Organization: []string{"ACME"}, | |
}, | |
NotBefore: time.Now(), | |
NotAfter: time.Now().Add(365 * 24 * time.Hour), | |
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, | |
BasicConstraintsValid: true, | |
} | |
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv) | |
assert.NoError(t, err) | |
certBytes := pem.EncodeToMemory(&pem.Block{ | |
Type: "CERTIFICATE", | |
Bytes: derBytes, | |
}) | |
privFile, err := ioutil.TempFile("", "priv") | |
assert.NoError(t, err) | |
certFile, err := ioutil.TempFile("", "cert") | |
assert.NoError(t, err) | |
err = ioutil.WriteFile(privFile.Name(), privBytes, 0644) | |
assert.NoError(t, err) | |
err = ioutil.WriteFile(certFile.Name(), certBytes, 0644) | |
assert.NoError(t, err) | |
return certFile.Name(), privFile.Name() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment