tls.go 1.4 KB

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