tlsutil.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package tlsutil
  15. import (
  16. "crypto/tls"
  17. "crypto/x509"
  18. "encoding/pem"
  19. "io/ioutil"
  20. )
  21. // NewCertPool creates x509 certPool with provided CA files.
  22. func NewCertPool(CAFiles []string) (*x509.CertPool, error) {
  23. certPool := x509.NewCertPool()
  24. for _, CAFile := range CAFiles {
  25. pemByte, err := ioutil.ReadFile(CAFile)
  26. if err != nil {
  27. return nil, err
  28. }
  29. for {
  30. var block *pem.Block
  31. block, pemByte = pem.Decode(pemByte)
  32. if block == nil {
  33. break
  34. }
  35. cert, err := x509.ParseCertificate(block.Bytes)
  36. if err != nil {
  37. return nil, err
  38. }
  39. certPool.AddCert(cert)
  40. }
  41. }
  42. return certPool, nil
  43. }
  44. // NewCert generates TLS cert by using the given cert,key and parse function.
  45. func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) {
  46. cert, err := ioutil.ReadFile(certfile)
  47. if err != nil {
  48. return nil, err
  49. }
  50. key, err := ioutil.ReadFile(keyfile)
  51. if err != nil {
  52. return nil, err
  53. }
  54. if parseFunc == nil {
  55. parseFunc = tls.X509KeyPair
  56. }
  57. tlsCert, err := parseFunc(cert, key)
  58. if err != nil {
  59. return nil, err
  60. }
  61. return &tlsCert, nil
  62. }