Debian Codegraph @

testutil/certificates.go

raw symbols SCIP
1 package testutil
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/x509"
7 "crypto/x509/pkix"
8 "math/big"
9 "time"
10 )
11
12 // GenerateTrustCA generates a new certificate authority for testing.
13 func GenerateTrustCA(pub crypto.PublicKey, priv crypto.PrivateKey) (*x509.Certificate, error) {
14 cert := &x509.Certificate{
15 SerialNumber: big.NewInt(0),
16 Subject: pkix.Name{
17 CommonName: "CA Root",
18 },
19 NotBefore: time.Now().Add(-time.Second),
20 NotAfter: time.Now().Add(time.Hour),
21 IsCA: true,
22 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
23 BasicConstraintsValid: true,
24 }
25
26 certDER, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, priv)
27 if err != nil {
28 return nil, err
29 }
30
31 cert, err = x509.ParseCertificate(certDER)
32 if err != nil {
33 return nil, err
34 }
35
36 return cert, nil
37 }
38
39 // GenerateIntermediate generates an intermediate certificate for testing using
40 // the parent certificate (likely a CA) and the provided keys.
41 func GenerateIntermediate(key crypto.PublicKey, parentKey crypto.PrivateKey, parent *x509.Certificate) (*x509.Certificate, error) {
42 cert := &x509.Certificate{
43 SerialNumber: big.NewInt(0),
44 Subject: pkix.Name{
45 CommonName: "Intermediate",
46 },
47 NotBefore: time.Now().Add(-time.Second),
48 NotAfter: time.Now().Add(time.Hour),
49 IsCA: true,
50 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
51 BasicConstraintsValid: true,
52 }
53
54 certDER, err := x509.CreateCertificate(rand.Reader, cert, parent, key, parentKey)
55 if err != nil {
56 return nil, err
57 }
58
59 cert, err = x509.ParseCertificate(certDER)
60 if err != nil {
61 return nil, err
62 }
63
64 return cert, nil
65 }
66
67 // GenerateTrustCert generates a new trust certificate for testing. Unlike the
68 // intermediate certificates, this certificate should be used for signature
69 // only, not creating certificates.
70 func GenerateTrustCert(key crypto.PublicKey, parentKey crypto.PrivateKey, parent *x509.Certificate) (*x509.Certificate, error) {
71 cert := &x509.Certificate{
72 SerialNumber: big.NewInt(0),
73 Subject: pkix.Name{
74 CommonName: "Trust Cert",
75 },
76 NotBefore: time.Now().Add(-time.Second),
77 NotAfter: time.Now().Add(time.Hour),
78 IsCA: true,
79 KeyUsage: x509.KeyUsageDigitalSignature,
80 BasicConstraintsValid: true,
81 }
82
83 certDER, err := x509.CreateCertificate(rand.Reader, cert, parent, key, parentKey)
84 if err != nil {
85 return nil, err
86 }
87
88 cert, err = x509.ParseCertificate(certDER)
89 if err != nil {
90 return nil, err
91 }
92
93 return cert, nil
94 }