pem.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cert
  14. import (
  15. "bytes"
  16. "crypto/x509"
  17. "encoding/pem"
  18. "errors"
  19. )
  20. const (
  21. // CertificateBlockType is a possible value for pem.Block.Type.
  22. CertificateBlockType = "CERTIFICATE"
  23. // CertificateRequestBlockType is a possible value for pem.Block.Type.
  24. CertificateRequestBlockType = "CERTIFICATE REQUEST"
  25. )
  26. // ParseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array
  27. // Returns an error if a certificate could not be parsed, or if the data does not contain any certificates
  28. func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) {
  29. ok := false
  30. certs := []*x509.Certificate{}
  31. for len(pemCerts) > 0 {
  32. var block *pem.Block
  33. block, pemCerts = pem.Decode(pemCerts)
  34. if block == nil {
  35. break
  36. }
  37. // Only use PEM "CERTIFICATE" blocks without extra headers
  38. if block.Type != CertificateBlockType || len(block.Headers) != 0 {
  39. continue
  40. }
  41. cert, err := x509.ParseCertificate(block.Bytes)
  42. if err != nil {
  43. return certs, err
  44. }
  45. certs = append(certs, cert)
  46. ok = true
  47. }
  48. if !ok {
  49. return certs, errors.New("data does not contain any valid RSA or ECDSA certificates")
  50. }
  51. return certs, nil
  52. }
  53. // EncodeCertificates returns the PEM-encoded byte array that represents by the specified certs.
  54. func EncodeCertificates(certs ...*x509.Certificate) ([]byte, error) {
  55. b := bytes.Buffer{}
  56. for _, cert := range certs {
  57. if err := pem.Encode(&b, &pem.Block{Type: CertificateBlockType, Bytes: cert.Raw}); err != nil {
  58. return []byte{}, err
  59. }
  60. }
  61. return b.Bytes(), nil
  62. }