2 ucspi -- UCSPI-related utilities
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 func CertificateFromFile(p string) (b []byte, c *x509.Certificate, err error) {
29 data, err = ioutil.ReadFile(p)
35 block, data = pem.Decode(data)
39 if block.Type == "CERTIFICATE" {
41 c, err = x509.ParseCertificate(b)
45 err = errors.New("no CERTIFICATE found in PEM")
49 func PrivateKeyFromFile(p string) (prv interface{}, err error) {
51 data, err = ioutil.ReadFile(p)
57 block, data = pem.Decode(data)
63 prv, err = x509.ParsePKCS8PrivateKey(block.Bytes)
65 case "EC PRIVATE KEY":
66 prv, err = x509.ParseECPrivateKey(block.Bytes)
70 err = errors.New("no PRIVATE KEY found in PEM")
74 func CertPoolFromFile(p string) (certs []*x509.Certificate, pool *x509.CertPool, err error) {
76 data, err = ioutil.ReadFile(p)
80 pool = x509.NewCertPool()
83 block, data = pem.Decode(data)
85 err = errors.New("can not decode PEM")
88 if block.Type != "CERTIFICATE" {
89 err = errors.New("non CERTIFICATE found in PEM")
92 var ca *x509.Certificate
93 ca, err = x509.ParseCertificate(block.Bytes)
97 certs = append(certs, ca)