Matteo Scandolo | a428586 | 2020-12-01 18:10:10 -0800 | [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 | "bytes" |
| 21 | "crypto/x509" |
| 22 | "encoding/pem" |
| 23 | "errors" |
| 24 | ) |
| 25 | |
| 26 | const ( |
| 27 | // CertificateBlockType is a possible value for pem.Block.Type. |
| 28 | CertificateBlockType = "CERTIFICATE" |
| 29 | // CertificateRequestBlockType is a possible value for pem.Block.Type. |
| 30 | CertificateRequestBlockType = "CERTIFICATE REQUEST" |
| 31 | ) |
| 32 | |
| 33 | // ParseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array |
| 34 | // Returns an error if a certificate could not be parsed, or if the data does not contain any certificates |
| 35 | func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) { |
| 36 | ok := false |
| 37 | certs := []*x509.Certificate{} |
| 38 | for len(pemCerts) > 0 { |
| 39 | var block *pem.Block |
| 40 | block, pemCerts = pem.Decode(pemCerts) |
| 41 | if block == nil { |
| 42 | break |
| 43 | } |
| 44 | // Only use PEM "CERTIFICATE" blocks without extra headers |
| 45 | if block.Type != CertificateBlockType || len(block.Headers) != 0 { |
| 46 | continue |
| 47 | } |
| 48 | |
| 49 | cert, err := x509.ParseCertificate(block.Bytes) |
| 50 | if err != nil { |
| 51 | return certs, err |
| 52 | } |
| 53 | |
| 54 | certs = append(certs, cert) |
| 55 | ok = true |
| 56 | } |
| 57 | |
| 58 | if !ok { |
| 59 | return certs, errors.New("data does not contain any valid RSA or ECDSA certificates") |
| 60 | } |
| 61 | return certs, nil |
| 62 | } |
| 63 | |
| 64 | // EncodeCertificates returns the PEM-encoded byte array that represents by the specified certs. |
| 65 | func EncodeCertificates(certs ...*x509.Certificate) ([]byte, error) { |
| 66 | b := bytes.Buffer{} |
| 67 | for _, cert := range certs { |
| 68 | if err := pem.Encode(&b, &pem.Block{Type: CertificateBlockType, Bytes: cert.Raw}); err != nil { |
| 69 | return []byte{}, err |
| 70 | } |
| 71 | } |
| 72 | return b.Bytes(), nil |
| 73 | } |