github.com/letsencrypt/boulder@v0.20251208.0/test/certs.go (about) 1 package test 2 3 import ( 4 "bytes" 5 "crypto/ecdsa" 6 "crypto/elliptic" 7 "crypto/rand" 8 "crypto/x509" 9 "encoding/hex" 10 "fmt" 11 "math/big" 12 "net" 13 "testing" 14 "time" 15 16 "github.com/jmhodges/clock" 17 ) 18 19 // ThrowAwayCert is a small test helper function that creates a self-signed 20 // certificate with one SAN. It returns the parsed certificate and its serial 21 // in string form for convenience. 22 // The certificate returned from this function is the bare minimum needed for 23 // most tests and isn't a robust example of a complete end entity certificate. 24 func ThrowAwayCert(t *testing.T, clk clock.Clock) (string, *x509.Certificate) { 25 var nameBytes [3]byte 26 _, _ = rand.Read(nameBytes[:]) 27 name := fmt.Sprintf("%s.example.com", hex.EncodeToString(nameBytes[:])) 28 29 // Generate a random IPv6 address under the RFC 3849 space. 30 // https://www.rfc-editor.org/rfc/rfc3849.txt 31 var ipBytes [12]byte 32 _, _ = rand.Read(ipBytes[:]) 33 ipPrefix, _ := hex.DecodeString("20010db8") 34 ip := net.IP(bytes.Join([][]byte{ipPrefix, ipBytes[:]}, nil)) 35 36 var serialBytes [16]byte 37 _, _ = rand.Read(serialBytes[:]) 38 serial := big.NewInt(0).SetBytes(serialBytes[:]) 39 40 key, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) 41 AssertNotError(t, err, "rsa.GenerateKey failed") 42 43 template := &x509.Certificate{ 44 SerialNumber: serial, 45 DNSNames: []string{name}, 46 IPAddresses: []net.IP{ip}, 47 NotBefore: clk.Now(), 48 NotAfter: clk.Now().Add(6 * 24 * time.Hour), 49 IssuingCertificateURL: []string{"http://localhost:4001/issuer/1234/cert"}, 50 CRLDistributionPoints: []string{"http://localhost:4002/issuer/1234/crl/1"}, 51 } 52 53 testCertDER, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) 54 AssertNotError(t, err, "x509.CreateCertificate failed") 55 testCert, err := x509.ParseCertificate(testCertDER) 56 AssertNotError(t, err, "failed to parse self-signed cert DER") 57 58 return fmt.Sprintf("%036x", serial), testCert 59 }