Add a PrivateKeyFromFile method to certutil for parsing a private key from a file

pull/6/head
Lucas Käldström 2017-01-03 23:36:23 +02:00
parent 7f9056dd07
commit 733393d800
No known key found for this signature in database
GPG Key ID: 3FA3783D77751514
1 changed files with 14 additions and 4 deletions

View File

@ -18,7 +18,6 @@ package cert
import (
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"os"
@ -104,9 +103,6 @@ func NewPool(filename string) (*x509.CertPool, error) {
// CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.
// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
func CertsFromFile(file string) ([]*x509.Certificate, error) {
if len(file) == 0 {
return nil, errors.New("error reading certificates from an empty filename")
}
pemBlock, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
@ -117,3 +113,17 @@ func CertsFromFile(file string) ([]*x509.Certificate, error) {
}
return certs, nil
}
// PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.
// Returns an error if the file could not be read or if the private key could not be parsed.
func PrivateKeyFromFile(file string) (interface{}, error) {
pemBlock, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err := ParsePrivateKeyPEM(pemBlock)
if err != nil {
return nil, fmt.Errorf("error reading %s: %v", file, err)
}
return key, nil
}