Debian Codegraph @

internal/test/test_cert.go

raw
1 package test
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/x509"
8 "math/big"
9 "testing"
10 "time"
11 )
12
13 // GetTestCert returns an x509 Certificate with the provided issuingURL and signed with the provided parent certificate and key.
14 // If parentCert and parentKey are nil, the certificate will be self-signed.
15 func GetTestCert(t *testing.T, issuingURL []string, parentCert *x509.Certificate, parentKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey) {
16 t.Helper()
17
18 certKey, _ := rsa.GenerateKey(rand.Reader, 2048)
19
20 template := &x509.Certificate{
21 SerialNumber: big.NewInt(1),
22 NotBefore: time.Now(),
23 NotAfter: time.Now().AddDate(10, 0, 0),
24 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
25 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
26 BasicConstraintsValid: true,
27 IsCA: true,
28 MaxPathLenZero: true,
29 IssuingCertificateURL: issuingURL,
30 }
31
32 if parentCert == nil && parentKey == nil {
33 parentCert = template
34 parentKey = certKey
35 }
36
37 certBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, certKey.Public(), parentKey)
38 if err != nil {
39 t.Fatalf("Unable to create test certificate: %v", err)
40 }
41
42 cert, err := x509.ParseCertificate(certBytes)
43 if err != nil {
44 t.Fatalf("Unable to parse test certificate: %v", err)
45 }
46
47 return cert, certKey
48 }
49
50 // GetTestCertForKey returns an x509 Certificate for the provided public key.
51 // The certificate is self-signed by a newly generated key.
52 func GetTestCertForKey(t *testing.T, pubKey crypto.PublicKey) *x509.Certificate {
53 t.Helper()
54
55 priv, err := rsa.GenerateKey(rand.Reader, 2048)
56 if err != nil {
57 t.Fatalf("failed to generate signing key: %v", err)
58 }
59 template := &x509.Certificate{
60 SerialNumber: big.NewInt(1),
61 NotBefore: time.Now(),
62 NotAfter: time.Now().Add(time.Hour),
63 }
64 certBytes, err := x509.CreateCertificate(rand.Reader, template, template, pubKey, priv)
65 if err != nil {
66 t.Fatalf("failed to create certificate: %v", err)
67 }
68 cert, err := x509.ParseCertificate(certBytes)
69 if err != nil {
70 t.Fatalf("failed to parse certificate: %v", err)
71 }
72 return cert
73 }