Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2014 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package cert |
| 18 | |
| 19 | import ( |
| 20 | "crypto/x509" |
| 21 | "encoding/pem" |
| 22 | "errors" |
| 23 | ) |
| 24 | |
| 25 | const ( |
| 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 |
| 34 | func 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 | } |