1 | package fasthttp
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "crypto/rand"
|
---|
5 | "crypto/rsa"
|
---|
6 | "crypto/x509"
|
---|
7 | "crypto/x509/pkix"
|
---|
8 | "encoding/pem"
|
---|
9 | "math/big"
|
---|
10 | "time"
|
---|
11 | )
|
---|
12 |
|
---|
13 | // GenerateTestCertificate generates a test certificate and private key based on the given host.
|
---|
14 | func GenerateTestCertificate(host string) ([]byte, []byte, error) {
|
---|
15 | priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
---|
16 | if err != nil {
|
---|
17 | return nil, nil, err
|
---|
18 | }
|
---|
19 |
|
---|
20 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
---|
21 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
---|
22 | if err != nil {
|
---|
23 | return nil, nil, err
|
---|
24 | }
|
---|
25 |
|
---|
26 | cert := &x509.Certificate{
|
---|
27 | SerialNumber: serialNumber,
|
---|
28 | Subject: pkix.Name{
|
---|
29 | Organization: []string{"fasthttp test"},
|
---|
30 | },
|
---|
31 | NotBefore: time.Now(),
|
---|
32 | NotAfter: time.Now().Add(365 * 24 * time.Hour),
|
---|
33 | KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
|
---|
34 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
---|
35 | SignatureAlgorithm: x509.SHA256WithRSA,
|
---|
36 | DNSNames: []string{host},
|
---|
37 | BasicConstraintsValid: true,
|
---|
38 | IsCA: true,
|
---|
39 | }
|
---|
40 |
|
---|
41 | certBytes, err := x509.CreateCertificate(
|
---|
42 | rand.Reader, cert, cert, &priv.PublicKey, priv,
|
---|
43 | )
|
---|
44 |
|
---|
45 | p := pem.EncodeToMemory(
|
---|
46 | &pem.Block{
|
---|
47 | Type: "PRIVATE KEY",
|
---|
48 | Bytes: x509.MarshalPKCS1PrivateKey(priv),
|
---|
49 | },
|
---|
50 | )
|
---|
51 |
|
---|
52 | b := pem.EncodeToMemory(
|
---|
53 | &pem.Block{
|
---|
54 | Type: "CERTIFICATE",
|
---|
55 | Bytes: certBytes,
|
---|
56 | },
|
---|
57 | )
|
---|
58 |
|
---|
59 | return b, p, err
|
---|
60 | }
|
---|