1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
// Copyright (c) 2022, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package cli
import (
"bytes"
"crypto/x509"
"encoding/pem"
"errors"
"os"
)
var errFailedToDecodePEM = errors.New("failed to decode PEM")
// loadCertificate returns the certificate read from path.
func loadCertificate(path string) (*x509.Certificate, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
p, _ := pem.Decode(b)
if p == nil {
return nil, errFailedToDecodePEM
}
return x509.ParseCertificate(p.Bytes)
}
// loadCertificatePool returns the pool of certificates read from path.
func loadCertificatePool(path string) (*x509.CertPool, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
for rest := bytes.TrimSpace(b); len(rest) > 0; {
var p *pem.Block
if p, rest = pem.Decode(rest); p == nil {
return nil, errFailedToDecodePEM
}
c, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return nil, err
}
pool.AddCert(c)
}
return pool, nil
}
|