From 733393d80016ed17e3c69d60cf8e3cce4ef328d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20K=C3=A4ldstr=C3=B6m?= Date: Tue, 3 Jan 2017 23:36:23 +0200 Subject: [PATCH] Add a PrivateKeyFromFile method to certutil for parsing a private key from a file --- pkg/util/cert/io.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/pkg/util/cert/io.go b/pkg/util/cert/io.go index 2b6201fc30..c2bde8efdd 100644 --- a/pkg/util/cert/io.go +++ b/pkg/util/cert/io.go @@ -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 +}