fix pkcs8 vs pkcs1 vs pkcs EC private key parsing

This commit is contained in:
Andrew Martinez
2023-07-28 10:36:31 -04:00
parent 9f0da4b97b
commit 1bc8bcbee6
3 changed files with 34 additions and 12 deletions
+20 -2
View File
@@ -21,6 +21,7 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
@@ -200,10 +201,27 @@ func generateCert(options *verifyCaOptions, token string) ([]byte, crypto.Signer
}
var signerInterface crypto.Signer
if caPrivateKeyBlock.Type == "EC PRIVATE KEY" {
switch caPrivateKeyBlock.Type {
case "EC PRIVATE KEY":
signerInterface, err = x509.ParseECPrivateKey(caPrivateKeyBlock.Bytes)
} else {
case "RSA PRIVATE KEY":
signerInterface, err = x509.ParsePKCS1PrivateKey(caPrivateKeyBlock.Bytes)
case "PRIVATE KEY":
key, err := x509.ParsePKCS8PrivateKey(caPrivateKeyBlock.Bytes)
if err != nil {
return nil, nil, fmt.Errorf("could not parse PKCS8 key file (%s)", err)
}
switch typedKey := key.(type) {
case *rsa.PrivateKey:
signerInterface = typedKey
case *ecdsa.PrivateKey:
signerInterface = typedKey
default:
return nil, nil, fmt.Errorf("unsupported private key parsed from PKCS8 %T", typedKey)
}
}
if err != nil {
@@ -229,6 +229,8 @@ func loadPrivateKey(file string) (crypto.PrivateKey, error) {
return x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(keyBlock.Bytes)
case "PRIVATE KEY":
return x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
}
return nil, errors.New("unknown private key type")
+12 -10
View File
@@ -18,8 +18,6 @@ package store
import (
"bufio"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
@@ -188,17 +186,21 @@ func (l *Local) writeKey(caName, name, pemType string, key []byte) error {
}
func getPkPemType(key []byte) string {
parsedKey, _ := x509.ParsePKCS8PrivateKey(key)
var pkcs1Err error
_, pkcs1Err = x509.ParsePKCS1PrivateKey(key)
keyPemType := "UNKNOWN PRIVATE KEY"
switch parsedKey.(type) {
case *rsa.PrivateKey:
keyPemType = "RSA PRIVATE KEY"
case *ecdsa.PrivateKey:
keyPemType = "EC PRIVATE KEY"
if pkcs1Err == nil {
return "RSA PRIVATE KEY"
}
return keyPemType
var pkcsEcErr error
_, pkcsEcErr = x509.ParseECPrivateKey(key)
if pkcsEcErr == nil {
return "EC PRIVATE KEY"
}
return "PRIVATE KEY"
}
// writeBundle encodes in PEM format the bundle private key and