/* ucspi -- UCSPI-related utilities Copyright (C) 2021 Sergey Matveev This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package ucspi import ( "crypto/x509" "encoding/pem" "errors" "io/ioutil" ) func CertificateFromFile(p string) (b []byte, c *x509.Certificate, err error) { var data []byte data, err = ioutil.ReadFile(p) if err != nil { return } block, data := pem.Decode(data) if block == nil { err = errors.New("can not decode PEM") return } if block.Type != "CERTIFICATE" { err = errors.New("non CERTIFICATE found in PEM") return } b = block.Bytes c, err = x509.ParseCertificate(b) return } func PrivateKeyFromFile(p string) (prv interface{}, err error) { var data []byte data, err = ioutil.ReadFile(p) if err != nil { return } block, data := pem.Decode(data) if block == nil { err = errors.New("can not decode PEM") return } data = block.Bytes switch block.Type { case "PRIVATE KEY": prv, err = x509.ParsePKCS8PrivateKey(data) case "EC PRIVATE KEY": prv, err = x509.ParseECPrivateKey(data) default: err = errors.New("non PRIVATE KEY found in PEM") } return } func CertPoolFromFile(p string) (pool *x509.CertPool, err error) { var data []byte data, err = ioutil.ReadFile(p) if err != nil { return } pool = x509.NewCertPool() var block *pem.Block for len(data) > 0 { block, data = pem.Decode(data) if block == nil { err = errors.New("can not decode PEM") return } if block.Type != "CERTIFICATE" { err = errors.New("non CERTIFICATE found in PEM") return } var ca *x509.Certificate ca, err = x509.ParseCertificate(block.Bytes) if err != nil { return } pool.AddCert(ca) } return }