pem.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package template
  13. import (
  14. "bytes"
  15. "encoding/pem"
  16. "errors"
  17. "strings"
  18. )
  19. const (
  20. errJunk = "error filtering pem: found junk"
  21. )
  22. func filterPEM(pemType, input string) (string, error) {
  23. data := []byte(input)
  24. var blocks []byte
  25. var block *pem.Block
  26. var rest []byte
  27. for {
  28. block, rest = pem.Decode(data)
  29. data = rest
  30. if block == nil {
  31. break
  32. }
  33. if !strings.EqualFold(block.Type, pemType) {
  34. continue
  35. }
  36. var buf bytes.Buffer
  37. err := pem.Encode(&buf, block)
  38. if err != nil {
  39. return "", err
  40. }
  41. blocks = append(blocks, buf.Bytes()...)
  42. }
  43. if len(blocks) == 0 && len(rest) != 0 {
  44. return "", errors.New(errJunk)
  45. }
  46. return string(blocks), nil
  47. }
  48. func pemEncode(thing, kind string) (string, error) {
  49. buf := bytes.NewBuffer(nil)
  50. err := pem.Encode(buf, &pem.Block{Type: kind, Bytes: []byte(thing)})
  51. return buf.String(), err
  52. }