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