From f577896010e1e742583d500577ce15451da1bcd4 Mon Sep 17 00:00:00 2001 From: Jeff Mitchell Date: Fri, 6 Jul 2018 10:25:32 -0400 Subject: [PATCH] Port pubkey parsing from kube-auth to helper/certutil --- helper/certutil/helpers.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/helper/certutil/helpers.go b/helper/certutil/helpers.go index 3c072cee81..7c66519428 100644 --- a/helper/certutil/helpers.go +++ b/helper/certutil/helpers.go @@ -10,6 +10,7 @@ import ( "crypto/sha1" "crypto/x509" "encoding/pem" + "errors" "fmt" "math/big" "strconv" @@ -273,3 +274,28 @@ func ComparePublicKeys(key1Iface, key2Iface crypto.PublicKey) (bool, error) { return false, fmt.Errorf("cannot compare key with type %T", key1Iface) } } + +// PasrsePublicKeyPEM is used to parse RSA and ECDSA public keys from PEMs +func ParsePublicKeyPEM(data []byte) (interface{}, error) { + block, data := pem.Decode(data) + if block != nil { + var rawKey interface{} + var err error + if rawKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + rawKey = cert.PublicKey + } else { + return nil, err + } + } + + if rsaPublicKey, ok := rawKey.(*rsa.PublicKey); ok { + return rsaPublicKey, nil + } + if ecPublicKey, ok := rawKey.(*ecdsa.PublicKey); ok { + return ecPublicKey, nil + } + } + + return nil, errors.New("data does not contain any valid RSA or ECDSA public keys") +}