cert.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package cert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "github.com/lf-edge/ekuiper/internal/conf"
  6. "io/ioutil"
  7. )
  8. type TlsConfigurationOptions struct {
  9. SkipCertVerify bool
  10. CertFile string
  11. KeyFile string
  12. CaFile string
  13. }
  14. func GenerateTLSForClient(
  15. Opts TlsConfigurationOptions) (*tls.Config, error) {
  16. tlsConfig := &tls.Config{
  17. InsecureSkipVerify: Opts.SkipCertVerify,
  18. }
  19. if len(Opts.CertFile) <= 0 && len(Opts.KeyFile) <= 0 {
  20. tlsConfig.Certificates = nil
  21. } else {
  22. if cert, err := certLoader(Opts.CertFile, Opts.KeyFile); err != nil {
  23. return nil, err
  24. } else {
  25. tlsConfig.Certificates = []tls.Certificate{cert}
  26. }
  27. }
  28. if len(Opts.CaFile) > 0 {
  29. root, err := caLoader(Opts.CaFile)
  30. if err != nil {
  31. return nil, err
  32. }
  33. tlsConfig.RootCAs = root
  34. }
  35. return tlsConfig, nil
  36. }
  37. func certLoader(certFilePath, keyFilePath string) (tls.Certificate, error) {
  38. if cp, err := conf.ProcessPath(certFilePath); err == nil {
  39. if kp, err1 := conf.ProcessPath(keyFilePath); err1 == nil {
  40. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  41. return tls.Certificate{}, err2
  42. } else {
  43. return cer, nil
  44. }
  45. } else {
  46. return tls.Certificate{}, err1
  47. }
  48. } else {
  49. return tls.Certificate{}, err
  50. }
  51. }
  52. func caLoader(caFilePath string) (*x509.CertPool, error) {
  53. if cp, err := conf.ProcessPath(caFilePath); err == nil {
  54. pool := x509.NewCertPool()
  55. caCrt, err1 := ioutil.ReadFile(cp)
  56. if err1 != nil {
  57. return nil, err1
  58. }
  59. pool.AppendCertsFromPEM(caCrt)
  60. return pool, err1
  61. } else {
  62. return nil, err
  63. }
  64. }