certfile.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Yunion
  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 seclib2
  15. import (
  16. "crypto/rsa"
  17. "fmt"
  18. "io/ioutil"
  19. "strings"
  20. "yunion.io/x/pkg/util/seclib"
  21. )
  22. const (
  23. certBeginString = "BEGIN CERTIFICATE"
  24. )
  25. // MergeCaCertFiles concatenates cert and ca file to form a chain, write it to
  26. // a tmpfile then return the path
  27. //
  28. // Callers are responsible for removing the returned tmpfile
  29. func MergeCaCertFiles(cafile string, certfile string) (string, error) {
  30. tmpfile, err := ioutil.TempFile("", "cerfile.*.crt")
  31. if err != nil {
  32. return "", fmt.Errorf("fail to open tempfile for ca cerfile: %s", err)
  33. }
  34. defer tmpfile.Close()
  35. cont, err := ioutil.ReadFile(certfile)
  36. if err != nil {
  37. return "", fmt.Errorf("fail to read certfile %s", err)
  38. }
  39. offset := strings.Index(string(cont), certBeginString)
  40. if offset < 0 {
  41. return "", fmt.Errorf("invalid certfile, no BEGIN CERTIFICATE found")
  42. }
  43. for offset > 0 && cont[offset-1] == '-' {
  44. offset -= 1
  45. }
  46. tmpfile.Write(cont[offset:])
  47. cont, err = ioutil.ReadFile(cafile)
  48. if err != nil {
  49. return "", fmt.Errorf("fail to read cafile %s", err)
  50. }
  51. tmpfile.Write(cont)
  52. return tmpfile.Name(), nil
  53. }
  54. func CleanCertificate(cert string) string {
  55. return seclib.CleanCertificate(cert)
  56. }
  57. func DecodePrivateKey(keyString []byte) (*rsa.PrivateKey, error) {
  58. return seclib.DecodePrivateKey(keyString)
  59. }