1 // ucspi -- UCSPI-related utilities
2 // Copyright (C) 2021-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
25 func CertificateFromFile(p string) (b []byte, c *x509.Certificate, err error) {
27 data, err = os.ReadFile(p)
33 block, data = pem.Decode(data)
37 if block.Type == "CERTIFICATE" {
39 c, err = x509.ParseCertificate(b)
43 err = errors.New("no CERTIFICATE found in PEM")
47 func PrivateKeyFromFile(p string) (prv interface{}, err error) {
49 data, err = os.ReadFile(p)
55 block, data = pem.Decode(data)
61 prv, err = x509.ParsePKCS8PrivateKey(block.Bytes)
63 case "EC PRIVATE KEY":
64 prv, err = x509.ParseECPrivateKey(block.Bytes)
68 err = errors.New("no PRIVATE KEY found in PEM")
72 func CertPoolFromFile(p string) (certs []*x509.Certificate, pool *x509.CertPool, err error) {
74 data, err = os.ReadFile(p)
78 pool = x509.NewCertPool()
81 block, data = pem.Decode(data)
83 err = errors.New("can not decode PEM")
86 if block.Type != "CERTIFICATE" {
87 err = errors.New("non CERTIFICATE found in PEM")
90 var ca *x509.Certificate
91 ca, err = x509.ParseCertificate(block.Bytes)
95 certs = append(certs, ca)