From 988fe4ed95bb12f82812fd2fe00a832670e74f18 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste PIN Date: Fri, 1 Dec 2023 07:31:18 +0100 Subject: [PATCH] Add support for PKCS8 key and non encrypted (#198) --- depot/file/depot.go | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/depot/file/depot.go b/depot/file/depot.go index ab8d336..0eb6d74 100644 --- a/depot/file/depot.go +++ b/depot/file/depot.go @@ -368,8 +368,9 @@ func (d *fileDepot) path(name string) string { } const ( - rsaPrivateKeyPEMBlockType = "RSA PRIVATE KEY" - certificatePEMBlockType = "CERTIFICATE" + rsaPrivateKeyPEMBlockType = "RSA PRIVATE KEY" + pkcs8PrivateKeyPEMBlockType = "PRIVATE KEY" + certificatePEMBlockType = "CERTIFICATE" ) // load an encrypted private key from disk @@ -378,15 +379,33 @@ func loadKey(data []byte, password []byte) (*rsa.PrivateKey, error) { if pemBlock == nil { return nil, errors.New("PEM decode failed") } - if pemBlock.Type != rsaPrivateKeyPEMBlockType { + switch pemBlock.Type { + case rsaPrivateKeyPEMBlockType: + if x509.IsEncryptedPEMBlock(pemBlock) { + b, err := x509.DecryptPEMBlock(pemBlock, password) + if err != nil { + return nil, err + } + return x509.ParsePKCS1PrivateKey(b) + } + return x509.ParsePKCS1PrivateKey(pemBlock.Bytes) + case pkcs8PrivateKeyPEMBlockType: + priv, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes) + if err != nil { + return nil, err + } + switch priv := priv.(type) { + case *rsa.PrivateKey: + return priv, nil + // case *dsa.PublicKey: + // case *ecdsa.PublicKey: + // case ed25519.PublicKey: + default: + panic("unsupported type of public key. SCEP need RSA private key") + } + default: return nil, errors.New("unmatched type or headers") } - - b, err := x509.DecryptPEMBlock(pemBlock, password) - if err != nil { - return nil, err - } - return x509.ParsePKCS1PrivateKey(b) } // load an encrypted private key from disk