cert.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package testdata
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "io/ioutil"
  7. "path"
  8. "runtime"
  9. )
  10. var certPath string
  11. func init() {
  12. _, filename, _, ok := runtime.Caller(0)
  13. if !ok {
  14. panic("Failed to get current frame")
  15. }
  16. certPath = path.Dir(filename)
  17. }
  18. // GetCertificatePaths returns the paths to certificate and key
  19. func GetCertificatePaths() (string, string) {
  20. return path.Join(certPath, "cert.pem"), path.Join(certPath, "priv.key")
  21. }
  22. // GetTLSConfig returns a tls config for quic.clemente.io
  23. func GetTLSConfig() *tls.Config {
  24. cert, err := tls.LoadX509KeyPair(GetCertificatePaths())
  25. if err != nil {
  26. panic(err)
  27. }
  28. return &tls.Config{
  29. Certificates: []tls.Certificate{cert},
  30. }
  31. }
  32. // GetRootCA returns an x509.CertPool containing the CA certificate
  33. func GetRootCA() *x509.CertPool {
  34. caCertPath := path.Join(certPath, "ca.pem")
  35. caCertRaw, err := ioutil.ReadFile(caCertPath)
  36. if err != nil {
  37. panic(err)
  38. }
  39. p, _ := pem.Decode(caCertRaw)
  40. if p.Type != "CERTIFICATE" {
  41. panic("expected a certificate")
  42. }
  43. caCert, err := x509.ParseCertificate(p.Bytes)
  44. if err != nil {
  45. panic(err)
  46. }
  47. certPool := x509.NewCertPool()
  48. certPool.AddCert(caCert)
  49. return certPool
  50. }